symbols.py 6.2 KB

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