内核准备
内核配置
建议从源代码重新编译内核,这样可以更方便地进行源代码级调试;当然自己从发行版官网下载相应内核的调试符号亦可以,通常情况下只用于应急分析,比如crash dump分析等。
自己编译Linux内核的话,最好打开两个选项:
CONFIG_DEBUG_INFO=y
CONFIG_GDB_SCRIPTS=y
可通过make menuconfig来设置内核配置项,分别以5.12及6.1.0为例:
5.12:
6.1.0:

禁止编译优化
无法针对Linux内核禁止全局优化,但可以针对特定的源代码文件做禁止编译优化的处理,可通过以下方式达成:
在需要被调试的源代码文件头部增加下面一行代码:
#pragma GCC optimize ("O0")
或者修改其对应的Makefile,以文件名core.c为例:
CFLAGS_REMOVE_core.o := -O2
CFLAGS_core.o := -O0
镜像准备
建议通过libvirt来管理本地KVM虚拟机,这样使用起来非常方便,如果条件不允许的话亦可用qemu命令行方式来运行。
添加 gdb stub
下面的示例是以命令行方式来运行调试目标:
qemu-system-x86_64 -m 4096 -nographic -net user,hostfwd=tcp::44334-:22 -net nic -hda \
debian-10.7.qcow2 -machine type=pc,accel=kvm -cpu host -smp 4 -gdb tcp:127.0.0.1:44333
“-gdb tcp:127.0.0.1:44333” 就是gdb stub的命令行参数,即gdb可连接localhost:44333来调试目标系统。
如果使用libvirt的话则需要修改QEMU配置,可通过命令virsh edit来进行修改,需要在末尾加上中间4行:
</devices>
<qemu:commandline>
<qemu:arg value='-gdb'/>
<qemu:arg value='tcp:localhost:44333'/>
</qemu:commandline>
</domain>
另外还需要更改虚拟机配置文件的domain type,即将第一行从
<domain type='kvm'>
改为:
<domain type='kvm' xmlns:qemu='http://libvirt.org/schemas/domain/qemu/1.0'>
修改内核启动项
本步骤主要为了禁止内核地址随机化,不然内核符号无法定位并正确绑定。可通过修改grub项完成,在安装新内核过程中会自加增加nokaslr及nopti,当然在编译内核时亦可直接禁止相应功能亦可。
root@T490:~# cat /etc/default/grub | grep nokaslr
GRUB_CMDLINE_LINUX_DEFAULT="noquiet nopti nokaslr console=ttyS0"
最直接的方式就是直接修改/boot/grub/grub.cfg文件,或者在系统启动时手工编译grub启动项亦可:
root@T490:~# cat /boot/grub/grub.cfg | grep nokaslr
linux /boot/vmlinuz-5.10.14 root=UUID=c4072cd3-9ed9-4376-b85c-95d1306e817b ro noquiet nopti nokaslr console=ttyS0,115200
host端准备
前面我们就完成了guest端即调试目标机的配置,然后就是准备host端,可以用gdb,亦可以用vscode等gui工具,甚至可以用Windows Visual Studio配合VisualKernel工具来调试Linux系统。
源代码及调试符号vmlinux
将相应源代码及调试符号vmlinux复制到host端即可,复制时注意软链接问题,比如:
vmlinux-gdb.py -> /BUILD/linux-5.12/scripts/gdb/vmlinux-gdb.py
设置gdb的auto-load路径
建议直接修改 ~/.gdbinit文件,当然手动执行亦可,当处理多个调试机时最好通过.gdbinit来保存配置:
matt@T490 /W/K/debian-10.7> cat ~/.gdbinit
add-auto-load-safe-path /usr/share/gdb/python/gdb/
add-auto-load-safe-path /usr/share/gdb/python/
add-auto-load-safe-path /usr/share/gdb/
add-auto-load-safe-path /BUILD/linux-5.12
set auto-load python-scripts on
source /BUILD/pwndbg/gdbinit.py
我本地的调试环境里安装的是pwndbg,已配置好了python组件
启动gdb
cd /BUILD/linux-5.12; gdb ./vmlinux
在gdb中执行以下执行开启内核调试:
target remote :44333
然后gdb会自动加载pwndbg并中断目标机:

在内核gdb scripts加载成功的情况下可以执行lx系列扩展命令以获取内核信息:

可通过apropos lx查询相应的gdb scripts扩展命令,如lx-lsmod, 变量:$lx_current():
gdb> apropos lx
function lx_clk_core_lookup -- Find struct clk_core by name
function lx_current -- Return current task.
function lx_device_find_by_bus_name -- Find struct device by bus and name (both strings)
function lx_device_find_by_class_name -- Find struct device by class and name (both strings)
function lx_module -- Find module by name and return the module variable.
function lx_per_cpu -- Return per-cpu variable.
function lx_rb_first -- Lookup and return a node from an RBTree
function lx_rb_last -- Lookup and return a node from an RBTree.
function lx_rb_next -- Lookup and return a node from an RBTree.
function lx_rb_prev -- Lookup and return a node from an RBTree.
function lx_task_by_pid -- Find Linux task by PID and return the task_struct variable.
function lx_thread_info -- Calculate Linux thread_info from task variable.
function lx_thread_info_by_pid -- Calculate Linux thread_info from task variable found by pid
lx-clk-summary -- Print clk tree summary
lx-cmdline -- Report the Linux Commandline used in the current kernel.
lx-configdump -- Output kernel config to the filename specified as the command
lx-cpus -- List CPU status arrays
lx-device-list-bus -- Print devices on a bus (or all buses if not specified)
lx-device-list-class -- Print devices in a class (or all classes if not specified)
lx-device-list-tree -- Print a device and its children recursively
lx-dmesg -- Print Linux kernel log buffer.
lx-fdtdump -- Output Flattened Device Tree header and dump FDT blob to the filename
lx-genpd-summary -- Print genpd summary
lx-iomem -- Identify the IO memory resource locations defined by the kernel
lx-ioports -- Identify the IO port resource locations defined by the kernel
lx-list-check -- Verify a list consistency
lx-lsmod -- List currently loaded modules.
lx-mounts -- Report the VFS mounts of the current process namespace.
lx-ps -- Dump Linux tasks.
lx-symbols -- (Re-)load symbols of Linux kernel and currently loaded modules.
lx-timerlist -- Print /proc/timer_list
lx-version -- Report the Linux Version of the current kernel.

gdb常用命令及调试技巧
常用命令
常用gdb指令:bt, disass, step, next, break/delete, print, x/[i/g/d]等,具体可查询gdb命令手册
断点设置
使用break命令可设置断点,支持以下几种命令格式:
- break 函数名: break dump_stack
- break source_file:line_number: break smith_hook.c:70
- break 逻辑地址:break 0xffffffff81003010,可以强制break跳过符号/函数名识别
针对模块的调试,可以考虑在模块中增加不常用内核函数的调用,如dump_stack;模块加载前是无法设置断点的,但内核函数的调用是可以的,这样就可以在模块调用指定内核函数时触发断点,然后再通过add-symbol-file /path_to/ko_file base_address,base_address或通过lx-lsmod查询得到,即模块在内核中的内存位置,之后就可以访问模块内的符号了,如全局变量或内部函数
X86_64位环境调试32位虚拟机
需要在attach前设置目标及当前系统架构,如 set architecture i386:x86-64。建议安装gdb-multiarch,以免系统自带gdb不支持多种架构:
pwndbg> target remote :44323
Remote debugging using :44323
warning: Selected architecture i386 is not compatible with reported target architecture i386:x86-64
warning: Architecture rejected target-supplied description
Remote 'g' packet reply is too long (expected 312 bytes, got 608 bytes): 102b91c10......0000
pwndbg> set architecture i386:x86-64
The target architecture is set to "i386:x86-64".
pwndbg> target remote :44323
Remote debugging using :44323
0x00000000c1912b23 in default_idle () at arch/x86/kernel
кэшбэк 1win https://1win26514.help/
ставки на спорт, новости спорта, прогнозы и
https://bkradar.com/guides читайте подробнее про ставки и букмекеров на bkradar.com
pin-up şəxsiyyət təsdiqi pin-up şəxsiyyət təsdiqi
Hey I am so glad I found your webpage, I really found you by error, while I was searching on Google for something else, Anyways I am here now and would just like to say thanks a lot for a tremendous post and a all round enjoyable blog (I also love the theme/design), I don’t have time to read it all at the minute but I have book-marked it and also added your RSS feeds, so when I have time I will be back to read a great deal more, Please do keep up the fantastic job.
best online casino slots for real money
Hi there to every body, it’s my first pay a visit of this weblog; this blog consists of awesome and genuinely fine material in favor of readers.
在线购买他达拉非片用于肛交XXX色情
Pretty section of content. I just stumbled upon your blog and in accession capital to assert that I get in fact enjoyed account your blog posts. Anyway I will be subscribing to your augment and even I achievement you access consistently rapidly.
new online slots casino
Hi, its pleasant article about media print, we all be familiar with media is a fantastic source of information.
Watch sexual porno video xxx sex adults site
download mostbet apk http://mostbet94827.help/
запасной адрес mostbet https://www.mostbet15384.help
1вин вход без регистрации http://1win59801.help/
Right now it appears like Movable Type is the preferred blogging platform out there right now. (from what I’ve read) Is that what you’re using on your blog?
在线购买无处方安定片 xxx Pornhub
ставки на спорт, новости спорта, прогнозы и
виды спорта для ставок читайте подробнее про ставки и букмекеров на bkradar.com
Отдельного внимания требуют случаи, когда больной почти не ест, плохо пьет воду, не может спокойно лежать, жалуется на сильное сердцебиение, нехватку сна или выраженное внутреннее напряжение. В такой ситуации осмотр помогает определить, безопасно ли оставаться дома и какого объема помощи достаточно на текущем этапе. Если речь идет о выраженных проявлениях абстинентного синдрома, затягивать с обращением нецелесообразно.
Изучить вопрос глубже – врач нарколог на дом
Hey I know this is off topic but I was wondering if you knew of any widgets I could add to my blog that automatically tweet my newest twitter updates. I’ve been looking for a plug-in like this for quite some time and was hoping maybe you would have some experience with something like this. Please let me know if you run into anything. I truly enjoy reading your blog and I look forward to your new updates.
Watch sexual porno video xxx sex adults site
ставки на спорт, новости спорта, прогнозы и
рейтинг бк читайте подробнее про ставки и букмекеров на bkradar.com
Heya superb blog! Does running a blog like this require a lot of work? I’ve no expertise in coding but I had been hoping to start my own blog soon. Anyhow, if you have any ideas or tips for new blog owners please share. I know this is off subject nevertheless I simply had to ask. Many thanks!
在线购买无处方安定片 xxx Pornhub
Do you have a spam issue on this website; I also am a blogger, and I was wanting to know your situation; we have developed some nice methods and we are looking to swap strategies with other folks, be sure to shoot me an email if interested.
Xxx video onlyfans sex video site
1вин app бехатар http://1win26514.help/
1win мобильная версия https://1win68503.help/
pin-up çıxarış təsdiqi https://www.pinup2010.help
1win обновление apk https://1win68503.help
Hello to every body, it’s my first pay a visit of this blog; this weblog includes awesome and actually good material in support of visitors.
Watch sexual porno video xxx sex adults site
1win ios версия 1win68503.help
мостбет плинко http://mostbet15384.help/
mostbet bonus calculator https://mostbet94827.help/
1вин официальный сайт вход 1вин официальный сайт вход
For the reason that the admin of this web site is working, no doubt very shortly it will be well-known, due to its quality contents.
Watch sexual porno video xxx sex adults site
Нарколог на дом в Екатеринбурге — это формат помощи, который рассматривают при состояниях после употребления алкоголя, когда больному требуется врачебный осмотр без поездки в клинику. Обычно речь идет о запое, выраженном похмельном синдроме, нарушении сна, обезвоживании, слабости, треморе, тревоге, скачках давления, сердцебиении и общем ухудшении самочувствия. Дальнейшая тактика зависит от состояния больного на момент осмотра, длительности употребления алкоголя и наличия сопутствующих заболеваний.
Разобраться лучше – https://narkolog-na-dom-ekaterinburg.ru/
Hey! This post couldn’t be written any better! Reading through this post reminds me of my good old room mate! He always kept talking about this. I will forward this post to him. Pretty sure he will have a good read. Thanks for sharing!
在线购买大麻用于XXX成人色情视频
Hey, I think your site might be having browser compatibility issues. When I look at your blog site in Ie, it looks fine but when opening in Internet Explorer, it has some overlapping. I just wanted to give you a quick heads up! Other then that, great blog!
adult xxx video porn site xxx sex video
I have fun with, result in I found just what I used to be looking for. You’ve ended my four day long hunt! God Bless you man. Have a nice day. Bye
在线购买他达拉非片用于肛交XXX色情
melbet crash играть https://www.melbet94130.help
Heya! I realize this is somewhat off-topic however I had to ask. Does running a well-established website such as yours take a large amount of work? I’m brand new to blogging but I do write in my diary everyday. I’d like to start a blog so I can share my experience and views online. Please let me know if you have any kind of suggestions or tips for brand new aspiring blog owners. Thankyou!
Watch sexual porno video xxx sex adults site
Wow, fantastic blog layout! How long have you been blogging for? you made blogging look easy. The overall look of your web site is great, as well as the content!
adult xxx video porn site xxx sex video
melbet lucky jet игра https://www.melbet94130.help
Howdy this is kinda of off topic but I was wanting to know if blogs use WYSIWYG editors or if you have to manually code with HTML. I’m starting a blog soon but have no coding know-how so I wanted to get guidance from someone with experience. Any help would be greatly appreciated!
Xxx video onlyfans sex video site
1win комиссия при выводе http://1win68503.help
общий баланс melbet казино и спорт https://www.melbet94130.help
mostbet loyalty bonus http://mostbet94827.help/
лаки джет мостбет mostbet15384.help
I believe everything published made a bunch of sense. But, what about this? suppose you were to write a awesome post title? I ain’t saying your information is not good., however suppose you added a post title to maybe grab folk’s attention? I mean %BLOG_TITLE% is a little plain. You could look at Yahoo’s home page and watch how they write news headlines to get people interested. You might add a related video or a related picture or two to grab readers interested about what you’ve written. In my opinion, it might make your posts a little livelier.
Watch sexual porno video xxx sex adults site
1вин бонус за регистрацию 1вин бонус за регистрацию
мелбет сабти ном бе хато https://melbet39704.help
vavada official website hr vavada official website hr
aviator reset password aviator reset password
This is the right webpage for everyone who wishes to understand this topic. You know a whole lot its almost tough to argue with you (not that I really will need to…HaHa). You definitely put a brand new spin on a subject that has been written about for many years. Wonderful stuff, just great!
在线购买无处方安定片 xxx Pornhub
An impressive share! I have just forwarded this onto a friend who had been conducting a little research on this. And he actually ordered me dinner simply because I found it for him… lol. So allow me to reword this…. Thank YOU for the meal!! But yeah, thanx for spending time to talk about this subject here on your web site.
在线购买无处方安定片 xxx Pornhub
Программы лечения выстраиваются гибко: можно начать с домашнего вызова врача и продолжить терапию в клинике, либо пройти весь курс стационарно с круглосуточным наблюдением. Главный принцип — безопасность, эффективность и уважение к личности пациента.
Детальнее – http://narcologicheskaya-clinika-v-rnd19.ru
I was able to find good information from your blog posts.
在线购买他达拉非片用于肛交XXX色情
mostbet slots tournament mostbet slots tournament