gpt4 book ai didi

python - 有人有 Linux 上 fd_set 的 gdb pretty-print 代码吗?

转载 作者:IT王子 更新时间:2023-10-29 00:34:08 26 4
gpt4 key购买 nike

现代版本的 gdb 允许集成 python 代码以“ pretty-print ”复杂的数据结构。对于 C++ 的 STL 类以及一些更常见的 boost.org 类型,有一些非常 pretty-print 实现。

在网络编程中,经常会遇到select/poll调用。 poll() 使用数据结构数组,而 select() 使用 fd_set

有没有人遇到过fd_set 的 pretty-print 实现,最好是可移植的,但即使是特定于平台的也可以。理想情况下,它是 linux/x86,但我愿意接受任何东西并希望能够适应。

最佳答案

好吧,这是我写的东西,它似乎在 Linux 下对我有用。让我知道它是否适合您:

anonprint.py

import gdb

class fd_set_printer:
"""
Prints an fd_set, which is normally an opaque
array of ints, each bit representing one file descriptor
"""

def __init__(self, val, val_array):
self.val = val
self.val_array = val_array

@staticmethod
def find_set_bits(bit_array):
"""
Finds set bits in a long bit list.
Expects a gdb.Value which contains a C array,
such as int[10], and treats it as a bitlist
of int_size * 10 bits long. Returns an array of
bit positions, starting with 0, for which the bits
are on.
e.g. for int foo[] = [1, 6], it will return [ 0, 33, 34 ]
The array should be given as a gdb.Value
"""
set_bits = []
bits_length = bit_array[0].type.sizeof * 8
current_bit = 0

# Can not use 'for current_byte in gdb.Value:' even if
# gdb.Value.type.code == gdb.TYPE_CODE_ARRAY
# So iteration happens this ugly C-style way
for current_byte_pos in xrange(*bit_array.type.range()):
current_byte = bit_array[current_byte_pos]
for bit in xrange(0, bits_length):
bit_mask = 1 << bit
if bit_mask & current_byte == bit_mask:
set_bits.append(current_bit)
current_bit += 1

return set_bits

def to_string(self):
fd_list = self.find_set_bits(self.val_array)
if len(fd_list) == 0:
output = "Empty file descriptor set."
else:
output = "File descriptor set: "
output += ', '.join(map(str, fd_list))
return output


def anon_struct_lookup_function(val):
"""
Checks if the given value looks like an fd_set.
If it does, delegates printing to the printer
"""
lookup_tag = val.type.tag
if lookup_tag == None:
return None
if lookup_tag != "<anonymous struct>":
return None

fields = val.type.fields()
val_array = None

if len(fields) == 1 and fields[0].name == 'fds_bits':
val_array = val['fds_bits']
elif len(fields) == 1 and fields[0].name == '__fds_bits':
val_array = val['__fds_bits']

if not val_array is None:
return fd_set_printer(val, val_array)

return None


def add_fd_set_printer(obj = gdb):
"Adds the fd_set pretty printer to the given object"
obj.pretty_printers.append(anon_struct_lookup_function)

然后让你的~/.gdbinit:

python
import sys
sys.path.insert(0, '/home/user/anonprint_py_directory_here')
from anonprint import add_fd_set_printer
add_fd_set_printer()
end

这是我第一次尝试通过 Python 与 gdb 内部交互,因此欢迎评论和建议。

关于python - 有人有 Linux 上 fd_set 的 gdb pretty-print 代码吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6832213/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com