GDB:如何查看哪些内存地址是可访问的?
假设在调试会话中我有一个不幸地指向一些垃圾的地址。我想检查它周围的记忆,看看附近有什么。正如预期的那样,出现以下错误:
(gdb) x/64 $t5
0x842da7ac: Cannot access memory at address 0x842da7ac
那么,问题是:有没有办法读取一系列地址,其中一些地址无效?
(更准确地说,我如何知道上面的示例中的 $t5+n
是某些 0
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您无法读取无效地址(显然)。
在某些操作系统上,当进程在 GDB 中停止时,您可以查询操作系统有关有效地址的信息。例如,在 Linux 上,
cat /proc//maps
将为您提供有关哪些地址有效(以及它们有效的访问模式)的信息。其他操作系统可能具有类似的机制。由于您将问题标记为事后分析,因此您无法使用上述机制;但你必须有一个
core
文件。在 Linux(和其他 ELF 系统)上,readelf -l core 会告诉您哪些内存区域被写入核心,这通常可以让您很好地了解哪些内存在崩溃时有效。但是,只读映射通常不会写入core
,因此您可能在readelf
输出中看不到此类映射。所有现代操作系统都使用分页,并且页面至少为
1K
(尽管4K
更常见),因此您可以知道最接近$t5
的内存code> 可能有效的是0x842da800
,因此n >= 84
(字节)。最后,如果你要求GDB检查64个单词,而GDB无法检查第一个单词,它就会停止。
但是,如果您使用的是 GDB-7.x,则可以要求 GDB 在 Python 中一次检查一个单词,如果 GDB 无法检查该特定单词,则会抛出 Python 异常。但既然你可以捕获Python异常,那么编写一个脚本来实现“检查接下来的N个单词,忽略任何不可读的单词”在Python中是微不足道的(我相信这回答了你的“如何做到这一点”的问题)。
You can't read invalid addresses (obviously).
On some OSes you can can query the OS about valid addresses while the process is stopped in GDB. For example, on Linux
cat /proc/<pid>/maps
will give you info about which addresses are valid (and the access mode they are valid for). Other OSes may have similar mechanism.Since you tagged your question
post-mortem
, you can't use above mechanism; but then you must have acore
file. On Linux (and otherELF
systems),readelf -l core
will tell you which regions of memory were written into the core, which usually gives you a good idea of what memory was valid at the time of crash. However, read-only mappings are usually not written tocore
, so you may not see such mappings inreadelf
output.All modern OSes use paging, and pages are at least
1K
(though4K
is more common), so you can tell that the closest memory to$t5
which could possibly be valid is0x842da800
, and son >= 84
(bytes).Finally, if you ask GDB to examine 64 words, and GDB can't examine the first one, it will stop.
However, if you are using GDB-7.x, you can ask GDB to examine one word at a time in Python, and GDB will throw Python exception if it can't examine that particular word. But since you can catch Python exceptions, it is trivial to write a script that will implement "examine next N words, ignoring any unreadable ones" in Python (which I believe answers your "how can this be done" question).