symbols.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  1. #
  2. # gdb helper commands and functions for Linux kernel debugging
  3. #
  4. # load kernel and module symbols
  5. #
  6. # Copyright (c) Siemens AG, 2011-2013
  7. #
  8. # Authors:
  9. # Jan Kiszka <jan.kiszka@siemens.com>
  10. #
  11. # This work is licensed under the terms of the GNU GPL version 2.
  12. #
  13. import gdb
  14. import os
  15. import re
  16. from linux import modules
  17. if hasattr(gdb, 'Breakpoint'):
  18. class LoadModuleBreakpoint(gdb.Breakpoint):
  19. def __init__(self, spec, gdb_command):
  20. super(LoadModuleBreakpoint, self).__init__(spec, internal=True)
  21. self.silent = True
  22. self.gdb_command = gdb_command
  23. def stop(self):
  24. module = gdb.parse_and_eval("mod")
  25. module_name = module['name'].string()
  26. cmd = self.gdb_command
  27. # enforce update if object file is not found
  28. cmd.module_files_updated = False
  29. # Disable pagination while reporting symbol (re-)loading.
  30. # The console input is blocked in this context so that we would
  31. # get stuck waiting for the user to acknowledge paged output.
  32. show_pagination = gdb.execute("show pagination", to_string=True)
  33. pagination = show_pagination.endswith("on.\n")
  34. gdb.execute("set pagination off")
  35. if module_name in cmd.loaded_modules:
  36. gdb.write("refreshing all symbols to reload module "
  37. "'{0}'\n".format(module_name))
  38. cmd.load_all_symbols()
  39. else:
  40. cmd.load_module_symbols(module)
  41. # restore pagination state
  42. gdb.execute("set pagination %s" % ("on" if pagination else "off"))
  43. return False
  44. class LxSymbols(gdb.Command):
  45. """(Re-)load symbols of Linux kernel and currently loaded modules.
  46. The kernel (vmlinux) is taken from the current working directly. Modules (.ko)
  47. are scanned recursively, starting in the same directory. Optionally, the module
  48. search path can be extended by a space separated list of paths passed to the
  49. lx-symbols command."""
  50. module_paths = []
  51. module_files = []
  52. module_files_updated = False
  53. loaded_modules = []
  54. breakpoint = None
  55. def __init__(self):
  56. super(LxSymbols, self).__init__("lx-symbols", gdb.COMMAND_FILES,
  57. gdb.COMPLETE_FILENAME)
  58. def _update_module_files(self):
  59. self.module_files = []
  60. for path in self.module_paths:
  61. gdb.write("scanning for modules in {0}\n".format(path))
  62. for root, dirs, files in os.walk(path):
  63. for name in files:
  64. if name.endswith(".ko"):
  65. self.module_files.append(root + "/" + name)
  66. self.module_files_updated = True
  67. def _get_module_file(self, module_name):
  68. module_pattern = ".*/{0}\.ko$".format(
  69. module_name.replace("_", r"[_\-]"))
  70. for name in self.module_files:
  71. if re.match(module_pattern, name) and os.path.exists(name):
  72. return name
  73. return None
  74. def _section_arguments(self, module):
  75. try:
  76. sect_attrs = module['sect_attrs'].dereference()
  77. except gdb.error:
  78. return ""
  79. attrs = sect_attrs['attrs']
  80. section_name_to_address = {
  81. attrs[n]['name'].string(): attrs[n]['address']
  82. for n in range(int(sect_attrs['nsections']))}
  83. args = []
  84. for section_name in [".data", ".data..read_mostly", ".rodata", ".bss"]:
  85. address = section_name_to_address.get(section_name)
  86. if address:
  87. args.append(" -s {name} {addr}".format(
  88. name=section_name, addr=str(address)))
  89. return "".join(args)
  90. def load_module_symbols(self, module):
  91. module_name = module['name'].string()
  92. module_addr = str(module['module_core']).split()[0]
  93. module_file = self._get_module_file(module_name)
  94. if not module_file and not self.module_files_updated:
  95. self._update_module_files()
  96. module_file = self._get_module_file(module_name)
  97. if module_file:
  98. gdb.write("loading @{addr}: {filename}\n".format(
  99. addr=module_addr, filename=module_file))
  100. cmdline = "add-symbol-file {filename} {addr}{sections}".format(
  101. filename=module_file,
  102. addr=module_addr,
  103. sections=self._section_arguments(module))
  104. gdb.execute(cmdline, to_string=True)
  105. if module_name not in self.loaded_modules:
  106. self.loaded_modules.append(module_name)
  107. else:
  108. gdb.write("no module object found for '{0}'\n".format(module_name))
  109. def load_all_symbols(self):
  110. gdb.write("loading vmlinux\n")
  111. # Dropping symbols will disable all breakpoints. So save their states
  112. # and restore them afterward.
  113. saved_states = []
  114. if hasattr(gdb, 'breakpoints') and not gdb.breakpoints() is None:
  115. for bp in gdb.breakpoints():
  116. saved_states.append({'breakpoint': bp, 'enabled': bp.enabled})
  117. # drop all current symbols and reload vmlinux
  118. gdb.execute("symbol-file", to_string=True)
  119. gdb.execute("symbol-file vmlinux")
  120. self.loaded_modules = []
  121. module_list = modules.module_list()
  122. if not module_list:
  123. gdb.write("no modules found\n")
  124. else:
  125. [self.load_module_symbols(module) for module in module_list]
  126. for saved_state in saved_states:
  127. saved_state['breakpoint'].enabled = saved_state['enabled']
  128. def invoke(self, arg, from_tty):
  129. self.module_paths = arg.split()
  130. self.module_paths.append(os.getcwd())
  131. # enforce update
  132. self.module_files = []
  133. self.module_files_updated = False
  134. self.load_all_symbols()
  135. if hasattr(gdb, 'Breakpoint'):
  136. if self.breakpoint is not None:
  137. self.breakpoint.delete()
  138. self.breakpoint = None
  139. self.breakpoint = LoadModuleBreakpoint(
  140. "kernel/module.c:do_init_module", self)
  141. else:
  142. gdb.write("Note: symbol update on module loading not supported "
  143. "with this gdb version\n")
  144. LxSymbols()