SmiHandlerProfileSymbolGen.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. ##
  2. # Generate symbal for SMI handler profile info.
  3. #
  4. # This tool depends on DIA2Dump.exe (VS) or nm (gcc) to parse debug entry.
  5. #
  6. # Copyright (c) 2017, Intel Corporation. All rights reserved.<BR>
  7. # SPDX-License-Identifier: BSD-2-Clause-Patent
  8. #
  9. ##
  10. from __future__ import print_function
  11. import os
  12. import re
  13. import sys
  14. from optparse import OptionParser
  15. from xml.dom.minidom import parse
  16. import xml.dom.minidom
  17. versionNumber = "1.1"
  18. __copyright__ = "Copyright (c) 2016, Intel Corporation. All rights reserved."
  19. class Symbols:
  20. def __init__(self):
  21. self.listLineAddress = []
  22. self.pdbName = ""
  23. # Cache for function
  24. self.functionName = ""
  25. # Cache for line
  26. self.sourceName = ""
  27. def getSymbol (self, rva):
  28. index = 0
  29. lineName = 0
  30. sourceName = "??"
  31. while index + 1 < self.lineCount :
  32. if self.listLineAddress[index][0] <= rva and self.listLineAddress[index + 1][0] > rva :
  33. offset = rva - self.listLineAddress[index][0]
  34. functionName = self.listLineAddress[index][1]
  35. lineName = self.listLineAddress[index][2]
  36. sourceName = self.listLineAddress[index][3]
  37. if lineName == 0 :
  38. return [functionName]
  39. else :
  40. return [functionName, sourceName, lineName]
  41. index += 1
  42. return []
  43. def parse_debug_file(self, driverName, pdbName):
  44. if cmp (pdbName, "") == 0 :
  45. return
  46. self.pdbName = pdbName;
  47. try:
  48. nmCommand = "nm"
  49. nmLineOption = "-l"
  50. print("parsing (debug) - " + pdbName)
  51. os.system ('%s %s %s > nmDump.line.log' % (nmCommand, nmLineOption, pdbName))
  52. except :
  53. print('ERROR: nm command not available. Please verify PATH')
  54. return
  55. #
  56. # parse line
  57. #
  58. linefile = open("nmDump.line.log")
  59. reportLines = linefile.readlines()
  60. linefile.close()
  61. # 000113ca T AllocatePool c:\home\edk-ii\MdePkg\Library\UefiMemoryAllocationLib\MemoryAllocationLib.c:399
  62. patchLineFileMatchString = "([0-9a-fA-F]*)\s+[T|D|t|d]\s+(\w+)\s*((?:[a-zA-Z]:)?[\w+\-./_a-zA-Z0-9\\\\]*):?([0-9]*)"
  63. for reportLine in reportLines:
  64. match = re.match(patchLineFileMatchString, reportLine)
  65. if match is not None:
  66. rva = int (match.group(1), 16)
  67. functionName = match.group(2)
  68. sourceName = match.group(3)
  69. if cmp (match.group(4), "") != 0 :
  70. lineName = int (match.group(4))
  71. else :
  72. lineName = 0
  73. self.listLineAddress.append ([rva, functionName, lineName, sourceName])
  74. self.lineCount = len (self.listLineAddress)
  75. self.listLineAddress = sorted(self.listLineAddress, key=lambda symbolAddress:symbolAddress[0])
  76. def parse_pdb_file(self, driverName, pdbName):
  77. if cmp (pdbName, "") == 0 :
  78. return
  79. self.pdbName = pdbName;
  80. try:
  81. #DIA2DumpCommand = "\"C:\\Program Files (x86)\Microsoft Visual Studio 14.0\\DIA SDK\\Samples\\DIA2Dump\\x64\\Debug\\Dia2Dump.exe\""
  82. DIA2DumpCommand = "Dia2Dump.exe"
  83. #DIA2SymbolOption = "-p"
  84. DIA2LinesOption = "-l"
  85. print("parsing (pdb) - " + pdbName)
  86. #os.system ('%s %s %s > DIA2Dump.symbol.log' % (DIA2DumpCommand, DIA2SymbolOption, pdbName))
  87. os.system ('%s %s %s > DIA2Dump.line.log' % (DIA2DumpCommand, DIA2LinesOption, pdbName))
  88. except :
  89. print('ERROR: DIA2Dump command not available. Please verify PATH')
  90. return
  91. #
  92. # parse line
  93. #
  94. linefile = open("DIA2Dump.line.log")
  95. reportLines = linefile.readlines()
  96. linefile.close()
  97. # ** GetDebugPrintErrorLevel
  98. # line 32 at [0000C790][0001:0000B790], len = 0x3 c:\home\edk-ii\mdepkg\library\basedebugprinterrorlevellib\basedebugprinterrorlevellib.c (MD5: 687C0AE564079D35D56ED5D84A6164CC)
  99. # line 36 at [0000C793][0001:0000B793], len = 0x5
  100. # line 37 at [0000C798][0001:0000B798], len = 0x2
  101. patchLineFileMatchString = "\s+line ([0-9]+) at \[([0-9a-fA-F]{8})\]\[[0-9a-fA-F]{4}\:[0-9a-fA-F]{8}\], len = 0x[0-9a-fA-F]+\s*([\w+\-\:./_a-zA-Z0-9\\\\]*)\s*"
  102. patchLineFileMatchStringFunc = "\*\*\s+(\w+)\s*"
  103. for reportLine in reportLines:
  104. match = re.match(patchLineFileMatchString, reportLine)
  105. if match is not None:
  106. if cmp (match.group(3), "") != 0 :
  107. self.sourceName = match.group(3)
  108. sourceName = self.sourceName
  109. functionName = self.functionName
  110. rva = int (match.group(2), 16)
  111. lineName = int (match.group(1))
  112. self.listLineAddress.append ([rva, functionName, lineName, sourceName])
  113. else :
  114. match = re.match(patchLineFileMatchStringFunc, reportLine)
  115. if match is not None:
  116. self.functionName = match.group(1)
  117. self.lineCount = len (self.listLineAddress)
  118. self.listLineAddress = sorted(self.listLineAddress, key=lambda symbolAddress:symbolAddress[0])
  119. class SymbolsFile:
  120. def __init__(self):
  121. self.symbolsTable = {}
  122. symbolsFile = ""
  123. driverName = ""
  124. rvaName = ""
  125. symbolName = ""
  126. def getSymbolName(driverName, rva):
  127. global symbolsFile
  128. try :
  129. symbolList = symbolsFile.symbolsTable[driverName]
  130. if symbolList is not None:
  131. return symbolList.getSymbol (rva)
  132. else:
  133. return []
  134. except Exception:
  135. return []
  136. def myOptionParser():
  137. usage = "%prog [--version] [-h] [--help] [-i inputfile [-o outputfile] [-g guidreffile]]"
  138. Parser = OptionParser(usage=usage, description=__copyright__, version="%prog " + str(versionNumber))
  139. Parser.add_option("-i", "--inputfile", dest="inputfilename", type="string", help="The input memory profile info file output from MemoryProfileInfo application in MdeModulePkg")
  140. Parser.add_option("-o", "--outputfile", dest="outputfilename", type="string", help="The output memory profile info file with symbol, MemoryProfileInfoSymbol.txt will be used if it is not specified")
  141. Parser.add_option("-g", "--guidref", dest="guidreffilename", type="string", help="The input guid ref file output from build")
  142. (Options, args) = Parser.parse_args()
  143. if Options.inputfilename is None:
  144. Parser.error("no input file specified")
  145. if Options.outputfilename is None:
  146. Options.outputfilename = "SmiHandlerProfileInfoSymbol.xml"
  147. return Options
  148. dictGuid = {
  149. '00000000-0000-0000-0000-000000000000':'gZeroGuid',
  150. '2A571201-4966-47F6-8B86-F31E41F32F10':'gEfiEventLegacyBootGuid',
  151. '27ABF055-B1B8-4C26-8048-748F37BAA2DF':'gEfiEventExitBootServicesGuid',
  152. '7CE88FB3-4BD7-4679-87A8-A8D8DEE50D2B':'gEfiEventReadyToBootGuid',
  153. '02CE967A-DD7E-4FFC-9EE7-810CF0470880':'gEfiEndOfDxeEventGroupGuid',
  154. '60FF8964-E906-41D0-AFED-F241E974E08E':'gEfiDxeSmmReadyToLockProtocolGuid',
  155. '18A3C6DC-5EEA-48C8-A1C1-B53389F98999':'gEfiSmmSwDispatch2ProtocolGuid',
  156. '456D2859-A84B-4E47-A2EE-3276D886997D':'gEfiSmmSxDispatch2ProtocolGuid',
  157. '4CEC368E-8E8E-4D71-8BE1-958C45FC8A53':'gEfiSmmPeriodicTimerDispatch2ProtocolGuid',
  158. 'EE9B8D90-C5A6-40A2-BDE2-52558D33CCA1':'gEfiSmmUsbDispatch2ProtocolGuid',
  159. '25566B03-B577-4CBF-958C-ED663EA24380':'gEfiSmmGpiDispatch2ProtocolGuid',
  160. '7300C4A1-43F2-4017-A51B-C81A7F40585B':'gEfiSmmStandbyButtonDispatch2ProtocolGuid',
  161. '1B1183FA-1823-46A7-8872-9C578755409D':'gEfiSmmPowerButtonDispatch2ProtocolGuid',
  162. '58DC368D-7BFA-4E77-ABBC-0E29418DF930':'gEfiSmmIoTrapDispatch2ProtocolGuid',
  163. }
  164. def genGuidString(guidreffile):
  165. guidLines = guidreffile.readlines()
  166. for guidLine in guidLines:
  167. guidLineList = guidLine.split(" ")
  168. if len(guidLineList) == 2:
  169. guid = guidLineList[0]
  170. guidName = guidLineList[1]
  171. if guid not in dictGuid :
  172. dictGuid[guid] = guidName
  173. def createSym(symbolName):
  174. SymbolNode = xml.dom.minidom.Document().createElement("Symbol")
  175. SymbolFunction = xml.dom.minidom.Document().createElement("Function")
  176. SymbolFunctionData = xml.dom.minidom.Document().createTextNode(symbolName[0])
  177. SymbolFunction.appendChild(SymbolFunctionData)
  178. SymbolNode.appendChild(SymbolFunction)
  179. if (len(symbolName)) >= 2:
  180. SymbolSourceFile = xml.dom.minidom.Document().createElement("SourceFile")
  181. SymbolSourceFileData = xml.dom.minidom.Document().createTextNode(symbolName[1])
  182. SymbolSourceFile.appendChild(SymbolSourceFileData)
  183. SymbolNode.appendChild(SymbolSourceFile)
  184. if (len(symbolName)) >= 3:
  185. SymbolLineNumber = xml.dom.minidom.Document().createElement("LineNumber")
  186. SymbolLineNumberData = xml.dom.minidom.Document().createTextNode(str(symbolName[2]))
  187. SymbolLineNumber.appendChild(SymbolLineNumberData)
  188. SymbolNode.appendChild(SymbolLineNumber)
  189. return SymbolNode
  190. def main():
  191. global symbolsFile
  192. global Options
  193. Options = myOptionParser()
  194. symbolsFile = SymbolsFile()
  195. try :
  196. DOMTree = xml.dom.minidom.parse(Options.inputfilename)
  197. except Exception:
  198. print("fail to open input " + Options.inputfilename)
  199. return 1
  200. if Options.guidreffilename is not None:
  201. try :
  202. guidreffile = open(Options.guidreffilename)
  203. except Exception:
  204. print("fail to open guidref" + Options.guidreffilename)
  205. return 1
  206. genGuidString(guidreffile)
  207. guidreffile.close()
  208. SmiHandlerProfile = DOMTree.documentElement
  209. SmiHandlerDatabase = SmiHandlerProfile.getElementsByTagName("SmiHandlerDatabase")
  210. SmiHandlerCategory = SmiHandlerDatabase[0].getElementsByTagName("SmiHandlerCategory")
  211. for smiHandlerCategory in SmiHandlerCategory:
  212. SmiEntry = smiHandlerCategory.getElementsByTagName("SmiEntry")
  213. for smiEntry in SmiEntry:
  214. if smiEntry.hasAttribute("HandlerType"):
  215. guidValue = smiEntry.getAttribute("HandlerType")
  216. if guidValue in dictGuid:
  217. smiEntry.setAttribute("HandlerType", dictGuid[guidValue])
  218. SmiHandler = smiEntry.getElementsByTagName("SmiHandler")
  219. for smiHandler in SmiHandler:
  220. Module = smiHandler.getElementsByTagName("Module")
  221. Pdb = Module[0].getElementsByTagName("Pdb")
  222. if (len(Pdb)) >= 1:
  223. driverName = Module[0].getAttribute("Name")
  224. pdbName = Pdb[0].childNodes[0].data
  225. Module[0].removeChild(Pdb[0])
  226. symbolsFile.symbolsTable[driverName] = Symbols()
  227. if cmp (pdbName[-3:], "pdb") == 0 :
  228. symbolsFile.symbolsTable[driverName].parse_pdb_file (driverName, pdbName)
  229. else :
  230. symbolsFile.symbolsTable[driverName].parse_debug_file (driverName, pdbName)
  231. Handler = smiHandler.getElementsByTagName("Handler")
  232. RVA = Handler[0].getElementsByTagName("RVA")
  233. print(" Handler RVA: %s" % RVA[0].childNodes[0].data)
  234. if (len(RVA)) >= 1:
  235. rvaName = RVA[0].childNodes[0].data
  236. symbolName = getSymbolName (driverName, int(rvaName, 16))
  237. if (len(symbolName)) >= 1:
  238. SymbolNode = createSym(symbolName)
  239. Handler[0].appendChild(SymbolNode)
  240. Caller = smiHandler.getElementsByTagName("Caller")
  241. RVA = Caller[0].getElementsByTagName("RVA")
  242. print(" Caller RVA: %s" % RVA[0].childNodes[0].data)
  243. if (len(RVA)) >= 1:
  244. rvaName = RVA[0].childNodes[0].data
  245. symbolName = getSymbolName (driverName, int(rvaName, 16))
  246. if (len(symbolName)) >= 1:
  247. SymbolNode = createSym(symbolName)
  248. Caller[0].appendChild(SymbolNode)
  249. try :
  250. newfile = open(Options.outputfilename, "w")
  251. except Exception:
  252. print("fail to open output" + Options.outputfilename)
  253. return 1
  254. newfile.write(DOMTree.toprettyxml(indent = "\t", newl = "\n", encoding = "utf-8"))
  255. newfile.close()
  256. if __name__ == '__main__':
  257. sys.exit(main())