Is there a way to step into kernel code with lldb, or otherwise, on the Mac?

370 Views Asked by At

Is there a way to see the code that is being called by a syscall instruction with lldb, or otherwise, on the Mac?

I am trying to understand what goes behind the hood when a "write" syscall is called. I have compiled a simple .c program with gcc -g:

#include <unistd.h>
#include <sys/syscall.h>
int main(void) {
  syscall(SYS_write, 1, "hello, world!\n", 14);
  return 0;
}

lldb does not step into the syscall instruction even when I use: s -a false

Is there any way?

2

There are 2 best solutions below

0
On

No. If you were able to step into a kernel trap, the kernel would be stopped and the debugger would stop running as well. You can debug the kernel from a second system -- if you look for the Kernel Debug Kit on Apple's developer portal download site, there are instructions for how to do two-machine kernel debugging. The instructions are most likely aimed at people doing kernel extension (kext) development, but they'll get in you in the right ballpark.

0
On

Your best bet (short of two machines) is to run MacOS in a VM, and then attach a kernel debugger over serial. You'll need to start the VM kernel with boot-args (debug=0x44 or a bit mask of your choice), and connect lldb from the host machine. There are plentiful resources on how to do that over the web. one of the most direct and comprehensive is Scott Knight's - https://knight.sc/debugging/2018/08/15/macos-kernel-debugging.html

You can also figure it out from the code: All sys calls funnel to hndl_unix_scall64, which in turn checks the syscall/machtrap indicator (0x2000000 or 0x1000000), and then directs to unix_syscall64 (for the former), and then dispatches to actual sys call from the table. In a backtrace it would look like:

 frame #8: 0xffffff801e4ed8c3 kernel`read_nocancel + 115
 frame #9: 0xffffff801e5b62bb kernel`unix_syscall64 + 619
 frame #10: 0xffffff801df5c466 kernel`hndl_unix_scall64 + 22

Source: *OS Internals, Volume II, Chapter 4 (http://NewOSXBook.com)