proc.py 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. #
  2. # gdb helper commands and functions for Linux kernel debugging
  3. #
  4. # Kernel proc information reader
  5. #
  6. # Copyright (c) 2016 Linaro Ltd
  7. #
  8. # Authors:
  9. # Kieran Bingham <[email protected]>
  10. #
  11. # This work is licensed under the terms of the GNU GPL version 2.
  12. #
  13. import gdb
  14. from linux import constants
  15. from linux import utils
  16. from linux import tasks
  17. from linux import lists
  18. from struct import *
  19. class LxCmdLine(gdb.Command):
  20. """ Report the Linux Commandline used in the current kernel.
  21. Equivalent to cat /proc/cmdline on a running target"""
  22. def __init__(self):
  23. super(LxCmdLine, self).__init__("lx-cmdline", gdb.COMMAND_DATA)
  24. def invoke(self, arg, from_tty):
  25. gdb.write(gdb.parse_and_eval("saved_command_line").string() + "\n")
  26. LxCmdLine()
  27. class LxVersion(gdb.Command):
  28. """ Report the Linux Version of the current kernel.
  29. Equivalent to cat /proc/version on a running target"""
  30. def __init__(self):
  31. super(LxVersion, self).__init__("lx-version", gdb.COMMAND_DATA)
  32. def invoke(self, arg, from_tty):
  33. # linux_banner should contain a newline
  34. gdb.write(gdb.parse_and_eval("(char *)linux_banner").string())
  35. LxVersion()
  36. # Resource Structure Printers
  37. # /proc/iomem
  38. # /proc/ioports
  39. def get_resources(resource, depth):
  40. while resource:
  41. yield resource, depth
  42. child = resource['child']
  43. if child:
  44. for res, deep in get_resources(child, depth + 1):
  45. yield res, deep
  46. resource = resource['sibling']
  47. def show_lx_resources(resource_str):
  48. resource = gdb.parse_and_eval(resource_str)
  49. width = 4 if resource['end'] < 0x10000 else 8
  50. # Iterate straight to the first child
  51. for res, depth in get_resources(resource['child'], 0):
  52. start = int(res['start'])
  53. end = int(res['end'])
  54. gdb.write(" " * depth * 2 +
  55. "{0:0{1}x}-".format(start, width) +
  56. "{0:0{1}x} : ".format(end, width) +
  57. res['name'].string() + "\n")
  58. class LxIOMem(gdb.Command):
  59. """Identify the IO memory resource locations defined by the kernel
  60. Equivalent to cat /proc/iomem on a running target"""
  61. def __init__(self):
  62. super(LxIOMem, self).__init__("lx-iomem", gdb.COMMAND_DATA)
  63. def invoke(self, arg, from_tty):
  64. return show_lx_resources("iomem_resource")
  65. LxIOMem()
  66. class LxIOPorts(gdb.Command):
  67. """Identify the IO port resource locations defined by the kernel
  68. Equivalent to cat /proc/ioports on a running target"""
  69. def __init__(self):
  70. super(LxIOPorts, self).__init__("lx-ioports", gdb.COMMAND_DATA)
  71. def invoke(self, arg, from_tty):
  72. return show_lx_resources("ioport_resource")
  73. LxIOPorts()
  74. # Mount namespace viewer
  75. # /proc/mounts
  76. def info_opts(lst, opt):
  77. opts = ""
  78. for key, string in lst.items():
  79. if opt & key:
  80. opts += string
  81. return opts
  82. FS_INFO = {constants.LX_SB_SYNCHRONOUS: ",sync",
  83. constants.LX_SB_MANDLOCK: ",mand",
  84. constants.LX_SB_DIRSYNC: ",dirsync",
  85. constants.LX_SB_NOATIME: ",noatime",
  86. constants.LX_SB_NODIRATIME: ",nodiratime"}
  87. MNT_INFO = {constants.LX_MNT_NOSUID: ",nosuid",
  88. constants.LX_MNT_NODEV: ",nodev",
  89. constants.LX_MNT_NOEXEC: ",noexec",
  90. constants.LX_MNT_NOATIME: ",noatime",
  91. constants.LX_MNT_NODIRATIME: ",nodiratime",
  92. constants.LX_MNT_RELATIME: ",relatime"}
  93. mount_type = utils.CachedType("struct mount")
  94. mount_ptr_type = mount_type.get_type().pointer()
  95. class LxMounts(gdb.Command):
  96. """Report the VFS mounts of the current process namespace.
  97. Equivalent to cat /proc/mounts on a running target
  98. An integer value can be supplied to display the mount
  99. values of that process namespace"""
  100. def __init__(self):
  101. super(LxMounts, self).__init__("lx-mounts", gdb.COMMAND_DATA)
  102. # Equivalent to proc_namespace.c:show_vfsmnt
  103. # However, that has the ability to call into s_op functions
  104. # whereas we cannot and must make do with the information we can obtain.
  105. def invoke(self, arg, from_tty):
  106. argv = gdb.string_to_argv(arg)
  107. if len(argv) >= 1:
  108. try:
  109. pid = int(argv[0])
  110. except gdb.error:
  111. raise gdb.GdbError("Provide a PID as integer value")
  112. else:
  113. pid = 1
  114. task = tasks.get_task_by_pid(pid)
  115. if not task:
  116. raise gdb.GdbError("Couldn't find a process with PID {}"
  117. .format(pid))
  118. namespace = task['nsproxy']['mnt_ns']
  119. if not namespace:
  120. raise gdb.GdbError("No namespace for current process")
  121. gdb.write("{:^18} {:^15} {:>9} {} {} options\n".format(
  122. "mount", "super_block", "devname", "pathname", "fstype"))
  123. for vfs in lists.list_for_each_entry(namespace['list'],
  124. mount_ptr_type, "mnt_list"):
  125. devname = vfs['mnt_devname'].string()
  126. devname = devname if devname else "none"
  127. pathname = ""
  128. parent = vfs
  129. while True:
  130. mntpoint = parent['mnt_mountpoint']
  131. pathname = utils.dentry_name(mntpoint) + pathname
  132. if (parent == parent['mnt_parent']):
  133. break
  134. parent = parent['mnt_parent']
  135. if (pathname == ""):
  136. pathname = "/"
  137. superblock = vfs['mnt']['mnt_sb']
  138. fstype = superblock['s_type']['name'].string()
  139. s_flags = int(superblock['s_flags'])
  140. m_flags = int(vfs['mnt']['mnt_flags'])
  141. rd = "ro" if (s_flags & constants.LX_SB_RDONLY) else "rw"
  142. gdb.write("{} {} {} {} {} {}{}{} 0 0\n".format(
  143. vfs.format_string(), superblock.format_string(), devname,
  144. pathname, fstype, rd, info_opts(FS_INFO, s_flags),
  145. info_opts(MNT_INFO, m_flags)))
  146. LxMounts()
  147. class LxFdtDump(gdb.Command):
  148. """Output Flattened Device Tree header and dump FDT blob to the filename
  149. specified as the command argument. Equivalent to
  150. 'cat /proc/fdt > fdtdump.dtb' on a running target"""
  151. def __init__(self):
  152. super(LxFdtDump, self).__init__("lx-fdtdump", gdb.COMMAND_DATA,
  153. gdb.COMPLETE_FILENAME)
  154. def fdthdr_to_cpu(self, fdt_header):
  155. fdt_header_be = ">IIIIIII"
  156. fdt_header_le = "<IIIIIII"
  157. if utils.get_target_endianness() == 1:
  158. output_fmt = fdt_header_le
  159. else:
  160. output_fmt = fdt_header_be
  161. return unpack(output_fmt, pack(fdt_header_be,
  162. fdt_header['magic'],
  163. fdt_header['totalsize'],
  164. fdt_header['off_dt_struct'],
  165. fdt_header['off_dt_strings'],
  166. fdt_header['off_mem_rsvmap'],
  167. fdt_header['version'],
  168. fdt_header['last_comp_version']))
  169. def invoke(self, arg, from_tty):
  170. if not constants.LX_CONFIG_OF:
  171. raise gdb.GdbError("Kernel not compiled with CONFIG_OF\n")
  172. if len(arg) == 0:
  173. filename = "fdtdump.dtb"
  174. else:
  175. filename = arg
  176. py_fdt_header_ptr = gdb.parse_and_eval(
  177. "(const struct fdt_header *) initial_boot_params")
  178. py_fdt_header = py_fdt_header_ptr.dereference()
  179. fdt_header = self.fdthdr_to_cpu(py_fdt_header)
  180. if fdt_header[0] != constants.LX_OF_DT_HEADER:
  181. raise gdb.GdbError("No flattened device tree magic found\n")
  182. gdb.write("fdt_magic: 0x{:02X}\n".format(fdt_header[0]))
  183. gdb.write("fdt_totalsize: 0x{:02X}\n".format(fdt_header[1]))
  184. gdb.write("off_dt_struct: 0x{:02X}\n".format(fdt_header[2]))
  185. gdb.write("off_dt_strings: 0x{:02X}\n".format(fdt_header[3]))
  186. gdb.write("off_mem_rsvmap: 0x{:02X}\n".format(fdt_header[4]))
  187. gdb.write("version: {}\n".format(fdt_header[5]))
  188. gdb.write("last_comp_version: {}\n".format(fdt_header[6]))
  189. inf = gdb.inferiors()[0]
  190. fdt_buf = utils.read_memoryview(inf, py_fdt_header_ptr,
  191. fdt_header[1]).tobytes()
  192. try:
  193. f = open(filename, 'wb')
  194. except gdb.error:
  195. raise gdb.GdbError("Could not open file to dump fdt")
  196. f.write(fdt_buf)
  197. f.close()
  198. gdb.write("Dumped fdt blob to " + filename + "\n")
  199. LxFdtDump()