参考1:https://pdos.csail.mit.edu/6.S081/2023/labs/gdb.html
参考2:https://pdos.csail.mit.edu/6.S081/2023/labs/guidance.html
如何调试系统上的应用程序?
很神奇的是,直接 gdb user/file.c,然后打断点就行了。应该要求文件在被编译进文件系统之前,对文件加入调试符号。
例子如下:
首先 make qemu-gdb 启动 qemu xv6
接着新开一个窗口 gdb-multiarch user/_ls
,对 main 函数打断点
再连接 qemu target remote localhost:26000
,随后 continue
可以看到 xv6 成功启动
输入 ls,触发 gdb 设置的断点
参考1中的一些调试 tips
If you get an error that says something about running file command or unknown symbol, you need to run file kernel/kernel so that gdb knows where to look to find the code you are trying to debug.
参考2中的一些调试 tips
1.C语言指针的理解:
A few common pointer idioms are particularly worth remembering:
-
If int p = (int)100, then (int)p + 1 and (int)(p + 1) are different numbers: the first is 101 but the second is 104. When adding an integer to a pointer, as in the second case, the integer is implicitly multiplied by the size of the object the pointer points to.
-
p[i] is defined to be the same as *(p+i), referring to the i'th object in the memory pointed to by p. The above rule for addition helps this definition work when the objects are larger than one byte.
-
&p[i] is the same as (p+i), yielding the address of the i'th object in the memory pointed to by p.
2.其它调试技巧
-
If the kernel causes an unexpected fault (e.g. uses an invalid memory address), it will print an error message that includes the program counter ("sepc") at the point where it crashed; you can search kernel.asm to find the function containing that program counter, or you can run addr2line -e kernel/kernel pc-value (run man addr2line for details). If you want to get backtrace, restart using gdb: run 'make qemu-gdb' in one window, run gdb (or riscv64-linux-gnu-gdb) in another window, set breakpoint in panic ('b panic'), followed by followed by 'c' (continue). When the kernel hits the break point, type 'bt' to get a backtrace. (看错误触发地址、看回溯栈)
-
If your kernel hangs, perhaps due to a deadlock, you can use gdb to find out where it is hanging. Run run 'make qemu-gdb' in one window, run gdb (riscv64-linux-gnu-gdb) in another window, followed by followed by 'c' (continue). When the kernel appears to hang hit Ctrl-C in the qemu-gdb window and type 'bt' to get a backtrace. (看回溯栈、看死循环)
-
qemu has a "monitor" that lets you query the state of the emulated machine. You can get at it by typing control-a c (the "c" is for console). A particularly useful monitor command is info mem to print the page table. You may need to use the cpu command to select which core info mem looks at, or you could start qemu with make CPUS=1 qemu to cause there to be just one core. (qemu 本身的调试工具,可以看页表)