ʹÓÃGDBµ÷ÊÔLinuxÄں˵ij£ÓÃÉèÖü¼ÇÉ
ʹÓÃgdbµ÷ÊÔlinuxÄں˵ij£ÓÃÉèÖü¼ÇÉ
СÐò£º
ÔÚLinux¿ª·¢ÖУ¬Ê¹ÓÃGDBµ÷ÊÔÄÚºËÊÇÒ»ÏîºÜÊÇÖ÷ÒªµÄÊÖÒÕ¡£GDBÊÇÒ»¿î¹¦Ð§Ç¿Ê¢µÄµ÷ÊÔ¹¤¾ß£¬¿ÉÒÔ×ÊÖú¿ª·¢Õß¿ìËÙ¶¨Î»Ï¢Õù¾öÄÚºËÖеÄbug¡£±¾ÎĽ«ÏÈÈÝһЩ³£ÓõÄGDBÉèÖü¼ÇÉ£¬ÒÔ¼°ÔõÑùʹÓÃGDBµ÷ÊÔLinuxÄںˡ£
Ò»¡¢ÉèÖÃGDBÇéÐÎ
Ê×ÏÈ£¬ÎÒÃÇÐèÒªÔÚLinuxϵͳÉÏÉèÖÃGDBµÄÇéÐΡ£ÇëÈ·±£ÄãµÄϵͳÒѾװÖÃÁËGDB¹¤¾ß¡£ÈôÊÇûÓÐ×°Ö㬿ÉÒÔͨ¹ýÒÔÏÂÏÂÁîÀ´×°Öãº
$ sudo apt-get install gdb
¶þ¡¢±àÒëÄÚºË
ÔÚʹÓÃGDBµ÷ÊÔÄÚºË֮ǰ£¬Ê×ÏÈÐèÒª±àÒëÄںˣ¬²¢ÌìÉúµ÷ÊÔÐÅÏ¢¡£
ÏÂÔØÄÚºËÔ´Âë
ͨ¹ýGit»òÕß¹Ù·½ÍøÕ¾ÏÂÔØÏëÒªµ÷ÊÔµÄÄÚºËÔ´Âë¡£
ÉèÖÃÄÚºË
½øÈëÄÚºËÔ´ÂëĿ¼£¬²¢Ö´ÐÐmake menuconfigÏÂÁîÀ´ÉèÖÃÄںˡ£ÔÚÕâÀÎÒÃÇÐèÒªÆôÓÃһЩµ÷ÊÔÑ¡Ïî¡£¿ÉÒÔͨ¹ýÒÔÏÂÏÂÁîÀ´ÆôÓõ÷ÊÔÑ¡Ï
$ make menuconfig
ÔÚÉèÖýçÃæÖÐÕÒµ½ÒÔÏÂÑ¡Ï²¢¾ÙÐÐÆôÓãº
Kernel hacking -> Kernel debugging -> GDB/KDB -> Enable KGDB/KDB Support
Kernel hacking -> Compile-time checks and compiler options -> Compile the kernel with debug info
ÉúÑIJ¢Í˳öÉèÖýçÃæ¡£
±àÒëÄÚºË
Ö´ÐÐÒÔÏÂÏÂÁîÀ´±àÒëÄںˣº
$ make
±àÒëÍê³Éºó£¬»áÔÚÔ´ÂëĿ¼ÏÂÌìÉúvmlinuzºÍvmlinuxÎļþ¡£
Èý¡¢ÉèÖÃÄÚºËÆô¶¯²ÎÊý
ÔÚʹÓÃGDBµ÷ÊÔÄÚºË֮ǰ£¬ÎÒÃÇ»¹ÐèÒªÔÚÄÚºËÆô¶¯Ê±Ìí¼ÓһЩ²ÎÊý¡£
ÐÞ¸ÄGRUBÎļþ
·¿ªGRUBÎļþ£¬²¢ÕÒµ½”default”±äÁ¿¡£½«ÆäÖµÐÞ¸ÄΪËùÖ§³ÖµÄÄں˰汾¡£ÀýÈ磺
default=0
ÉúÑIJ¢Í˳ö¡£
Ìí¼Óµ÷ÊÔ²ÎÊý
ÔÚGRUBÎļþÖÐÕÒµ½ËùÑ¡Ôñ°æ±¾µÄ”linux”ÐУ¬²¢ÔÚÆäĩβÌí¼Óµ÷ÊÔ²ÎÊý¡£ÀýÈ磺
linux /boot/vmlinuz-5.4.0-74-generic root=/dev/sda1 ro debug
ÉúÑIJ¢Í˳ö¡£
¸üÐÂGRUBÉèÖÃ
Ö´ÐÐÒÔÏÂÏÂÁîÀ´¸üÐÂGRUBÉèÖãº
$ sudo update-grub
ËÄ¡¢Ê¹ÓÃGDBµ÷ÊÔÄÚºË
ÏÖÔÚ£¬ÉèÖÃÒѾÍê³É£¬ÎÒÃÇ¿ÉÒÔʹÓÃGDBÀ´µ÷ÊÔLinuxÄÚºËÁË¡£
Æô¶¯GDB
·¿ªÖնˣ¬²¢Ö´ÐÐÒÔÏÂÏÂÁîÀ´Æô¶¯GDB£º
$ gdb vmlinux
ÉèÖÃGDB
ÔÚGDBÖУ¬ÎÒÃÇÐèÒª×öһЩÌØÁíÍâÉèÖá£Ö´ÐÐÒÔÏÂÏÂÁîÀ´ÉèÖÃGDB£º
É趨µ÷ÊÔÄ¿µÄ£º
(gdb) target remote :1234
É趨µ÷ÊÔ·ûºÅÎļþ£º
(gdb) symbol-file vmlinux
ÉèÖöϵ㣺
(gdb) break main
ÉúÑIJ¢Í˳ö¡£
Æô¶¯µ÷ÊԻỰ
Ö´ÐÐÒÔÏÂÏÂÁîÀ´Æô¶¯µ÷ÊԻỰ£º
(gdb) continue
´Ëʱ£¬GDB½«»áÅþÁ¬µ½Äں˵÷ÊÔÆ÷£¬²¢ÔÚmainº¯Êý´¦×èÖ¹Ö´ÐС£
¾ÙÐе÷ÊÔ
ʹÓÃGDBÌṩµÄÖÖÖÖÏÂÁîºÍµ÷ÊÔ¼¼ÇÉ£¬ÀýÈçÉó²é±äÁ¿Öµ¡¢Ð޸ıäÁ¿Öµ¡¢Éó²éº¯ÊýŲÓÿÍÕ»µÈ£¬À´¶¨Î»Ï¢Õù¾öÄÚºËÖеÄbug¡£
ÀýÈ磬¿ÉÒÔʹÓÃÒÔÏÂÏÂÁîÀ´Éó²é±äÁ¿µÄÖµ£º
(gdb) print my_variable
¿ÉÒÔʹÓÃÒÔÏÂÏÂÁîÀ´Ð޸ıäÁ¿µÄÖµ£º
(gdb) set var my_variable = 123
Îå¡¢×ܽá
±¾ÎÄÏÈÈÝÁËʹÓÃgdbµ÷ÊÔlinuxÄں˵ij£ÓÃÉèÖü¼ÇÉ¡£Ê×ÏÈ£¬ÎÒÃÇÐèÒªÔÚϵͳÉÏÉèÖÃGDBÇéÐΣ¬²¢±àÒëÄںˡ£È»ºó£¬Í¨¹ýÌí¼Óµ÷ÊÔ²ÎÊýÀ´ÉèÖÃÄÚºËÆô¶¯²ÎÊý¡£×îºó£¬Ê¹ÓÃGDBÀ´µ÷ÊÔÄںˣ¬²¢Í¨¹ýʹÓÃGDBÌṩµÄÖÖÖÖÏÂÁîºÍµ÷ÊÔ¼¼ÇÉ£¬À´¶¨Î»Ï¢Õù¾öÄÚºËÖеÄbug¡£Í¨¹ýÕÆÎÕÕâЩ¼¼ÇÉ£¬¿ª·¢Õß¿ÉÒÔÔ½·¢¸ßЧµØ¾ÙÐÐÄں˵÷ÊԺͿª·¢ÊÂÇé¡£
ÒÔÉϾÍÊÇʹÓÃGDBµ÷ÊÔLinuxÄں˵ij£ÓÃÉèÖü¼ÇɵÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡