efi_gdb.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918
  1. #!/usr/bin/python3
  2. '''
  3. Copyright 2021 (c) Apple Inc. All rights reserved.
  4. SPDX-License-Identifier: BSD-2-Clause-Patent
  5. EFI gdb commands based on efi_debugging classes.
  6. Example usage:
  7. OvmfPkg/build.sh qemu -gdb tcp::9000
  8. gdb -ex "target remote localhost:9000" -ex "source efi_gdb.py"
  9. (gdb) help efi
  10. Commands for debugging EFI. efi <cmd>
  11. List of efi subcommands:
  12. efi devicepath -- Display an EFI device path.
  13. efi guid -- Display info about EFI GUID's.
  14. efi hob -- Dump EFI HOBs. Type 'hob -h' for more info.
  15. efi symbols -- Load Symbols for EFI. Type 'efi_symbols -h' for more info.
  16. efi table -- Dump EFI System Tables. Type 'table -h' for more info.
  17. This module is coded against a generic gdb remote serial stub. It should work
  18. with QEMU, JTAG debugger, or a generic EFI gdb remote serial stub.
  19. If you are debugging with QEMU or a JTAG hardware debugger you can insert
  20. a CpuDeadLoop(); in your code, attach with gdb, and then `p Index=1` to
  21. step past. If you have a debug stub in EFI you can use CpuBreakpoint();.
  22. '''
  23. from gdb.printing import RegexpCollectionPrettyPrinter
  24. from gdb.printing import register_pretty_printer
  25. import gdb
  26. import os
  27. import sys
  28. import uuid
  29. import optparse
  30. import shlex
  31. # gdb will not import from the same path as this script.
  32. # so lets fix that for gdb...
  33. sys.path.append(os.path.dirname(os.path.abspath(__file__)))
  34. from efi_debugging import PeTeImage, patch_ctypes # noqa: E402
  35. from efi_debugging import EfiHob, GuidNames, EfiStatusClass # noqa: E402
  36. from efi_debugging import EfiBootMode, EfiDevicePath # noqa: E402
  37. from efi_debugging import EfiConfigurationTable, EfiTpl # noqa: E402
  38. class GdbFileObject(object):
  39. '''Provide a file like object required by efi_debugging'''
  40. def __init__(self):
  41. self.inferior = gdb.selected_inferior()
  42. self.offset = 0
  43. def tell(self):
  44. return self.offset
  45. def read(self, size=-1):
  46. if size == -1:
  47. # arbitrary default size
  48. size = 0x1000000
  49. try:
  50. data = self.inferior.read_memory(self.offset, size)
  51. except MemoryError:
  52. data = bytearray(size)
  53. assert False
  54. if len(data) != size:
  55. raise MemoryError(
  56. f'gdb could not read memory 0x{size:x}'
  57. + f' bytes from 0x{self.offset:08x}')
  58. else:
  59. # convert memoryview object to a bytestring.
  60. return data.tobytes()
  61. def readable(self):
  62. return True
  63. def seek(self, offset, whence=0):
  64. if whence == 0:
  65. self.offset = offset
  66. elif whence == 1:
  67. self.offset += offset
  68. else:
  69. # whence == 2 is seek from end
  70. raise NotImplementedError
  71. def seekable(self):
  72. return True
  73. def write(self, data):
  74. self.inferior.write_memory(self.offset, data)
  75. return len(data)
  76. def writable(self):
  77. return True
  78. def truncate(self, size=None):
  79. raise NotImplementedError
  80. def flush(self):
  81. raise NotImplementedError
  82. def fileno(self):
  83. raise NotImplementedError
  84. class EfiSymbols:
  85. """Class to manage EFI Symbols"""
  86. loaded = {}
  87. stride = None
  88. range = None
  89. verbose = False
  90. def __init__(self, file=None):
  91. EfiSymbols.file = file if file else GdbFileObject()
  92. @ classmethod
  93. def __str__(cls):
  94. return ''.join(f'{value}\n' for value in cls.loaded.values())
  95. @ classmethod
  96. def configure_search(cls, stride, range=None, verbose=False):
  97. cls.stride = stride
  98. cls.range = range
  99. cls.verbose = verbose
  100. @ classmethod
  101. def clear(cls):
  102. cls.loaded = {}
  103. @ classmethod
  104. def add_symbols_for_pecoff(cls, pecoff):
  105. '''Tell lldb the location of the .text and .data sections.'''
  106. if pecoff.TextAddress in cls.loaded:
  107. return 'Already Loaded: '
  108. try:
  109. res = 'Loading Symbols Failed:'
  110. res = gdb.execute('add-symbol-file ' + pecoff.CodeViewPdb +
  111. ' ' + hex(pecoff.TextAddress) +
  112. ' -s .data ' + hex(pecoff.DataAddress),
  113. False, True)
  114. cls.loaded[pecoff.TextAddress] = pecoff
  115. if cls.verbose:
  116. print(f'\n{res:s}\n')
  117. return ''
  118. except gdb.error:
  119. return res
  120. @ classmethod
  121. def address_to_symbols(cls, address, reprobe=False):
  122. '''
  123. Given an address search backwards for a PE/COFF (or TE) header
  124. and load symbols. Return a status string.
  125. '''
  126. if not isinstance(address, int):
  127. address = int(address)
  128. pecoff = cls.address_in_loaded_pecoff(address)
  129. if not reprobe and pecoff is not None:
  130. # skip the probe of the remote
  131. return f'{pecoff} is already loaded'
  132. pecoff = PeTeImage(cls.file, None)
  133. if pecoff.pcToPeCoff(address, cls.stride, cls.range):
  134. res = cls.add_symbols_for_pecoff(pecoff)
  135. return f'{res}{pecoff}'
  136. else:
  137. return f'0x{address:08x} not in a PE/COFF (or TE) image'
  138. @ classmethod
  139. def address_in_loaded_pecoff(cls, address):
  140. if not isinstance(address, int):
  141. address = int(address)
  142. for value in cls.loaded.values():
  143. if (address >= value.LoadAddress and
  144. address <= value.EndLoadAddress):
  145. return value
  146. return None
  147. @ classmethod
  148. def unload_symbols(cls, address):
  149. if not isinstance(address, int):
  150. address = int(address)
  151. pecoff = cls.address_in_loaded_pecoff(address)
  152. try:
  153. res = 'Unloading Symbols Failed:'
  154. res = gdb.execute(
  155. f'remove-symbol-file -a {hex(pecoff.TextAddress):s}',
  156. False, True)
  157. del cls.loaded[pecoff.LoadAddress]
  158. return res
  159. except gdb.error:
  160. return res
  161. class CHAR16_PrettyPrinter(object):
  162. def __init__(self, val):
  163. self.val = val
  164. def to_string(self):
  165. if int(self.val) < 0x20:
  166. return f"L'\\x{int(self.val):02x}'"
  167. else:
  168. return f"L'{chr(self.val):s}'"
  169. class EFI_TPL_PrettyPrinter(object):
  170. def __init__(self, val):
  171. self.val = val
  172. def to_string(self):
  173. return str(EfiTpl(int(self.val)))
  174. class EFI_STATUS_PrettyPrinter(object):
  175. def __init__(self, val):
  176. self.val = val
  177. def to_string(self):
  178. status = int(self.val)
  179. return f'{str(EfiStatusClass(status)):s} (0x{status:08x})'
  180. class EFI_BOOT_MODE_PrettyPrinter(object):
  181. def __init__(self, val):
  182. self.val = val
  183. def to_string(self):
  184. return str(EfiBootMode(int(self.val)))
  185. class EFI_GUID_PrettyPrinter(object):
  186. """Print 'EFI_GUID' as 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'"""
  187. def __init__(self, val):
  188. self.val = val
  189. def to_string(self):
  190. # if we could get a byte like object of *(unsigned char (*)[16])
  191. # then we could just use uuid.UUID() to convert
  192. Data1 = int(self.val['Data1'])
  193. Data2 = int(self.val['Data2'])
  194. Data3 = int(self.val['Data3'])
  195. Data4 = self.val['Data4']
  196. guid = f'{Data1:08X}-{Data2:04X}-'
  197. guid += f'{Data3:04X}-'
  198. guid += f'{int(Data4[0]):02X}{int(Data4[1]):02X}-'
  199. guid += f'{int(Data4[2]):02X}{int(Data4[3]):02X}'
  200. guid += f'{int(Data4[4]):02X}{int(Data4[5]):02X}'
  201. guid += f'{int(Data4[6]):02X}{int(Data4[7]):02X}'
  202. return str(GuidNames(guid))
  203. def build_pretty_printer():
  204. # Turn off via: disable pretty-printer global EFI
  205. pp = RegexpCollectionPrettyPrinter("EFI")
  206. # you can also tell gdb `x/sh <address>` to print CHAR16 string
  207. pp.add_printer('CHAR16', '^CHAR16$', CHAR16_PrettyPrinter)
  208. pp.add_printer('EFI_BOOT_MODE', '^EFI_BOOT_MODE$',
  209. EFI_BOOT_MODE_PrettyPrinter)
  210. pp.add_printer('EFI_GUID', '^EFI_GUID$', EFI_GUID_PrettyPrinter)
  211. pp.add_printer('EFI_STATUS', '^EFI_STATUS$', EFI_STATUS_PrettyPrinter)
  212. pp.add_printer('EFI_TPL', '^EFI_TPL$', EFI_TPL_PrettyPrinter)
  213. return pp
  214. class EfiDevicePathCmd (gdb.Command):
  215. """Display an EFI device path. Type 'efi devicepath -h' for more info"""
  216. def __init__(self):
  217. super(EfiDevicePathCmd, self).__init__(
  218. "efi devicepath", gdb.COMMAND_NONE)
  219. self.file = GdbFileObject()
  220. def create_options(self, arg, from_tty):
  221. usage = "usage: %prog [options] [arg]"
  222. description = (
  223. "Command that can load EFI PE/COFF and TE image symbols. ")
  224. self.parser = optparse.OptionParser(
  225. description=description,
  226. prog='efi devicepath',
  227. usage=usage,
  228. add_help_option=False)
  229. self.parser.add_option(
  230. '-v',
  231. '--verbose',
  232. action='store_true',
  233. dest='verbose',
  234. help='hex dump extra data',
  235. default=False)
  236. self.parser.add_option(
  237. '-n',
  238. '--node',
  239. action='store_true',
  240. dest='node',
  241. help='dump a single device path node',
  242. default=False)
  243. self.parser.add_option(
  244. '-h',
  245. '--help',
  246. action='store_true',
  247. dest='help',
  248. help='Show help for the command',
  249. default=False)
  250. return self.parser.parse_args(shlex.split(arg))
  251. def invoke(self, arg, from_tty):
  252. '''gdb command to dump EFI device paths'''
  253. try:
  254. (options, _) = self.create_options(arg, from_tty)
  255. if options.help:
  256. self.parser.print_help()
  257. return
  258. dev_addr = int(gdb.parse_and_eval(arg))
  259. except ValueError:
  260. print("Invalid argument!")
  261. return
  262. if options.node:
  263. print(EfiDevicePath(
  264. self.file).device_path_node_str(dev_addr,
  265. options.verbose))
  266. else:
  267. device_path = EfiDevicePath(self.file, dev_addr, options.verbose)
  268. if device_path.valid():
  269. print(device_path)
  270. class EfiGuidCmd (gdb.Command):
  271. """Display info about EFI GUID's. Type 'efi guid -h' for more info"""
  272. def __init__(self):
  273. super(EfiGuidCmd, self).__init__("efi guid",
  274. gdb.COMMAND_NONE,
  275. gdb.COMPLETE_EXPRESSION)
  276. self.file = GdbFileObject()
  277. def create_options(self, arg, from_tty):
  278. usage = "usage: %prog [options] [arg]"
  279. description = (
  280. "Show EFI_GUID values and the C name of the EFI_GUID variables"
  281. "in the C code. If symbols are loaded the Guid.xref file"
  282. "can be processed and the complete GUID database can be shown."
  283. "This command also suports generating new GUID's, and showing"
  284. "the value used to initialize the C variable.")
  285. self.parser = optparse.OptionParser(
  286. description=description,
  287. prog='efi guid',
  288. usage=usage,
  289. add_help_option=False)
  290. self.parser.add_option(
  291. '-n',
  292. '--new',
  293. action='store_true',
  294. dest='new',
  295. help='Generate a new GUID',
  296. default=False)
  297. self.parser.add_option(
  298. '-v',
  299. '--verbose',
  300. action='store_true',
  301. dest='verbose',
  302. help='Also display GUID C structure values',
  303. default=False)
  304. self.parser.add_option(
  305. '-h',
  306. '--help',
  307. action='store_true',
  308. dest='help',
  309. help='Show help for the command',
  310. default=False)
  311. return self.parser.parse_args(shlex.split(arg))
  312. def invoke(self, arg, from_tty):
  313. '''gdb command to dump EFI System Tables'''
  314. try:
  315. (options, args) = self.create_options(arg, from_tty)
  316. if options.help:
  317. self.parser.print_help()
  318. return
  319. if len(args) >= 1:
  320. # guid { 0x414e6bdd, 0xe47b, 0x47cc,
  321. # { 0xb2, 0x44, 0xbb, 0x61, 0x02, 0x0c,0xf5, 0x16 }}
  322. # this generates multiple args
  323. guid = ' '.join(args)
  324. except ValueError:
  325. print('bad arguments!')
  326. return
  327. if options.new:
  328. guid = uuid.uuid4()
  329. print(str(guid).upper())
  330. print(GuidNames.to_c_guid(guid))
  331. return
  332. if len(args) > 0:
  333. if GuidNames.is_guid_str(arg):
  334. # guid 05AD34BA-6F02-4214-952E-4DA0398E2BB9
  335. key = guid.upper()
  336. name = GuidNames.to_name(key)
  337. elif GuidNames.is_c_guid(arg):
  338. # guid { 0x414e6bdd, 0xe47b, 0x47cc,
  339. # { 0xb2, 0x44, 0xbb, 0x61, 0x02, 0x0c,0xf5, 0x16 }}
  340. key = GuidNames.from_c_guid(arg)
  341. name = GuidNames.to_name(key)
  342. else:
  343. # guid gEfiDxeServicesTableGuid
  344. name = guid
  345. try:
  346. key = GuidNames.to_guid(name)
  347. name = GuidNames.to_name(key)
  348. except ValueError:
  349. return
  350. extra = f'{GuidNames.to_c_guid(key)}: ' if options.verbose else ''
  351. print(f'{key}: {extra}{name}')
  352. else:
  353. for key, value in GuidNames._dict_.items():
  354. if options.verbose:
  355. extra = f'{GuidNames.to_c_guid(key)}: '
  356. else:
  357. extra = ''
  358. print(f'{key}: {extra}{value}')
  359. class EfiHobCmd (gdb.Command):
  360. """Dump EFI HOBs. Type 'hob -h' for more info."""
  361. def __init__(self):
  362. super(EfiHobCmd, self).__init__("efi hob", gdb.COMMAND_NONE)
  363. self.file = GdbFileObject()
  364. def create_options(self, arg, from_tty):
  365. usage = "usage: %prog [options] [arg]"
  366. description = (
  367. "Command that can load EFI PE/COFF and TE image symbols. ")
  368. self.parser = optparse.OptionParser(
  369. description=description,
  370. prog='efi hob',
  371. usage=usage,
  372. add_help_option=False)
  373. self.parser.add_option(
  374. '-a',
  375. '--address',
  376. type="int",
  377. dest='address',
  378. help='Parse HOBs from address',
  379. default=None)
  380. self.parser.add_option(
  381. '-t',
  382. '--type',
  383. type="int",
  384. dest='type',
  385. help='Only dump HOBS of his type',
  386. default=None)
  387. self.parser.add_option(
  388. '-v',
  389. '--verbose',
  390. action='store_true',
  391. dest='verbose',
  392. help='hex dump extra data',
  393. default=False)
  394. self.parser.add_option(
  395. '-h',
  396. '--help',
  397. action='store_true',
  398. dest='help',
  399. help='Show help for the command',
  400. default=False)
  401. return self.parser.parse_args(shlex.split(arg))
  402. def invoke(self, arg, from_tty):
  403. '''gdb command to dump EFI System Tables'''
  404. try:
  405. (options, _) = self.create_options(arg, from_tty)
  406. if options.help:
  407. self.parser.print_help()
  408. return
  409. except ValueError:
  410. print('bad arguments!')
  411. return
  412. if options.address:
  413. try:
  414. value = gdb.parse_and_eval(options.address)
  415. address = int(value)
  416. except ValueError:
  417. address = None
  418. else:
  419. address = None
  420. hob = EfiHob(self.file,
  421. address,
  422. options.verbose).get_hob_by_type(options.type)
  423. print(hob)
  424. class EfiTablesCmd (gdb.Command):
  425. """Dump EFI System Tables. Type 'table -h' for more info."""
  426. def __init__(self):
  427. super(EfiTablesCmd, self).__init__("efi table", gdb.COMMAND_NONE)
  428. self.file = GdbFileObject()
  429. def create_options(self, arg, from_tty):
  430. usage = "usage: %prog [options] [arg]"
  431. description = "Dump EFI System Tables. Requires symbols to be loaded"
  432. self.parser = optparse.OptionParser(
  433. description=description,
  434. prog='efi table',
  435. usage=usage,
  436. add_help_option=False)
  437. self.parser.add_option(
  438. '-h',
  439. '--help',
  440. action='store_true',
  441. dest='help',
  442. help='Show help for the command',
  443. default=False)
  444. return self.parser.parse_args(shlex.split(arg))
  445. def invoke(self, arg, from_tty):
  446. '''gdb command to dump EFI System Tables'''
  447. try:
  448. (options, _) = self.create_options(arg, from_tty)
  449. if options.help:
  450. self.parser.print_help()
  451. return
  452. except ValueError:
  453. print('bad arguments!')
  454. return
  455. gST = gdb.lookup_global_symbol('gST')
  456. if gST is None:
  457. print('Error: This command requires symbols for gST to be loaded')
  458. return
  459. table = EfiConfigurationTable(
  460. self.file, int(gST.value(gdb.selected_frame())))
  461. if table:
  462. print(table, '\n')
  463. class EfiSymbolsCmd (gdb.Command):
  464. """Load Symbols for EFI. Type 'efi symbols -h' for more info."""
  465. def __init__(self):
  466. super(EfiSymbolsCmd, self).__init__("efi symbols",
  467. gdb.COMMAND_NONE,
  468. gdb.COMPLETE_EXPRESSION)
  469. self.file = GdbFileObject()
  470. self.gST = None
  471. self.efi_symbols = EfiSymbols(self.file)
  472. def create_options(self, arg, from_tty):
  473. usage = "usage: %prog [options]"
  474. description = (
  475. "Command that can load EFI PE/COFF and TE image symbols. "
  476. "If you are having trouble in PEI try adding --pei. "
  477. "Given any address search backward for the PE/COFF (or TE header) "
  478. "and then parse the PE/COFF image to get debug info. "
  479. "The address can come from the current pc, pc values in the "
  480. "frame, or an address provided to the command"
  481. "")
  482. self.parser = optparse.OptionParser(
  483. description=description,
  484. prog='efi symbols',
  485. usage=usage,
  486. add_help_option=False)
  487. self.parser.add_option(
  488. '-a',
  489. '--address',
  490. type="str",
  491. dest='address',
  492. help='Load symbols for image that contains address',
  493. default=None)
  494. self.parser.add_option(
  495. '-c',
  496. '--clear',
  497. action='store_true',
  498. dest='clear',
  499. help='Clear the cache of loaded images',
  500. default=False)
  501. self.parser.add_option(
  502. '-f',
  503. '--frame',
  504. action='store_true',
  505. dest='frame',
  506. help='Load symbols for current stack frame',
  507. default=False)
  508. self.parser.add_option(
  509. '-p',
  510. '--pc',
  511. action='store_true',
  512. dest='pc',
  513. help='Load symbols for pc',
  514. default=False)
  515. self.parser.add_option(
  516. '--pei',
  517. action='store_true',
  518. dest='pei',
  519. help='Load symbols for PEI (searches every 4 bytes)',
  520. default=False)
  521. self.parser.add_option(
  522. '-e',
  523. '--extended',
  524. action='store_true',
  525. dest='extended',
  526. help='Try to load all symbols based on config tables',
  527. default=False)
  528. self.parser.add_option(
  529. '-r',
  530. '--range',
  531. type="long",
  532. dest='range',
  533. help='How far to search backward for start of PE/COFF Image',
  534. default=None)
  535. self.parser.add_option(
  536. '-s',
  537. '--stride',
  538. type="long",
  539. dest='stride',
  540. help='Boundary to search for PE/COFF header',
  541. default=None)
  542. self.parser.add_option(
  543. '-t',
  544. '--thread',
  545. action='store_true',
  546. dest='thread',
  547. help='Load symbols for the frames of all threads',
  548. default=False)
  549. self.parser.add_option(
  550. '-v',
  551. '--verbose',
  552. action='store_true',
  553. dest='verbose',
  554. help='Show more info on symbols loading in gdb',
  555. default=False)
  556. self.parser.add_option(
  557. '-h',
  558. '--help',
  559. action='store_true',
  560. dest='help',
  561. help='Show help for the command',
  562. default=False)
  563. return self.parser.parse_args(shlex.split(arg))
  564. def save_user_state(self):
  565. self.pagination = gdb.parameter("pagination")
  566. if self.pagination:
  567. gdb.execute("set pagination off")
  568. self.user_selected_thread = gdb.selected_thread()
  569. self.user_selected_frame = gdb.selected_frame()
  570. def restore_user_state(self):
  571. self.user_selected_thread.switch()
  572. self.user_selected_frame.select()
  573. if self.pagination:
  574. gdb.execute("set pagination on")
  575. def canonical_address(self, address):
  576. '''
  577. Scrub out 48-bit non canonical addresses
  578. Raw frames in gdb can have some funky values
  579. '''
  580. # Skip lowest 256 bytes to avoid interrupt frames
  581. if address > 0xFF and address < 0x00007FFFFFFFFFFF:
  582. return True
  583. if address >= 0xFFFF800000000000:
  584. return True
  585. return False
  586. def pc_set_for_frames(self):
  587. '''Return a set for the PC's in the current frame'''
  588. pc_list = []
  589. frame = gdb.newest_frame()
  590. while frame:
  591. pc = int(frame.read_register('pc'))
  592. if self.canonical_address(pc):
  593. pc_list.append(pc)
  594. frame = frame.older()
  595. return set(pc_list)
  596. def invoke(self, arg, from_tty):
  597. '''gdb command to symbolicate all the frames from all the threads'''
  598. try:
  599. (options, _) = self.create_options(arg, from_tty)
  600. if options.help:
  601. self.parser.print_help()
  602. return
  603. except ValueError:
  604. print('bad arguments!')
  605. return
  606. self.dont_repeat()
  607. self.save_user_state()
  608. if options.clear:
  609. self.efi_symbols.clear()
  610. return
  611. if options.pei:
  612. # XIP code can be 4 byte aligned in the FV
  613. options.stride = 4
  614. options.range = 0x100000
  615. self.efi_symbols.configure_search(options.stride,
  616. options.range,
  617. options.verbose)
  618. if options.thread:
  619. thread_list = gdb.selected_inferior().threads()
  620. else:
  621. thread_list = (gdb.selected_thread(),)
  622. address = None
  623. if options.address:
  624. value = gdb.parse_and_eval(options.address)
  625. address = int(value)
  626. elif options.pc:
  627. address = gdb.selected_frame().pc()
  628. if address:
  629. res = self.efi_symbols.address_to_symbols(address)
  630. print(res)
  631. else:
  632. for thread in thread_list:
  633. thread.switch()
  634. # You can not iterate over frames as you load symbols. Loading
  635. # symbols changes the frames gdb can see due to inlining and
  636. # boom. So we loop adding symbols for the current frame, and
  637. # we test to see if new frames have shown up. If new frames
  638. # show up we process those new frames. Thus 1st pass is the
  639. # raw frame, and other passes are only new PC values.
  640. NewPcSet = self.pc_set_for_frames()
  641. while NewPcSet:
  642. PcSet = self.pc_set_for_frames()
  643. for pc in NewPcSet:
  644. res = self.efi_symbols.address_to_symbols(pc)
  645. print(res)
  646. NewPcSet = PcSet.symmetric_difference(
  647. self.pc_set_for_frames())
  648. # find the EFI System tables the 1st time
  649. if self.gST is None:
  650. gST = gdb.lookup_global_symbol('gST')
  651. if gST is not None:
  652. self.gST = int(gST.value(gdb.selected_frame()))
  653. table = EfiConfigurationTable(self.file, self.gST)
  654. else:
  655. table = None
  656. else:
  657. table = EfiConfigurationTable(self.file, self.gST)
  658. if options.extended and table:
  659. # load symbols from EFI System Table entry
  660. for address, _ in table.DebugImageInfo():
  661. res = self.efi_symbols.address_to_symbols(address)
  662. print(res)
  663. # sync up the GUID database from the build output
  664. for m in gdb.objfiles():
  665. if GuidNames.add_build_guid_file(str(m.filename)):
  666. break
  667. self.restore_user_state()
  668. class EfiCmd (gdb.Command):
  669. """Commands for debugging EFI. efi <cmd>"""
  670. def __init__(self):
  671. super(EfiCmd, self).__init__("efi",
  672. gdb.COMMAND_NONE,
  673. gdb.COMPLETE_NONE,
  674. True)
  675. def invoke(self, arg, from_tty):
  676. '''default to loading symbols'''
  677. if '-h' in arg or '--help' in arg:
  678. gdb.execute('help efi')
  679. else:
  680. # default to loading all symbols
  681. gdb.execute('efi symbols --extended')
  682. class LoadEmulatorEfiSymbols(gdb.Breakpoint):
  683. '''
  684. breakpoint for EmulatorPkg to load symbols
  685. Note: make sure SecGdbScriptBreak is not optimized away!
  686. Also turn off the dlopen() flow like on macOS.
  687. '''
  688. def stop(self):
  689. symbols = EfiSymbols()
  690. # Emulator adds SizeOfHeaders so we need file alignment to search
  691. symbols.configure_search(0x20)
  692. frame = gdb.newest_frame()
  693. try:
  694. # gdb was looking at spill address, pre spill :(
  695. LoadAddress = frame.read_register('rdx')
  696. AddSymbolFlag = frame.read_register('rcx')
  697. except gdb.error:
  698. LoadAddress = frame.read_var('LoadAddress')
  699. AddSymbolFlag = frame.read_var('AddSymbolFlag')
  700. if AddSymbolFlag == 1:
  701. res = symbols.address_to_symbols(LoadAddress)
  702. else:
  703. res = symbols.unload_symbols(LoadAddress)
  704. print(res)
  705. # keep running
  706. return False
  707. # Get python backtraces to debug errors in this script
  708. gdb.execute("set python print-stack full")
  709. # tell efi_debugging how to walk data structures with pointers
  710. try:
  711. pointer_width = gdb.lookup_type('int').pointer().sizeof
  712. except ValueError:
  713. pointer_width = 8
  714. patch_ctypes(pointer_width)
  715. register_pretty_printer(None, build_pretty_printer(), replace=True)
  716. # gdb commands that we are adding
  717. # add `efi` prefix gdb command
  718. EfiCmd()
  719. # subcommands for `efi`
  720. EfiSymbolsCmd()
  721. EfiTablesCmd()
  722. EfiHobCmd()
  723. EfiDevicePathCmd()
  724. EfiGuidCmd()
  725. #
  726. bp = LoadEmulatorEfiSymbols('SecGdbScriptBreak', internal=True)
  727. if bp.pending:
  728. try:
  729. gdb.selected_frame()
  730. # Not the emulator so do this when you attach
  731. gdb.execute('efi symbols --frame --extended', True)
  732. gdb.execute('bt')
  733. # If you want to skip the above commands comment them out
  734. pass
  735. except gdb.error:
  736. # If you load the script and there is no target ignore the error.
  737. pass
  738. else:
  739. # start the emulator
  740. gdb.execute('run')