exported-sql-viewer.py 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133
  1. #!/usr/bin/python2
  2. # SPDX-License-Identifier: GPL-2.0
  3. # exported-sql-viewer.py: view data from sql database
  4. # Copyright (c) 2014-2018, Intel Corporation.
  5. # To use this script you will need to have exported data using either the
  6. # export-to-sqlite.py or the export-to-postgresql.py script. Refer to those
  7. # scripts for details.
  8. #
  9. # Following on from the example in the export scripts, a
  10. # call-graph can be displayed for the pt_example database like this:
  11. #
  12. # python tools/perf/scripts/python/exported-sql-viewer.py pt_example
  13. #
  14. # Note that for PostgreSQL, this script supports connecting to remote databases
  15. # by setting hostname, port, username, password, and dbname e.g.
  16. #
  17. # python tools/perf/scripts/python/exported-sql-viewer.py "hostname=myhost username=myuser password=mypassword dbname=pt_example"
  18. #
  19. # The result is a GUI window with a tree representing a context-sensitive
  20. # call-graph. Expanding a couple of levels of the tree and adjusting column
  21. # widths to suit will display something like:
  22. #
  23. # Call Graph: pt_example
  24. # Call Path Object Count Time(ns) Time(%) Branch Count Branch Count(%)
  25. # v- ls
  26. # v- 2638:2638
  27. # v- _start ld-2.19.so 1 10074071 100.0 211135 100.0
  28. # |- unknown unknown 1 13198 0.1 1 0.0
  29. # >- _dl_start ld-2.19.so 1 1400980 13.9 19637 9.3
  30. # >- _d_linit_internal ld-2.19.so 1 448152 4.4 11094 5.3
  31. # v-__libc_start_main@plt ls 1 8211741 81.5 180397 85.4
  32. # >- _dl_fixup ld-2.19.so 1 7607 0.1 108 0.1
  33. # >- __cxa_atexit libc-2.19.so 1 11737 0.1 10 0.0
  34. # >- __libc_csu_init ls 1 10354 0.1 10 0.0
  35. # |- _setjmp libc-2.19.so 1 0 0.0 4 0.0
  36. # v- main ls 1 8182043 99.6 180254 99.9
  37. #
  38. # Points to note:
  39. # The top level is a command name (comm)
  40. # The next level is a thread (pid:tid)
  41. # Subsequent levels are functions
  42. # 'Count' is the number of calls
  43. # 'Time' is the elapsed time until the function returns
  44. # Percentages are relative to the level above
  45. # 'Branch Count' is the total number of branches for that function and all
  46. # functions that it calls
  47. # There is also a "All branches" report, which displays branches and
  48. # possibly disassembly. However, presently, the only supported disassembler is
  49. # Intel XED, and additionally the object code must be present in perf build ID
  50. # cache. To use Intel XED, libxed.so must be present. To build and install
  51. # libxed.so:
  52. # git clone https://github.com/intelxed/mbuild.git mbuild
  53. # git clone https://github.com/intelxed/xed
  54. # cd xed
  55. # ./mfile.py --share
  56. # sudo ./mfile.py --prefix=/usr/local install
  57. # sudo ldconfig
  58. #
  59. # Example report:
  60. #
  61. # Time CPU Command PID TID Branch Type In Tx Branch
  62. # 8107675239590 2 ls 22011 22011 return from interrupt No ffffffff86a00a67 native_irq_return_iret ([kernel]) -> 7fab593ea260 _start (ld-2.19.so)
  63. # 7fab593ea260 48 89 e7 mov %rsp, %rdi
  64. # 8107675239899 2 ls 22011 22011 hardware interrupt No 7fab593ea260 _start (ld-2.19.so) -> ffffffff86a012e0 page_fault ([kernel])
  65. # 8107675241900 2 ls 22011 22011 return from interrupt No ffffffff86a00a67 native_irq_return_iret ([kernel]) -> 7fab593ea260 _start (ld-2.19.so)
  66. # 7fab593ea260 48 89 e7 mov %rsp, %rdi
  67. # 7fab593ea263 e8 c8 06 00 00 callq 0x7fab593ea930
  68. # 8107675241900 2 ls 22011 22011 call No 7fab593ea263 _start+0x3 (ld-2.19.so) -> 7fab593ea930 _dl_start (ld-2.19.so)
  69. # 7fab593ea930 55 pushq %rbp
  70. # 7fab593ea931 48 89 e5 mov %rsp, %rbp
  71. # 7fab593ea934 41 57 pushq %r15
  72. # 7fab593ea936 41 56 pushq %r14
  73. # 7fab593ea938 41 55 pushq %r13
  74. # 7fab593ea93a 41 54 pushq %r12
  75. # 7fab593ea93c 53 pushq %rbx
  76. # 7fab593ea93d 48 89 fb mov %rdi, %rbx
  77. # 7fab593ea940 48 83 ec 68 sub $0x68, %rsp
  78. # 7fab593ea944 0f 31 rdtsc
  79. # 7fab593ea946 48 c1 e2 20 shl $0x20, %rdx
  80. # 7fab593ea94a 89 c0 mov %eax, %eax
  81. # 7fab593ea94c 48 09 c2 or %rax, %rdx
  82. # 7fab593ea94f 48 8b 05 1a 15 22 00 movq 0x22151a(%rip), %rax
  83. # 8107675242232 2 ls 22011 22011 hardware interrupt No 7fab593ea94f _dl_start+0x1f (ld-2.19.so) -> ffffffff86a012e0 page_fault ([kernel])
  84. # 8107675242900 2 ls 22011 22011 return from interrupt No ffffffff86a00a67 native_irq_return_iret ([kernel]) -> 7fab593ea94f _dl_start+0x1f (ld-2.19.so)
  85. # 7fab593ea94f 48 8b 05 1a 15 22 00 movq 0x22151a(%rip), %rax
  86. # 7fab593ea956 48 89 15 3b 13 22 00 movq %rdx, 0x22133b(%rip)
  87. # 8107675243232 2 ls 22011 22011 hardware interrupt No 7fab593ea956 _dl_start+0x26 (ld-2.19.so) -> ffffffff86a012e0 page_fault ([kernel])
  88. import sys
  89. import weakref
  90. import threading
  91. import string
  92. import cPickle
  93. import re
  94. import os
  95. from PySide.QtCore import *
  96. from PySide.QtGui import *
  97. from PySide.QtSql import *
  98. from decimal import *
  99. from ctypes import *
  100. from multiprocessing import Process, Array, Value, Event
  101. # Data formatting helpers
  102. def tohex(ip):
  103. if ip < 0:
  104. ip += 1 << 64
  105. return "%x" % ip
  106. def offstr(offset):
  107. if offset:
  108. return "+0x%x" % offset
  109. return ""
  110. def dsoname(name):
  111. if name == "[kernel.kallsyms]":
  112. return "[kernel]"
  113. return name
  114. # Percent to one decimal place
  115. def PercentToOneDP(n, d):
  116. if not d:
  117. return "0.0"
  118. x = (n * Decimal(100)) / d
  119. return str(x.quantize(Decimal(".1"), rounding=ROUND_HALF_UP))
  120. # Helper for queries that must not fail
  121. def QueryExec(query, stmt):
  122. ret = query.exec_(stmt)
  123. if not ret:
  124. raise Exception("Query failed: " + query.lastError().text())
  125. # Background thread
  126. class Thread(QThread):
  127. done = Signal(object)
  128. def __init__(self, task, param=None, parent=None):
  129. super(Thread, self).__init__(parent)
  130. self.task = task
  131. self.param = param
  132. def run(self):
  133. while True:
  134. if self.param is None:
  135. done, result = self.task()
  136. else:
  137. done, result = self.task(self.param)
  138. self.done.emit(result)
  139. if done:
  140. break
  141. # Tree data model
  142. class TreeModel(QAbstractItemModel):
  143. def __init__(self, root, parent=None):
  144. super(TreeModel, self).__init__(parent)
  145. self.root = root
  146. self.last_row_read = 0
  147. def Item(self, parent):
  148. if parent.isValid():
  149. return parent.internalPointer()
  150. else:
  151. return self.root
  152. def rowCount(self, parent):
  153. result = self.Item(parent).childCount()
  154. if result < 0:
  155. result = 0
  156. self.dataChanged.emit(parent, parent)
  157. return result
  158. def hasChildren(self, parent):
  159. return self.Item(parent).hasChildren()
  160. def headerData(self, section, orientation, role):
  161. if role == Qt.TextAlignmentRole:
  162. return self.columnAlignment(section)
  163. if role != Qt.DisplayRole:
  164. return None
  165. if orientation != Qt.Horizontal:
  166. return None
  167. return self.columnHeader(section)
  168. def parent(self, child):
  169. child_item = child.internalPointer()
  170. if child_item is self.root:
  171. return QModelIndex()
  172. parent_item = child_item.getParentItem()
  173. return self.createIndex(parent_item.getRow(), 0, parent_item)
  174. def index(self, row, column, parent):
  175. child_item = self.Item(parent).getChildItem(row)
  176. return self.createIndex(row, column, child_item)
  177. def DisplayData(self, item, index):
  178. return item.getData(index.column())
  179. def FetchIfNeeded(self, row):
  180. if row > self.last_row_read:
  181. self.last_row_read = row
  182. if row + 10 >= self.root.child_count:
  183. self.fetcher.Fetch(glb_chunk_sz)
  184. def columnAlignment(self, column):
  185. return Qt.AlignLeft
  186. def columnFont(self, column):
  187. return None
  188. def data(self, index, role):
  189. if role == Qt.TextAlignmentRole:
  190. return self.columnAlignment(index.column())
  191. if role == Qt.FontRole:
  192. return self.columnFont(index.column())
  193. if role != Qt.DisplayRole:
  194. return None
  195. item = index.internalPointer()
  196. return self.DisplayData(item, index)
  197. # Table data model
  198. class TableModel(QAbstractTableModel):
  199. def __init__(self, parent=None):
  200. super(TableModel, self).__init__(parent)
  201. self.child_count = 0
  202. self.child_items = []
  203. self.last_row_read = 0
  204. def Item(self, parent):
  205. if parent.isValid():
  206. return parent.internalPointer()
  207. else:
  208. return self
  209. def rowCount(self, parent):
  210. return self.child_count
  211. def headerData(self, section, orientation, role):
  212. if role == Qt.TextAlignmentRole:
  213. return self.columnAlignment(section)
  214. if role != Qt.DisplayRole:
  215. return None
  216. if orientation != Qt.Horizontal:
  217. return None
  218. return self.columnHeader(section)
  219. def index(self, row, column, parent):
  220. return self.createIndex(row, column, self.child_items[row])
  221. def DisplayData(self, item, index):
  222. return item.getData(index.column())
  223. def FetchIfNeeded(self, row):
  224. if row > self.last_row_read:
  225. self.last_row_read = row
  226. if row + 10 >= self.child_count:
  227. self.fetcher.Fetch(glb_chunk_sz)
  228. def columnAlignment(self, column):
  229. return Qt.AlignLeft
  230. def columnFont(self, column):
  231. return None
  232. def data(self, index, role):
  233. if role == Qt.TextAlignmentRole:
  234. return self.columnAlignment(index.column())
  235. if role == Qt.FontRole:
  236. return self.columnFont(index.column())
  237. if role != Qt.DisplayRole:
  238. return None
  239. item = index.internalPointer()
  240. return self.DisplayData(item, index)
  241. # Model cache
  242. model_cache = weakref.WeakValueDictionary()
  243. model_cache_lock = threading.Lock()
  244. def LookupCreateModel(model_name, create_fn):
  245. model_cache_lock.acquire()
  246. try:
  247. model = model_cache[model_name]
  248. except:
  249. model = None
  250. if model is None:
  251. model = create_fn()
  252. model_cache[model_name] = model
  253. model_cache_lock.release()
  254. return model
  255. # Find bar
  256. class FindBar():
  257. def __init__(self, parent, finder, is_reg_expr=False):
  258. self.finder = finder
  259. self.context = []
  260. self.last_value = None
  261. self.last_pattern = None
  262. label = QLabel("Find:")
  263. label.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
  264. self.textbox = QComboBox()
  265. self.textbox.setEditable(True)
  266. self.textbox.currentIndexChanged.connect(self.ValueChanged)
  267. self.progress = QProgressBar()
  268. self.progress.setRange(0, 0)
  269. self.progress.hide()
  270. if is_reg_expr:
  271. self.pattern = QCheckBox("Regular Expression")
  272. else:
  273. self.pattern = QCheckBox("Pattern")
  274. self.pattern.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
  275. self.next_button = QToolButton()
  276. self.next_button.setIcon(parent.style().standardIcon(QStyle.SP_ArrowDown))
  277. self.next_button.released.connect(lambda: self.NextPrev(1))
  278. self.prev_button = QToolButton()
  279. self.prev_button.setIcon(parent.style().standardIcon(QStyle.SP_ArrowUp))
  280. self.prev_button.released.connect(lambda: self.NextPrev(-1))
  281. self.close_button = QToolButton()
  282. self.close_button.setIcon(parent.style().standardIcon(QStyle.SP_DockWidgetCloseButton))
  283. self.close_button.released.connect(self.Deactivate)
  284. self.hbox = QHBoxLayout()
  285. self.hbox.setContentsMargins(0, 0, 0, 0)
  286. self.hbox.addWidget(label)
  287. self.hbox.addWidget(self.textbox)
  288. self.hbox.addWidget(self.progress)
  289. self.hbox.addWidget(self.pattern)
  290. self.hbox.addWidget(self.next_button)
  291. self.hbox.addWidget(self.prev_button)
  292. self.hbox.addWidget(self.close_button)
  293. self.bar = QWidget()
  294. self.bar.setLayout(self.hbox);
  295. self.bar.hide()
  296. def Widget(self):
  297. return self.bar
  298. def Activate(self):
  299. self.bar.show()
  300. self.textbox.setFocus()
  301. def Deactivate(self):
  302. self.bar.hide()
  303. def Busy(self):
  304. self.textbox.setEnabled(False)
  305. self.pattern.hide()
  306. self.next_button.hide()
  307. self.prev_button.hide()
  308. self.progress.show()
  309. def Idle(self):
  310. self.textbox.setEnabled(True)
  311. self.progress.hide()
  312. self.pattern.show()
  313. self.next_button.show()
  314. self.prev_button.show()
  315. def Find(self, direction):
  316. value = self.textbox.currentText()
  317. pattern = self.pattern.isChecked()
  318. self.last_value = value
  319. self.last_pattern = pattern
  320. self.finder.Find(value, direction, pattern, self.context)
  321. def ValueChanged(self):
  322. value = self.textbox.currentText()
  323. pattern = self.pattern.isChecked()
  324. index = self.textbox.currentIndex()
  325. data = self.textbox.itemData(index)
  326. # Store the pattern in the combo box to keep it with the text value
  327. if data == None:
  328. self.textbox.setItemData(index, pattern)
  329. else:
  330. self.pattern.setChecked(data)
  331. self.Find(0)
  332. def NextPrev(self, direction):
  333. value = self.textbox.currentText()
  334. pattern = self.pattern.isChecked()
  335. if value != self.last_value:
  336. index = self.textbox.findText(value)
  337. # Allow for a button press before the value has been added to the combo box
  338. if index < 0:
  339. index = self.textbox.count()
  340. self.textbox.addItem(value, pattern)
  341. self.textbox.setCurrentIndex(index)
  342. return
  343. else:
  344. self.textbox.setItemData(index, pattern)
  345. elif pattern != self.last_pattern:
  346. # Keep the pattern recorded in the combo box up to date
  347. index = self.textbox.currentIndex()
  348. self.textbox.setItemData(index, pattern)
  349. self.Find(direction)
  350. def NotFound(self):
  351. QMessageBox.information(self.bar, "Find", "'" + self.textbox.currentText() + "' not found")
  352. # Context-sensitive call graph data model item base
  353. class CallGraphLevelItemBase(object):
  354. def __init__(self, glb, row, parent_item):
  355. self.glb = glb
  356. self.row = row
  357. self.parent_item = parent_item
  358. self.query_done = False;
  359. self.child_count = 0
  360. self.child_items = []
  361. def getChildItem(self, row):
  362. return self.child_items[row]
  363. def getParentItem(self):
  364. return self.parent_item
  365. def getRow(self):
  366. return self.row
  367. def childCount(self):
  368. if not self.query_done:
  369. self.Select()
  370. if not self.child_count:
  371. return -1
  372. return self.child_count
  373. def hasChildren(self):
  374. if not self.query_done:
  375. return True
  376. return self.child_count > 0
  377. def getData(self, column):
  378. return self.data[column]
  379. # Context-sensitive call graph data model level 2+ item base
  380. class CallGraphLevelTwoPlusItemBase(CallGraphLevelItemBase):
  381. def __init__(self, glb, row, comm_id, thread_id, call_path_id, time, branch_count, parent_item):
  382. super(CallGraphLevelTwoPlusItemBase, self).__init__(glb, row, parent_item)
  383. self.comm_id = comm_id
  384. self.thread_id = thread_id
  385. self.call_path_id = call_path_id
  386. self.branch_count = branch_count
  387. self.time = time
  388. def Select(self):
  389. self.query_done = True;
  390. query = QSqlQuery(self.glb.db)
  391. QueryExec(query, "SELECT call_path_id, name, short_name, COUNT(calls.id), SUM(return_time - call_time), SUM(branch_count)"
  392. " FROM calls"
  393. " INNER JOIN call_paths ON calls.call_path_id = call_paths.id"
  394. " INNER JOIN symbols ON call_paths.symbol_id = symbols.id"
  395. " INNER JOIN dsos ON symbols.dso_id = dsos.id"
  396. " WHERE parent_call_path_id = " + str(self.call_path_id) +
  397. " AND comm_id = " + str(self.comm_id) +
  398. " AND thread_id = " + str(self.thread_id) +
  399. " GROUP BY call_path_id, name, short_name"
  400. " ORDER BY call_path_id")
  401. while query.next():
  402. child_item = CallGraphLevelThreeItem(self.glb, self.child_count, self.comm_id, self.thread_id, query.value(0), query.value(1), query.value(2), query.value(3), int(query.value(4)), int(query.value(5)), self)
  403. self.child_items.append(child_item)
  404. self.child_count += 1
  405. # Context-sensitive call graph data model level three item
  406. class CallGraphLevelThreeItem(CallGraphLevelTwoPlusItemBase):
  407. def __init__(self, glb, row, comm_id, thread_id, call_path_id, name, dso, count, time, branch_count, parent_item):
  408. super(CallGraphLevelThreeItem, self).__init__(glb, row, comm_id, thread_id, call_path_id, time, branch_count, parent_item)
  409. dso = dsoname(dso)
  410. self.data = [ name, dso, str(count), str(time), PercentToOneDP(time, parent_item.time), str(branch_count), PercentToOneDP(branch_count, parent_item.branch_count) ]
  411. self.dbid = call_path_id
  412. # Context-sensitive call graph data model level two item
  413. class CallGraphLevelTwoItem(CallGraphLevelTwoPlusItemBase):
  414. def __init__(self, glb, row, comm_id, thread_id, pid, tid, parent_item):
  415. super(CallGraphLevelTwoItem, self).__init__(glb, row, comm_id, thread_id, 1, 0, 0, parent_item)
  416. self.data = [str(pid) + ":" + str(tid), "", "", "", "", "", ""]
  417. self.dbid = thread_id
  418. def Select(self):
  419. super(CallGraphLevelTwoItem, self).Select()
  420. for child_item in self.child_items:
  421. self.time += child_item.time
  422. self.branch_count += child_item.branch_count
  423. for child_item in self.child_items:
  424. child_item.data[4] = PercentToOneDP(child_item.time, self.time)
  425. child_item.data[6] = PercentToOneDP(child_item.branch_count, self.branch_count)
  426. # Context-sensitive call graph data model level one item
  427. class CallGraphLevelOneItem(CallGraphLevelItemBase):
  428. def __init__(self, glb, row, comm_id, comm, parent_item):
  429. super(CallGraphLevelOneItem, self).__init__(glb, row, parent_item)
  430. self.data = [comm, "", "", "", "", "", ""]
  431. self.dbid = comm_id
  432. def Select(self):
  433. self.query_done = True;
  434. query = QSqlQuery(self.glb.db)
  435. QueryExec(query, "SELECT thread_id, pid, tid"
  436. " FROM comm_threads"
  437. " INNER JOIN threads ON thread_id = threads.id"
  438. " WHERE comm_id = " + str(self.dbid))
  439. while query.next():
  440. child_item = CallGraphLevelTwoItem(self.glb, self.child_count, self.dbid, query.value(0), query.value(1), query.value(2), self)
  441. self.child_items.append(child_item)
  442. self.child_count += 1
  443. # Context-sensitive call graph data model root item
  444. class CallGraphRootItem(CallGraphLevelItemBase):
  445. def __init__(self, glb):
  446. super(CallGraphRootItem, self).__init__(glb, 0, None)
  447. self.dbid = 0
  448. self.query_done = True;
  449. query = QSqlQuery(glb.db)
  450. QueryExec(query, "SELECT id, comm FROM comms")
  451. while query.next():
  452. if not query.value(0):
  453. continue
  454. child_item = CallGraphLevelOneItem(glb, self.child_count, query.value(0), query.value(1), self)
  455. self.child_items.append(child_item)
  456. self.child_count += 1
  457. # Context-sensitive call graph data model
  458. class CallGraphModel(TreeModel):
  459. def __init__(self, glb, parent=None):
  460. super(CallGraphModel, self).__init__(CallGraphRootItem(glb), parent)
  461. self.glb = glb
  462. def columnCount(self, parent=None):
  463. return 7
  464. def columnHeader(self, column):
  465. headers = ["Call Path", "Object", "Count ", "Time (ns) ", "Time (%) ", "Branch Count ", "Branch Count (%) "]
  466. return headers[column]
  467. def columnAlignment(self, column):
  468. alignment = [ Qt.AlignLeft, Qt.AlignLeft, Qt.AlignRight, Qt.AlignRight, Qt.AlignRight, Qt.AlignRight, Qt.AlignRight ]
  469. return alignment[column]
  470. def FindSelect(self, value, pattern, query):
  471. if pattern:
  472. # postgresql and sqlite pattern patching differences:
  473. # postgresql LIKE is case sensitive but sqlite LIKE is not
  474. # postgresql LIKE allows % and _ to be escaped with \ but sqlite LIKE does not
  475. # postgresql supports ILIKE which is case insensitive
  476. # sqlite supports GLOB (text only) which uses * and ? and is case sensitive
  477. if not self.glb.dbref.is_sqlite3:
  478. # Escape % and _
  479. s = value.replace("%", "\%")
  480. s = s.replace("_", "\_")
  481. # Translate * and ? into SQL LIKE pattern characters % and _
  482. trans = string.maketrans("*?", "%_")
  483. match = " LIKE '" + str(s).translate(trans) + "'"
  484. else:
  485. match = " GLOB '" + str(value) + "'"
  486. else:
  487. match = " = '" + str(value) + "'"
  488. QueryExec(query, "SELECT call_path_id, comm_id, thread_id"
  489. " FROM calls"
  490. " INNER JOIN call_paths ON calls.call_path_id = call_paths.id"
  491. " INNER JOIN symbols ON call_paths.symbol_id = symbols.id"
  492. " WHERE symbols.name" + match +
  493. " GROUP BY comm_id, thread_id, call_path_id"
  494. " ORDER BY comm_id, thread_id, call_path_id")
  495. def FindPath(self, query):
  496. # Turn the query result into a list of ids that the tree view can walk
  497. # to open the tree at the right place.
  498. ids = []
  499. parent_id = query.value(0)
  500. while parent_id:
  501. ids.insert(0, parent_id)
  502. q2 = QSqlQuery(self.glb.db)
  503. QueryExec(q2, "SELECT parent_id"
  504. " FROM call_paths"
  505. " WHERE id = " + str(parent_id))
  506. if not q2.next():
  507. break
  508. parent_id = q2.value(0)
  509. # The call path root is not used
  510. if ids[0] == 1:
  511. del ids[0]
  512. ids.insert(0, query.value(2))
  513. ids.insert(0, query.value(1))
  514. return ids
  515. def Found(self, query, found):
  516. if found:
  517. return self.FindPath(query)
  518. return []
  519. def FindValue(self, value, pattern, query, last_value, last_pattern):
  520. if last_value == value and pattern == last_pattern:
  521. found = query.first()
  522. else:
  523. self.FindSelect(value, pattern, query)
  524. found = query.next()
  525. return self.Found(query, found)
  526. def FindNext(self, query):
  527. found = query.next()
  528. if not found:
  529. found = query.first()
  530. return self.Found(query, found)
  531. def FindPrev(self, query):
  532. found = query.previous()
  533. if not found:
  534. found = query.last()
  535. return self.Found(query, found)
  536. def FindThread(self, c):
  537. if c.direction == 0 or c.value != c.last_value or c.pattern != c.last_pattern:
  538. ids = self.FindValue(c.value, c.pattern, c.query, c.last_value, c.last_pattern)
  539. elif c.direction > 0:
  540. ids = self.FindNext(c.query)
  541. else:
  542. ids = self.FindPrev(c.query)
  543. return (True, ids)
  544. def Find(self, value, direction, pattern, context, callback):
  545. class Context():
  546. def __init__(self, *x):
  547. self.value, self.direction, self.pattern, self.query, self.last_value, self.last_pattern = x
  548. def Update(self, *x):
  549. self.value, self.direction, self.pattern, self.last_value, self.last_pattern = x + (self.value, self.pattern)
  550. if len(context):
  551. context[0].Update(value, direction, pattern)
  552. else:
  553. context.append(Context(value, direction, pattern, QSqlQuery(self.glb.db), None, None))
  554. # Use a thread so the UI is not blocked during the SELECT
  555. thread = Thread(self.FindThread, context[0])
  556. thread.done.connect(lambda ids, t=thread, c=callback: self.FindDone(t, c, ids), Qt.QueuedConnection)
  557. thread.start()
  558. def FindDone(self, thread, callback, ids):
  559. callback(ids)
  560. # Vertical widget layout
  561. class VBox():
  562. def __init__(self, w1, w2, w3=None):
  563. self.vbox = QWidget()
  564. self.vbox.setLayout(QVBoxLayout());
  565. self.vbox.layout().setContentsMargins(0, 0, 0, 0)
  566. self.vbox.layout().addWidget(w1)
  567. self.vbox.layout().addWidget(w2)
  568. if w3:
  569. self.vbox.layout().addWidget(w3)
  570. def Widget(self):
  571. return self.vbox
  572. # Context-sensitive call graph window
  573. class CallGraphWindow(QMdiSubWindow):
  574. def __init__(self, glb, parent=None):
  575. super(CallGraphWindow, self).__init__(parent)
  576. self.model = LookupCreateModel("Context-Sensitive Call Graph", lambda x=glb: CallGraphModel(x))
  577. self.view = QTreeView()
  578. self.view.setModel(self.model)
  579. for c, w in ((0, 250), (1, 100), (2, 60), (3, 70), (4, 70), (5, 100)):
  580. self.view.setColumnWidth(c, w)
  581. self.find_bar = FindBar(self, self)
  582. self.vbox = VBox(self.view, self.find_bar.Widget())
  583. self.setWidget(self.vbox.Widget())
  584. AddSubWindow(glb.mainwindow.mdi_area, self, "Context-Sensitive Call Graph")
  585. def DisplayFound(self, ids):
  586. if not len(ids):
  587. return False
  588. parent = QModelIndex()
  589. for dbid in ids:
  590. found = False
  591. n = self.model.rowCount(parent)
  592. for row in xrange(n):
  593. child = self.model.index(row, 0, parent)
  594. if child.internalPointer().dbid == dbid:
  595. found = True
  596. self.view.setCurrentIndex(child)
  597. parent = child
  598. break
  599. if not found:
  600. break
  601. return found
  602. def Find(self, value, direction, pattern, context):
  603. self.view.setFocus()
  604. self.find_bar.Busy()
  605. self.model.Find(value, direction, pattern, context, self.FindDone)
  606. def FindDone(self, ids):
  607. found = True
  608. if not self.DisplayFound(ids):
  609. found = False
  610. self.find_bar.Idle()
  611. if not found:
  612. self.find_bar.NotFound()
  613. # Child data item finder
  614. class ChildDataItemFinder():
  615. def __init__(self, root):
  616. self.root = root
  617. self.value, self.direction, self.pattern, self.last_value, self.last_pattern = (None,) * 5
  618. self.rows = []
  619. self.pos = 0
  620. def FindSelect(self):
  621. self.rows = []
  622. if self.pattern:
  623. pattern = re.compile(self.value)
  624. for child in self.root.child_items:
  625. for column_data in child.data:
  626. if re.search(pattern, str(column_data)) is not None:
  627. self.rows.append(child.row)
  628. break
  629. else:
  630. for child in self.root.child_items:
  631. for column_data in child.data:
  632. if self.value in str(column_data):
  633. self.rows.append(child.row)
  634. break
  635. def FindValue(self):
  636. self.pos = 0
  637. if self.last_value != self.value or self.pattern != self.last_pattern:
  638. self.FindSelect()
  639. if not len(self.rows):
  640. return -1
  641. return self.rows[self.pos]
  642. def FindThread(self):
  643. if self.direction == 0 or self.value != self.last_value or self.pattern != self.last_pattern:
  644. row = self.FindValue()
  645. elif len(self.rows):
  646. if self.direction > 0:
  647. self.pos += 1
  648. if self.pos >= len(self.rows):
  649. self.pos = 0
  650. else:
  651. self.pos -= 1
  652. if self.pos < 0:
  653. self.pos = len(self.rows) - 1
  654. row = self.rows[self.pos]
  655. else:
  656. row = -1
  657. return (True, row)
  658. def Find(self, value, direction, pattern, context, callback):
  659. self.value, self.direction, self.pattern, self.last_value, self.last_pattern = (value, direction,pattern, self.value, self.pattern)
  660. # Use a thread so the UI is not blocked
  661. thread = Thread(self.FindThread)
  662. thread.done.connect(lambda row, t=thread, c=callback: self.FindDone(t, c, row), Qt.QueuedConnection)
  663. thread.start()
  664. def FindDone(self, thread, callback, row):
  665. callback(row)
  666. # Number of database records to fetch in one go
  667. glb_chunk_sz = 10000
  668. # size of pickled integer big enough for record size
  669. glb_nsz = 8
  670. # Background process for SQL data fetcher
  671. class SQLFetcherProcess():
  672. def __init__(self, dbref, sql, buffer, head, tail, fetch_count, fetching_done, process_target, wait_event, fetched_event, prep):
  673. # Need a unique connection name
  674. conn_name = "SQLFetcher" + str(os.getpid())
  675. self.db, dbname = dbref.Open(conn_name)
  676. self.sql = sql
  677. self.buffer = buffer
  678. self.head = head
  679. self.tail = tail
  680. self.fetch_count = fetch_count
  681. self.fetching_done = fetching_done
  682. self.process_target = process_target
  683. self.wait_event = wait_event
  684. self.fetched_event = fetched_event
  685. self.prep = prep
  686. self.query = QSqlQuery(self.db)
  687. self.query_limit = 0 if "$$last_id$$" in sql else 2
  688. self.last_id = -1
  689. self.fetched = 0
  690. self.more = True
  691. self.local_head = self.head.value
  692. self.local_tail = self.tail.value
  693. def Select(self):
  694. if self.query_limit:
  695. if self.query_limit == 1:
  696. return
  697. self.query_limit -= 1
  698. stmt = self.sql.replace("$$last_id$$", str(self.last_id))
  699. QueryExec(self.query, stmt)
  700. def Next(self):
  701. if not self.query.next():
  702. self.Select()
  703. if not self.query.next():
  704. return None
  705. self.last_id = self.query.value(0)
  706. return self.prep(self.query)
  707. def WaitForTarget(self):
  708. while True:
  709. self.wait_event.clear()
  710. target = self.process_target.value
  711. if target > self.fetched or target < 0:
  712. break
  713. self.wait_event.wait()
  714. return target
  715. def HasSpace(self, sz):
  716. if self.local_tail <= self.local_head:
  717. space = len(self.buffer) - self.local_head
  718. if space > sz:
  719. return True
  720. if space >= glb_nsz:
  721. # Use 0 (or space < glb_nsz) to mean there is no more at the top of the buffer
  722. nd = cPickle.dumps(0, cPickle.HIGHEST_PROTOCOL)
  723. self.buffer[self.local_head : self.local_head + len(nd)] = nd
  724. self.local_head = 0
  725. if self.local_tail - self.local_head > sz:
  726. return True
  727. return False
  728. def WaitForSpace(self, sz):
  729. if self.HasSpace(sz):
  730. return
  731. while True:
  732. self.wait_event.clear()
  733. self.local_tail = self.tail.value
  734. if self.HasSpace(sz):
  735. return
  736. self.wait_event.wait()
  737. def AddToBuffer(self, obj):
  738. d = cPickle.dumps(obj, cPickle.HIGHEST_PROTOCOL)
  739. n = len(d)
  740. nd = cPickle.dumps(n, cPickle.HIGHEST_PROTOCOL)
  741. sz = n + glb_nsz
  742. self.WaitForSpace(sz)
  743. pos = self.local_head
  744. self.buffer[pos : pos + len(nd)] = nd
  745. self.buffer[pos + glb_nsz : pos + sz] = d
  746. self.local_head += sz
  747. def FetchBatch(self, batch_size):
  748. fetched = 0
  749. while batch_size > fetched:
  750. obj = self.Next()
  751. if obj is None:
  752. self.more = False
  753. break
  754. self.AddToBuffer(obj)
  755. fetched += 1
  756. if fetched:
  757. self.fetched += fetched
  758. with self.fetch_count.get_lock():
  759. self.fetch_count.value += fetched
  760. self.head.value = self.local_head
  761. self.fetched_event.set()
  762. def Run(self):
  763. while self.more:
  764. target = self.WaitForTarget()
  765. if target < 0:
  766. break
  767. batch_size = min(glb_chunk_sz, target - self.fetched)
  768. self.FetchBatch(batch_size)
  769. self.fetching_done.value = True
  770. self.fetched_event.set()
  771. def SQLFetcherFn(*x):
  772. process = SQLFetcherProcess(*x)
  773. process.Run()
  774. # SQL data fetcher
  775. class SQLFetcher(QObject):
  776. done = Signal(object)
  777. def __init__(self, glb, sql, prep, process_data, parent=None):
  778. super(SQLFetcher, self).__init__(parent)
  779. self.process_data = process_data
  780. self.more = True
  781. self.target = 0
  782. self.last_target = 0
  783. self.fetched = 0
  784. self.buffer_size = 16 * 1024 * 1024
  785. self.buffer = Array(c_char, self.buffer_size, lock=False)
  786. self.head = Value(c_longlong)
  787. self.tail = Value(c_longlong)
  788. self.local_tail = 0
  789. self.fetch_count = Value(c_longlong)
  790. self.fetching_done = Value(c_bool)
  791. self.last_count = 0
  792. self.process_target = Value(c_longlong)
  793. self.wait_event = Event()
  794. self.fetched_event = Event()
  795. glb.AddInstanceToShutdownOnExit(self)
  796. self.process = Process(target=SQLFetcherFn, args=(glb.dbref, sql, self.buffer, self.head, self.tail, self.fetch_count, self.fetching_done, self.process_target, self.wait_event, self.fetched_event, prep))
  797. self.process.start()
  798. self.thread = Thread(self.Thread)
  799. self.thread.done.connect(self.ProcessData, Qt.QueuedConnection)
  800. self.thread.start()
  801. def Shutdown(self):
  802. # Tell the thread and process to exit
  803. self.process_target.value = -1
  804. self.wait_event.set()
  805. self.more = False
  806. self.fetching_done.value = True
  807. self.fetched_event.set()
  808. def Thread(self):
  809. if not self.more:
  810. return True, 0
  811. while True:
  812. self.fetched_event.clear()
  813. fetch_count = self.fetch_count.value
  814. if fetch_count != self.last_count:
  815. break
  816. if self.fetching_done.value:
  817. self.more = False
  818. return True, 0
  819. self.fetched_event.wait()
  820. count = fetch_count - self.last_count
  821. self.last_count = fetch_count
  822. self.fetched += count
  823. return False, count
  824. def Fetch(self, nr):
  825. if not self.more:
  826. # -1 inidcates there are no more
  827. return -1
  828. result = self.fetched
  829. extra = result + nr - self.target
  830. if extra > 0:
  831. self.target += extra
  832. # process_target < 0 indicates shutting down
  833. if self.process_target.value >= 0:
  834. self.process_target.value = self.target
  835. self.wait_event.set()
  836. return result
  837. def RemoveFromBuffer(self):
  838. pos = self.local_tail
  839. if len(self.buffer) - pos < glb_nsz:
  840. pos = 0
  841. n = cPickle.loads(self.buffer[pos : pos + glb_nsz])
  842. if n == 0:
  843. pos = 0
  844. n = cPickle.loads(self.buffer[0 : glb_nsz])
  845. pos += glb_nsz
  846. obj = cPickle.loads(self.buffer[pos : pos + n])
  847. self.local_tail = pos + n
  848. return obj
  849. def ProcessData(self, count):
  850. for i in xrange(count):
  851. obj = self.RemoveFromBuffer()
  852. self.process_data(obj)
  853. self.tail.value = self.local_tail
  854. self.wait_event.set()
  855. self.done.emit(count)
  856. # Fetch more records bar
  857. class FetchMoreRecordsBar():
  858. def __init__(self, model, parent):
  859. self.model = model
  860. self.label = QLabel("Number of records (x " + "{:,}".format(glb_chunk_sz) + ") to fetch:")
  861. self.label.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
  862. self.fetch_count = QSpinBox()
  863. self.fetch_count.setRange(1, 1000000)
  864. self.fetch_count.setValue(10)
  865. self.fetch_count.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
  866. self.fetch = QPushButton("Go!")
  867. self.fetch.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
  868. self.fetch.released.connect(self.FetchMoreRecords)
  869. self.progress = QProgressBar()
  870. self.progress.setRange(0, 100)
  871. self.progress.hide()
  872. self.done_label = QLabel("All records fetched")
  873. self.done_label.hide()
  874. self.spacer = QLabel("")
  875. self.close_button = QToolButton()
  876. self.close_button.setIcon(parent.style().standardIcon(QStyle.SP_DockWidgetCloseButton))
  877. self.close_button.released.connect(self.Deactivate)
  878. self.hbox = QHBoxLayout()
  879. self.hbox.setContentsMargins(0, 0, 0, 0)
  880. self.hbox.addWidget(self.label)
  881. self.hbox.addWidget(self.fetch_count)
  882. self.hbox.addWidget(self.fetch)
  883. self.hbox.addWidget(self.spacer)
  884. self.hbox.addWidget(self.progress)
  885. self.hbox.addWidget(self.done_label)
  886. self.hbox.addWidget(self.close_button)
  887. self.bar = QWidget()
  888. self.bar.setLayout(self.hbox);
  889. self.bar.show()
  890. self.in_progress = False
  891. self.model.progress.connect(self.Progress)
  892. self.done = False
  893. if not model.HasMoreRecords():
  894. self.Done()
  895. def Widget(self):
  896. return self.bar
  897. def Activate(self):
  898. self.bar.show()
  899. self.fetch.setFocus()
  900. def Deactivate(self):
  901. self.bar.hide()
  902. def Enable(self, enable):
  903. self.fetch.setEnabled(enable)
  904. self.fetch_count.setEnabled(enable)
  905. def Busy(self):
  906. self.Enable(False)
  907. self.fetch.hide()
  908. self.spacer.hide()
  909. self.progress.show()
  910. def Idle(self):
  911. self.in_progress = False
  912. self.Enable(True)
  913. self.progress.hide()
  914. self.fetch.show()
  915. self.spacer.show()
  916. def Target(self):
  917. return self.fetch_count.value() * glb_chunk_sz
  918. def Done(self):
  919. self.done = True
  920. self.Idle()
  921. self.label.hide()
  922. self.fetch_count.hide()
  923. self.fetch.hide()
  924. self.spacer.hide()
  925. self.done_label.show()
  926. def Progress(self, count):
  927. if self.in_progress:
  928. if count:
  929. percent = ((count - self.start) * 100) / self.Target()
  930. if percent >= 100:
  931. self.Idle()
  932. else:
  933. self.progress.setValue(percent)
  934. if not count:
  935. # Count value of zero means no more records
  936. self.Done()
  937. def FetchMoreRecords(self):
  938. if self.done:
  939. return
  940. self.progress.setValue(0)
  941. self.Busy()
  942. self.in_progress = True
  943. self.start = self.model.FetchMoreRecords(self.Target())
  944. # Brance data model level two item
  945. class BranchLevelTwoItem():
  946. def __init__(self, row, text, parent_item):
  947. self.row = row
  948. self.parent_item = parent_item
  949. self.data = [""] * 8
  950. self.data[7] = text
  951. self.level = 2
  952. def getParentItem(self):
  953. return self.parent_item
  954. def getRow(self):
  955. return self.row
  956. def childCount(self):
  957. return 0
  958. def hasChildren(self):
  959. return False
  960. def getData(self, column):
  961. return self.data[column]
  962. # Brance data model level one item
  963. class BranchLevelOneItem():
  964. def __init__(self, glb, row, data, parent_item):
  965. self.glb = glb
  966. self.row = row
  967. self.parent_item = parent_item
  968. self.child_count = 0
  969. self.child_items = []
  970. self.data = data[1:]
  971. self.dbid = data[0]
  972. self.level = 1
  973. self.query_done = False
  974. def getChildItem(self, row):
  975. return self.child_items[row]
  976. def getParentItem(self):
  977. return self.parent_item
  978. def getRow(self):
  979. return self.row
  980. def Select(self):
  981. self.query_done = True
  982. if not self.glb.have_disassembler:
  983. return
  984. query = QSqlQuery(self.glb.db)
  985. QueryExec(query, "SELECT cpu, to_dso_id, to_symbol_id, to_sym_offset, short_name, long_name, build_id, sym_start, to_ip"
  986. " FROM samples"
  987. " INNER JOIN dsos ON samples.to_dso_id = dsos.id"
  988. " INNER JOIN symbols ON samples.to_symbol_id = symbols.id"
  989. " WHERE samples.id = " + str(self.dbid))
  990. if not query.next():
  991. return
  992. cpu = query.value(0)
  993. dso = query.value(1)
  994. sym = query.value(2)
  995. if dso == 0 or sym == 0:
  996. return
  997. off = query.value(3)
  998. short_name = query.value(4)
  999. long_name = query.value(5)
  1000. build_id = query.value(6)
  1001. sym_start = query.value(7)
  1002. ip = query.value(8)
  1003. QueryExec(query, "SELECT samples.dso_id, symbol_id, sym_offset, sym_start"
  1004. " FROM samples"
  1005. " INNER JOIN symbols ON samples.symbol_id = symbols.id"
  1006. " WHERE samples.id > " + str(self.dbid) + " AND cpu = " + str(cpu) +
  1007. " ORDER BY samples.id"
  1008. " LIMIT 1")
  1009. if not query.next():
  1010. return
  1011. if query.value(0) != dso:
  1012. # Cannot disassemble from one dso to another
  1013. return
  1014. bsym = query.value(1)
  1015. boff = query.value(2)
  1016. bsym_start = query.value(3)
  1017. if bsym == 0:
  1018. return
  1019. tot = bsym_start + boff + 1 - sym_start - off
  1020. if tot <= 0 or tot > 16384:
  1021. return
  1022. inst = self.glb.disassembler.Instruction()
  1023. f = self.glb.FileFromNamesAndBuildId(short_name, long_name, build_id)
  1024. if not f:
  1025. return
  1026. mode = 0 if Is64Bit(f) else 1
  1027. self.glb.disassembler.SetMode(inst, mode)
  1028. buf_sz = tot + 16
  1029. buf = create_string_buffer(tot + 16)
  1030. f.seek(sym_start + off)
  1031. buf.value = f.read(buf_sz)
  1032. buf_ptr = addressof(buf)
  1033. i = 0
  1034. while tot > 0:
  1035. cnt, text = self.glb.disassembler.DisassembleOne(inst, buf_ptr, buf_sz, ip)
  1036. if cnt:
  1037. byte_str = tohex(ip).rjust(16)
  1038. for k in xrange(cnt):
  1039. byte_str += " %02x" % ord(buf[i])
  1040. i += 1
  1041. while k < 15:
  1042. byte_str += " "
  1043. k += 1
  1044. self.child_items.append(BranchLevelTwoItem(0, byte_str + " " + text, self))
  1045. self.child_count += 1
  1046. else:
  1047. return
  1048. buf_ptr += cnt
  1049. tot -= cnt
  1050. buf_sz -= cnt
  1051. ip += cnt
  1052. def childCount(self):
  1053. if not self.query_done:
  1054. self.Select()
  1055. if not self.child_count:
  1056. return -1
  1057. return self.child_count
  1058. def hasChildren(self):
  1059. if not self.query_done:
  1060. return True
  1061. return self.child_count > 0
  1062. def getData(self, column):
  1063. return self.data[column]
  1064. # Brance data model root item
  1065. class BranchRootItem():
  1066. def __init__(self):
  1067. self.child_count = 0
  1068. self.child_items = []
  1069. self.level = 0
  1070. def getChildItem(self, row):
  1071. return self.child_items[row]
  1072. def getParentItem(self):
  1073. return None
  1074. def getRow(self):
  1075. return 0
  1076. def childCount(self):
  1077. return self.child_count
  1078. def hasChildren(self):
  1079. return self.child_count > 0
  1080. def getData(self, column):
  1081. return ""
  1082. # Branch data preparation
  1083. def BranchDataPrep(query):
  1084. data = []
  1085. for i in xrange(0, 8):
  1086. data.append(query.value(i))
  1087. data.append(tohex(query.value(8)).rjust(16) + " " + query.value(9) + offstr(query.value(10)) +
  1088. " (" + dsoname(query.value(11)) + ")" + " -> " +
  1089. tohex(query.value(12)) + " " + query.value(13) + offstr(query.value(14)) +
  1090. " (" + dsoname(query.value(15)) + ")")
  1091. return data
  1092. # Branch data model
  1093. class BranchModel(TreeModel):
  1094. progress = Signal(object)
  1095. def __init__(self, glb, event_id, where_clause, parent=None):
  1096. super(BranchModel, self).__init__(BranchRootItem(), parent)
  1097. self.glb = glb
  1098. self.event_id = event_id
  1099. self.more = True
  1100. self.populated = 0
  1101. sql = ("SELECT samples.id, time, cpu, comm, pid, tid, branch_types.name,"
  1102. " CASE WHEN in_tx = '0' THEN 'No' ELSE 'Yes' END,"
  1103. " ip, symbols.name, sym_offset, dsos.short_name,"
  1104. " to_ip, to_symbols.name, to_sym_offset, to_dsos.short_name"
  1105. " FROM samples"
  1106. " INNER JOIN comms ON comm_id = comms.id"
  1107. " INNER JOIN threads ON thread_id = threads.id"
  1108. " INNER JOIN branch_types ON branch_type = branch_types.id"
  1109. " INNER JOIN symbols ON symbol_id = symbols.id"
  1110. " INNER JOIN symbols to_symbols ON to_symbol_id = to_symbols.id"
  1111. " INNER JOIN dsos ON samples.dso_id = dsos.id"
  1112. " INNER JOIN dsos AS to_dsos ON samples.to_dso_id = to_dsos.id"
  1113. " WHERE samples.id > $$last_id$$" + where_clause +
  1114. " AND evsel_id = " + str(self.event_id) +
  1115. " ORDER BY samples.id"
  1116. " LIMIT " + str(glb_chunk_sz))
  1117. self.fetcher = SQLFetcher(glb, sql, BranchDataPrep, self.AddSample)
  1118. self.fetcher.done.connect(self.Update)
  1119. self.fetcher.Fetch(glb_chunk_sz)
  1120. def columnCount(self, parent=None):
  1121. return 8
  1122. def columnHeader(self, column):
  1123. return ("Time", "CPU", "Command", "PID", "TID", "Branch Type", "In Tx", "Branch")[column]
  1124. def columnFont(self, column):
  1125. if column != 7:
  1126. return None
  1127. return QFont("Monospace")
  1128. def DisplayData(self, item, index):
  1129. if item.level == 1:
  1130. self.FetchIfNeeded(item.row)
  1131. return item.getData(index.column())
  1132. def AddSample(self, data):
  1133. child = BranchLevelOneItem(self.glb, self.populated, data, self.root)
  1134. self.root.child_items.append(child)
  1135. self.populated += 1
  1136. def Update(self, fetched):
  1137. if not fetched:
  1138. self.more = False
  1139. self.progress.emit(0)
  1140. child_count = self.root.child_count
  1141. count = self.populated - child_count
  1142. if count > 0:
  1143. parent = QModelIndex()
  1144. self.beginInsertRows(parent, child_count, child_count + count - 1)
  1145. self.insertRows(child_count, count, parent)
  1146. self.root.child_count += count
  1147. self.endInsertRows()
  1148. self.progress.emit(self.root.child_count)
  1149. def FetchMoreRecords(self, count):
  1150. current = self.root.child_count
  1151. if self.more:
  1152. self.fetcher.Fetch(count)
  1153. else:
  1154. self.progress.emit(0)
  1155. return current
  1156. def HasMoreRecords(self):
  1157. return self.more
  1158. # Branch window
  1159. class BranchWindow(QMdiSubWindow):
  1160. def __init__(self, glb, event_id, name, where_clause, parent=None):
  1161. super(BranchWindow, self).__init__(parent)
  1162. model_name = "Branch Events " + str(event_id)
  1163. if len(where_clause):
  1164. model_name = where_clause + " " + model_name
  1165. self.model = LookupCreateModel(model_name, lambda: BranchModel(glb, event_id, where_clause))
  1166. self.view = QTreeView()
  1167. self.view.setUniformRowHeights(True)
  1168. self.view.setModel(self.model)
  1169. self.ResizeColumnsToContents()
  1170. self.find_bar = FindBar(self, self, True)
  1171. self.finder = ChildDataItemFinder(self.model.root)
  1172. self.fetch_bar = FetchMoreRecordsBar(self.model, self)
  1173. self.vbox = VBox(self.view, self.find_bar.Widget(), self.fetch_bar.Widget())
  1174. self.setWidget(self.vbox.Widget())
  1175. AddSubWindow(glb.mainwindow.mdi_area, self, name + " Branch Events")
  1176. def ResizeColumnToContents(self, column, n):
  1177. # Using the view's resizeColumnToContents() here is extrememly slow
  1178. # so implement a crude alternative
  1179. mm = "MM" if column else "MMMM"
  1180. font = self.view.font()
  1181. metrics = QFontMetrics(font)
  1182. max = 0
  1183. for row in xrange(n):
  1184. val = self.model.root.child_items[row].data[column]
  1185. len = metrics.width(str(val) + mm)
  1186. max = len if len > max else max
  1187. val = self.model.columnHeader(column)
  1188. len = metrics.width(str(val) + mm)
  1189. max = len if len > max else max
  1190. self.view.setColumnWidth(column, max)
  1191. def ResizeColumnsToContents(self):
  1192. n = min(self.model.root.child_count, 100)
  1193. if n < 1:
  1194. # No data yet, so connect a signal to notify when there is
  1195. self.model.rowsInserted.connect(self.UpdateColumnWidths)
  1196. return
  1197. columns = self.model.columnCount()
  1198. for i in xrange(columns):
  1199. self.ResizeColumnToContents(i, n)
  1200. def UpdateColumnWidths(self, *x):
  1201. # This only needs to be done once, so disconnect the signal now
  1202. self.model.rowsInserted.disconnect(self.UpdateColumnWidths)
  1203. self.ResizeColumnsToContents()
  1204. def Find(self, value, direction, pattern, context):
  1205. self.view.setFocus()
  1206. self.find_bar.Busy()
  1207. self.finder.Find(value, direction, pattern, context, self.FindDone)
  1208. def FindDone(self, row):
  1209. self.find_bar.Idle()
  1210. if row >= 0:
  1211. self.view.setCurrentIndex(self.model.index(row, 0, QModelIndex()))
  1212. else:
  1213. self.find_bar.NotFound()
  1214. # Event list
  1215. def GetEventList(db):
  1216. events = []
  1217. query = QSqlQuery(db)
  1218. QueryExec(query, "SELECT name FROM selected_events WHERE id > 0 ORDER BY id")
  1219. while query.next():
  1220. events.append(query.value(0))
  1221. return events
  1222. # SQL data preparation
  1223. def SQLTableDataPrep(query, count):
  1224. data = []
  1225. for i in xrange(count):
  1226. data.append(query.value(i))
  1227. return data
  1228. # SQL table data model item
  1229. class SQLTableItem():
  1230. def __init__(self, row, data):
  1231. self.row = row
  1232. self.data = data
  1233. def getData(self, column):
  1234. return self.data[column]
  1235. # SQL table data model
  1236. class SQLTableModel(TableModel):
  1237. progress = Signal(object)
  1238. def __init__(self, glb, sql, column_count, parent=None):
  1239. super(SQLTableModel, self).__init__(parent)
  1240. self.glb = glb
  1241. self.more = True
  1242. self.populated = 0
  1243. self.fetcher = SQLFetcher(glb, sql, lambda x, y=column_count: SQLTableDataPrep(x, y), self.AddSample)
  1244. self.fetcher.done.connect(self.Update)
  1245. self.fetcher.Fetch(glb_chunk_sz)
  1246. def DisplayData(self, item, index):
  1247. self.FetchIfNeeded(item.row)
  1248. return item.getData(index.column())
  1249. def AddSample(self, data):
  1250. child = SQLTableItem(self.populated, data)
  1251. self.child_items.append(child)
  1252. self.populated += 1
  1253. def Update(self, fetched):
  1254. if not fetched:
  1255. self.more = False
  1256. self.progress.emit(0)
  1257. child_count = self.child_count
  1258. count = self.populated - child_count
  1259. if count > 0:
  1260. parent = QModelIndex()
  1261. self.beginInsertRows(parent, child_count, child_count + count - 1)
  1262. self.insertRows(child_count, count, parent)
  1263. self.child_count += count
  1264. self.endInsertRows()
  1265. self.progress.emit(self.child_count)
  1266. def FetchMoreRecords(self, count):
  1267. current = self.child_count
  1268. if self.more:
  1269. self.fetcher.Fetch(count)
  1270. else:
  1271. self.progress.emit(0)
  1272. return current
  1273. def HasMoreRecords(self):
  1274. return self.more
  1275. # SQL automatic table data model
  1276. class SQLAutoTableModel(SQLTableModel):
  1277. def __init__(self, glb, table_name, parent=None):
  1278. sql = "SELECT * FROM " + table_name + " WHERE id > $$last_id$$ ORDER BY id LIMIT " + str(glb_chunk_sz)
  1279. if table_name == "comm_threads_view":
  1280. # For now, comm_threads_view has no id column
  1281. sql = "SELECT * FROM " + table_name + " WHERE comm_id > $$last_id$$ ORDER BY comm_id LIMIT " + str(glb_chunk_sz)
  1282. self.column_headers = []
  1283. query = QSqlQuery(glb.db)
  1284. if glb.dbref.is_sqlite3:
  1285. QueryExec(query, "PRAGMA table_info(" + table_name + ")")
  1286. while query.next():
  1287. self.column_headers.append(query.value(1))
  1288. if table_name == "sqlite_master":
  1289. sql = "SELECT * FROM " + table_name
  1290. else:
  1291. if table_name[:19] == "information_schema.":
  1292. sql = "SELECT * FROM " + table_name
  1293. select_table_name = table_name[19:]
  1294. schema = "information_schema"
  1295. else:
  1296. select_table_name = table_name
  1297. schema = "public"
  1298. QueryExec(query, "SELECT column_name FROM information_schema.columns WHERE table_schema = '" + schema + "' and table_name = '" + select_table_name + "'")
  1299. while query.next():
  1300. self.column_headers.append(query.value(0))
  1301. super(SQLAutoTableModel, self).__init__(glb, sql, len(self.column_headers), parent)
  1302. def columnCount(self, parent=None):
  1303. return len(self.column_headers)
  1304. def columnHeader(self, column):
  1305. return self.column_headers[column]
  1306. # Base class for custom ResizeColumnsToContents
  1307. class ResizeColumnsToContentsBase(QObject):
  1308. def __init__(self, parent=None):
  1309. super(ResizeColumnsToContentsBase, self).__init__(parent)
  1310. def ResizeColumnToContents(self, column, n):
  1311. # Using the view's resizeColumnToContents() here is extrememly slow
  1312. # so implement a crude alternative
  1313. font = self.view.font()
  1314. metrics = QFontMetrics(font)
  1315. max = 0
  1316. for row in xrange(n):
  1317. val = self.data_model.child_items[row].data[column]
  1318. len = metrics.width(str(val) + "MM")
  1319. max = len if len > max else max
  1320. val = self.data_model.columnHeader(column)
  1321. len = metrics.width(str(val) + "MM")
  1322. max = len if len > max else max
  1323. self.view.setColumnWidth(column, max)
  1324. def ResizeColumnsToContents(self):
  1325. n = min(self.data_model.child_count, 100)
  1326. if n < 1:
  1327. # No data yet, so connect a signal to notify when there is
  1328. self.data_model.rowsInserted.connect(self.UpdateColumnWidths)
  1329. return
  1330. columns = self.data_model.columnCount()
  1331. for i in xrange(columns):
  1332. self.ResizeColumnToContents(i, n)
  1333. def UpdateColumnWidths(self, *x):
  1334. # This only needs to be done once, so disconnect the signal now
  1335. self.data_model.rowsInserted.disconnect(self.UpdateColumnWidths)
  1336. self.ResizeColumnsToContents()
  1337. # Table window
  1338. class TableWindow(QMdiSubWindow, ResizeColumnsToContentsBase):
  1339. def __init__(self, glb, table_name, parent=None):
  1340. super(TableWindow, self).__init__(parent)
  1341. self.data_model = LookupCreateModel(table_name + " Table", lambda: SQLAutoTableModel(glb, table_name))
  1342. self.model = QSortFilterProxyModel()
  1343. self.model.setSourceModel(self.data_model)
  1344. self.view = QTableView()
  1345. self.view.setModel(self.model)
  1346. self.view.setEditTriggers(QAbstractItemView.NoEditTriggers)
  1347. self.view.verticalHeader().setVisible(False)
  1348. self.view.sortByColumn(-1, Qt.AscendingOrder)
  1349. self.view.setSortingEnabled(True)
  1350. self.ResizeColumnsToContents()
  1351. self.find_bar = FindBar(self, self, True)
  1352. self.finder = ChildDataItemFinder(self.data_model)
  1353. self.fetch_bar = FetchMoreRecordsBar(self.data_model, self)
  1354. self.vbox = VBox(self.view, self.find_bar.Widget(), self.fetch_bar.Widget())
  1355. self.setWidget(self.vbox.Widget())
  1356. AddSubWindow(glb.mainwindow.mdi_area, self, table_name + " Table")
  1357. def Find(self, value, direction, pattern, context):
  1358. self.view.setFocus()
  1359. self.find_bar.Busy()
  1360. self.finder.Find(value, direction, pattern, context, self.FindDone)
  1361. def FindDone(self, row):
  1362. self.find_bar.Idle()
  1363. if row >= 0:
  1364. self.view.setCurrentIndex(self.model.index(row, 0, QModelIndex()))
  1365. else:
  1366. self.find_bar.NotFound()
  1367. # Table list
  1368. def GetTableList(glb):
  1369. tables = []
  1370. query = QSqlQuery(glb.db)
  1371. if glb.dbref.is_sqlite3:
  1372. QueryExec(query, "SELECT name FROM sqlite_master WHERE type IN ( 'table' , 'view' ) ORDER BY name")
  1373. else:
  1374. QueryExec(query, "SELECT table_name FROM information_schema.tables WHERE table_schema = 'public' AND table_type IN ( 'BASE TABLE' , 'VIEW' ) ORDER BY table_name")
  1375. while query.next():
  1376. tables.append(query.value(0))
  1377. if glb.dbref.is_sqlite3:
  1378. tables.append("sqlite_master")
  1379. else:
  1380. tables.append("information_schema.tables")
  1381. tables.append("information_schema.views")
  1382. tables.append("information_schema.columns")
  1383. return tables
  1384. # Action Definition
  1385. def CreateAction(label, tip, callback, parent=None, shortcut=None):
  1386. action = QAction(label, parent)
  1387. if shortcut != None:
  1388. action.setShortcuts(shortcut)
  1389. action.setStatusTip(tip)
  1390. action.triggered.connect(callback)
  1391. return action
  1392. # Typical application actions
  1393. def CreateExitAction(app, parent=None):
  1394. return CreateAction("&Quit", "Exit the application", app.closeAllWindows, parent, QKeySequence.Quit)
  1395. # Typical MDI actions
  1396. def CreateCloseActiveWindowAction(mdi_area):
  1397. return CreateAction("Cl&ose", "Close the active window", mdi_area.closeActiveSubWindow, mdi_area)
  1398. def CreateCloseAllWindowsAction(mdi_area):
  1399. return CreateAction("Close &All", "Close all the windows", mdi_area.closeAllSubWindows, mdi_area)
  1400. def CreateTileWindowsAction(mdi_area):
  1401. return CreateAction("&Tile", "Tile the windows", mdi_area.tileSubWindows, mdi_area)
  1402. def CreateCascadeWindowsAction(mdi_area):
  1403. return CreateAction("&Cascade", "Cascade the windows", mdi_area.cascadeSubWindows, mdi_area)
  1404. def CreateNextWindowAction(mdi_area):
  1405. return CreateAction("Ne&xt", "Move the focus to the next window", mdi_area.activateNextSubWindow, mdi_area, QKeySequence.NextChild)
  1406. def CreatePreviousWindowAction(mdi_area):
  1407. return CreateAction("Pre&vious", "Move the focus to the previous window", mdi_area.activatePreviousSubWindow, mdi_area, QKeySequence.PreviousChild)
  1408. # Typical MDI window menu
  1409. class WindowMenu():
  1410. def __init__(self, mdi_area, menu):
  1411. self.mdi_area = mdi_area
  1412. self.window_menu = menu.addMenu("&Windows")
  1413. self.close_active_window = CreateCloseActiveWindowAction(mdi_area)
  1414. self.close_all_windows = CreateCloseAllWindowsAction(mdi_area)
  1415. self.tile_windows = CreateTileWindowsAction(mdi_area)
  1416. self.cascade_windows = CreateCascadeWindowsAction(mdi_area)
  1417. self.next_window = CreateNextWindowAction(mdi_area)
  1418. self.previous_window = CreatePreviousWindowAction(mdi_area)
  1419. self.window_menu.aboutToShow.connect(self.Update)
  1420. def Update(self):
  1421. self.window_menu.clear()
  1422. sub_window_count = len(self.mdi_area.subWindowList())
  1423. have_sub_windows = sub_window_count != 0
  1424. self.close_active_window.setEnabled(have_sub_windows)
  1425. self.close_all_windows.setEnabled(have_sub_windows)
  1426. self.tile_windows.setEnabled(have_sub_windows)
  1427. self.cascade_windows.setEnabled(have_sub_windows)
  1428. self.next_window.setEnabled(have_sub_windows)
  1429. self.previous_window.setEnabled(have_sub_windows)
  1430. self.window_menu.addAction(self.close_active_window)
  1431. self.window_menu.addAction(self.close_all_windows)
  1432. self.window_menu.addSeparator()
  1433. self.window_menu.addAction(self.tile_windows)
  1434. self.window_menu.addAction(self.cascade_windows)
  1435. self.window_menu.addSeparator()
  1436. self.window_menu.addAction(self.next_window)
  1437. self.window_menu.addAction(self.previous_window)
  1438. if sub_window_count == 0:
  1439. return
  1440. self.window_menu.addSeparator()
  1441. nr = 1
  1442. for sub_window in self.mdi_area.subWindowList():
  1443. label = str(nr) + " " + sub_window.name
  1444. if nr < 10:
  1445. label = "&" + label
  1446. action = self.window_menu.addAction(label)
  1447. action.setCheckable(True)
  1448. action.setChecked(sub_window == self.mdi_area.activeSubWindow())
  1449. action.triggered.connect(lambda x=nr: self.setActiveSubWindow(x))
  1450. self.window_menu.addAction(action)
  1451. nr += 1
  1452. def setActiveSubWindow(self, nr):
  1453. self.mdi_area.setActiveSubWindow(self.mdi_area.subWindowList()[nr - 1])
  1454. # Font resize
  1455. def ResizeFont(widget, diff):
  1456. font = widget.font()
  1457. sz = font.pointSize()
  1458. font.setPointSize(sz + diff)
  1459. widget.setFont(font)
  1460. def ShrinkFont(widget):
  1461. ResizeFont(widget, -1)
  1462. def EnlargeFont(widget):
  1463. ResizeFont(widget, 1)
  1464. # Unique name for sub-windows
  1465. def NumberedWindowName(name, nr):
  1466. if nr > 1:
  1467. name += " <" + str(nr) + ">"
  1468. return name
  1469. def UniqueSubWindowName(mdi_area, name):
  1470. nr = 1
  1471. while True:
  1472. unique_name = NumberedWindowName(name, nr)
  1473. ok = True
  1474. for sub_window in mdi_area.subWindowList():
  1475. if sub_window.name == unique_name:
  1476. ok = False
  1477. break
  1478. if ok:
  1479. return unique_name
  1480. nr += 1
  1481. # Add a sub-window
  1482. def AddSubWindow(mdi_area, sub_window, name):
  1483. unique_name = UniqueSubWindowName(mdi_area, name)
  1484. sub_window.setMinimumSize(200, 100)
  1485. sub_window.resize(800, 600)
  1486. sub_window.setWindowTitle(unique_name)
  1487. sub_window.setAttribute(Qt.WA_DeleteOnClose)
  1488. sub_window.setWindowIcon(sub_window.style().standardIcon(QStyle.SP_FileIcon))
  1489. sub_window.name = unique_name
  1490. mdi_area.addSubWindow(sub_window)
  1491. sub_window.show()
  1492. # Main window
  1493. class MainWindow(QMainWindow):
  1494. def __init__(self, glb, parent=None):
  1495. super(MainWindow, self).__init__(parent)
  1496. self.glb = glb
  1497. self.setWindowTitle("Exported SQL Viewer: " + glb.dbname)
  1498. self.setWindowIcon(self.style().standardIcon(QStyle.SP_ComputerIcon))
  1499. self.setMinimumSize(200, 100)
  1500. self.mdi_area = QMdiArea()
  1501. self.mdi_area.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded)
  1502. self.mdi_area.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
  1503. self.setCentralWidget(self.mdi_area)
  1504. menu = self.menuBar()
  1505. file_menu = menu.addMenu("&File")
  1506. file_menu.addAction(CreateExitAction(glb.app, self))
  1507. edit_menu = menu.addMenu("&Edit")
  1508. edit_menu.addAction(CreateAction("&Find...", "Find items", self.Find, self, QKeySequence.Find))
  1509. edit_menu.addAction(CreateAction("Fetch &more records...", "Fetch more records", self.FetchMoreRecords, self, [QKeySequence(Qt.Key_F8)]))
  1510. edit_menu.addAction(CreateAction("&Shrink Font", "Make text smaller", self.ShrinkFont, self, [QKeySequence("Ctrl+-")]))
  1511. edit_menu.addAction(CreateAction("&Enlarge Font", "Make text bigger", self.EnlargeFont, self, [QKeySequence("Ctrl++")]))
  1512. reports_menu = menu.addMenu("&Reports")
  1513. reports_menu.addAction(CreateAction("Context-Sensitive Call &Graph", "Create a new window containing a context-sensitive call graph", self.NewCallGraph, self))
  1514. self.EventMenu(GetEventList(glb.db), reports_menu)
  1515. self.TableMenu(GetTableList(glb), menu)
  1516. self.window_menu = WindowMenu(self.mdi_area, menu)
  1517. def Find(self):
  1518. win = self.mdi_area.activeSubWindow()
  1519. if win:
  1520. try:
  1521. win.find_bar.Activate()
  1522. except:
  1523. pass
  1524. def FetchMoreRecords(self):
  1525. win = self.mdi_area.activeSubWindow()
  1526. if win:
  1527. try:
  1528. win.fetch_bar.Activate()
  1529. except:
  1530. pass
  1531. def ShrinkFont(self):
  1532. win = self.mdi_area.activeSubWindow()
  1533. ShrinkFont(win.view)
  1534. def EnlargeFont(self):
  1535. win = self.mdi_area.activeSubWindow()
  1536. EnlargeFont(win.view)
  1537. def EventMenu(self, events, reports_menu):
  1538. branches_events = 0
  1539. for event in events:
  1540. event = event.split(":")[0]
  1541. if event == "branches":
  1542. branches_events += 1
  1543. dbid = 0
  1544. for event in events:
  1545. dbid += 1
  1546. event = event.split(":")[0]
  1547. if event == "branches":
  1548. label = "All branches" if branches_events == 1 else "All branches " + "(id=" + dbid + ")"
  1549. reports_menu.addAction(CreateAction(label, "Create a new window displaying branch events", lambda x=dbid: self.NewBranchView(x), self))
  1550. def TableMenu(self, tables, menu):
  1551. table_menu = menu.addMenu("&Tables")
  1552. for table in tables:
  1553. table_menu.addAction(CreateAction(table, "Create a new window containing a table view", lambda t=table: self.NewTableView(t), self))
  1554. def NewCallGraph(self):
  1555. CallGraphWindow(self.glb, self)
  1556. def NewBranchView(self, event_id):
  1557. BranchWindow(self.glb, event_id, "", "", self)
  1558. def NewTableView(self, table_name):
  1559. TableWindow(self.glb, table_name, self)
  1560. # XED Disassembler
  1561. class xed_state_t(Structure):
  1562. _fields_ = [
  1563. ("mode", c_int),
  1564. ("width", c_int)
  1565. ]
  1566. class XEDInstruction():
  1567. def __init__(self, libxed):
  1568. # Current xed_decoded_inst_t structure is 192 bytes. Use 512 to allow for future expansion
  1569. xedd_t = c_byte * 512
  1570. self.xedd = xedd_t()
  1571. self.xedp = addressof(self.xedd)
  1572. libxed.xed_decoded_inst_zero(self.xedp)
  1573. self.state = xed_state_t()
  1574. self.statep = addressof(self.state)
  1575. # Buffer for disassembled instruction text
  1576. self.buffer = create_string_buffer(256)
  1577. self.bufferp = addressof(self.buffer)
  1578. class LibXED():
  1579. def __init__(self):
  1580. try:
  1581. self.libxed = CDLL("libxed.so")
  1582. except:
  1583. self.libxed = None
  1584. if not self.libxed:
  1585. self.libxed = CDLL("/usr/local/lib/libxed.so")
  1586. self.xed_tables_init = self.libxed.xed_tables_init
  1587. self.xed_tables_init.restype = None
  1588. self.xed_tables_init.argtypes = []
  1589. self.xed_decoded_inst_zero = self.libxed.xed_decoded_inst_zero
  1590. self.xed_decoded_inst_zero.restype = None
  1591. self.xed_decoded_inst_zero.argtypes = [ c_void_p ]
  1592. self.xed_operand_values_set_mode = self.libxed.xed_operand_values_set_mode
  1593. self.xed_operand_values_set_mode.restype = None
  1594. self.xed_operand_values_set_mode.argtypes = [ c_void_p, c_void_p ]
  1595. self.xed_decoded_inst_zero_keep_mode = self.libxed.xed_decoded_inst_zero_keep_mode
  1596. self.xed_decoded_inst_zero_keep_mode.restype = None
  1597. self.xed_decoded_inst_zero_keep_mode.argtypes = [ c_void_p ]
  1598. self.xed_decode = self.libxed.xed_decode
  1599. self.xed_decode.restype = c_int
  1600. self.xed_decode.argtypes = [ c_void_p, c_void_p, c_uint ]
  1601. self.xed_format_context = self.libxed.xed_format_context
  1602. self.xed_format_context.restype = c_uint
  1603. self.xed_format_context.argtypes = [ c_int, c_void_p, c_void_p, c_int, c_ulonglong, c_void_p, c_void_p ]
  1604. self.xed_tables_init()
  1605. def Instruction(self):
  1606. return XEDInstruction(self)
  1607. def SetMode(self, inst, mode):
  1608. if mode:
  1609. inst.state.mode = 4 # 32-bit
  1610. inst.state.width = 4 # 4 bytes
  1611. else:
  1612. inst.state.mode = 1 # 64-bit
  1613. inst.state.width = 8 # 8 bytes
  1614. self.xed_operand_values_set_mode(inst.xedp, inst.statep)
  1615. def DisassembleOne(self, inst, bytes_ptr, bytes_cnt, ip):
  1616. self.xed_decoded_inst_zero_keep_mode(inst.xedp)
  1617. err = self.xed_decode(inst.xedp, bytes_ptr, bytes_cnt)
  1618. if err:
  1619. return 0, ""
  1620. # Use AT&T mode (2), alternative is Intel (3)
  1621. ok = self.xed_format_context(2, inst.xedp, inst.bufferp, sizeof(inst.buffer), ip, 0, 0)
  1622. if not ok:
  1623. return 0, ""
  1624. # Return instruction length and the disassembled instruction text
  1625. # For now, assume the length is in byte 166
  1626. return inst.xedd[166], inst.buffer.value
  1627. def TryOpen(file_name):
  1628. try:
  1629. return open(file_name, "rb")
  1630. except:
  1631. return None
  1632. def Is64Bit(f):
  1633. result = sizeof(c_void_p)
  1634. # ELF support only
  1635. pos = f.tell()
  1636. f.seek(0)
  1637. header = f.read(7)
  1638. f.seek(pos)
  1639. magic = header[0:4]
  1640. eclass = ord(header[4])
  1641. encoding = ord(header[5])
  1642. version = ord(header[6])
  1643. if magic == chr(127) + "ELF" and eclass > 0 and eclass < 3 and encoding > 0 and encoding < 3 and version == 1:
  1644. result = True if eclass == 2 else False
  1645. return result
  1646. # Global data
  1647. class Glb():
  1648. def __init__(self, dbref, db, dbname):
  1649. self.dbref = dbref
  1650. self.db = db
  1651. self.dbname = dbname
  1652. self.home_dir = os.path.expanduser("~")
  1653. self.buildid_dir = os.getenv("PERF_BUILDID_DIR")
  1654. if self.buildid_dir:
  1655. self.buildid_dir += "/.build-id/"
  1656. else:
  1657. self.buildid_dir = self.home_dir + "/.debug/.build-id/"
  1658. self.app = None
  1659. self.mainwindow = None
  1660. self.instances_to_shutdown_on_exit = weakref.WeakSet()
  1661. try:
  1662. self.disassembler = LibXED()
  1663. self.have_disassembler = True
  1664. except:
  1665. self.have_disassembler = False
  1666. def FileFromBuildId(self, build_id):
  1667. file_name = self.buildid_dir + build_id[0:2] + "/" + build_id[2:] + "/elf"
  1668. return TryOpen(file_name)
  1669. def FileFromNamesAndBuildId(self, short_name, long_name, build_id):
  1670. # Assume current machine i.e. no support for virtualization
  1671. if short_name[0:7] == "[kernel" and os.path.basename(long_name) == "kcore":
  1672. file_name = os.getenv("PERF_KCORE")
  1673. f = TryOpen(file_name) if file_name else None
  1674. if f:
  1675. return f
  1676. # For now, no special handling if long_name is /proc/kcore
  1677. f = TryOpen(long_name)
  1678. if f:
  1679. return f
  1680. f = self.FileFromBuildId(build_id)
  1681. if f:
  1682. return f
  1683. return None
  1684. def AddInstanceToShutdownOnExit(self, instance):
  1685. self.instances_to_shutdown_on_exit.add(instance)
  1686. # Shutdown any background processes or threads
  1687. def ShutdownInstances(self):
  1688. for x in self.instances_to_shutdown_on_exit:
  1689. try:
  1690. x.Shutdown()
  1691. except:
  1692. pass
  1693. # Database reference
  1694. class DBRef():
  1695. def __init__(self, is_sqlite3, dbname):
  1696. self.is_sqlite3 = is_sqlite3
  1697. self.dbname = dbname
  1698. def Open(self, connection_name):
  1699. dbname = self.dbname
  1700. if self.is_sqlite3:
  1701. db = QSqlDatabase.addDatabase("QSQLITE", connection_name)
  1702. else:
  1703. db = QSqlDatabase.addDatabase("QPSQL", connection_name)
  1704. opts = dbname.split()
  1705. for opt in opts:
  1706. if "=" in opt:
  1707. opt = opt.split("=")
  1708. if opt[0] == "hostname":
  1709. db.setHostName(opt[1])
  1710. elif opt[0] == "port":
  1711. db.setPort(int(opt[1]))
  1712. elif opt[0] == "username":
  1713. db.setUserName(opt[1])
  1714. elif opt[0] == "password":
  1715. db.setPassword(opt[1])
  1716. elif opt[0] == "dbname":
  1717. dbname = opt[1]
  1718. else:
  1719. dbname = opt
  1720. db.setDatabaseName(dbname)
  1721. if not db.open():
  1722. raise Exception("Failed to open database " + dbname + " error: " + db.lastError().text())
  1723. return db, dbname
  1724. # Main
  1725. def Main():
  1726. if (len(sys.argv) < 2):
  1727. print >> sys.stderr, "Usage is: exported-sql-viewer.py <database name>"
  1728. raise Exception("Too few arguments")
  1729. dbname = sys.argv[1]
  1730. is_sqlite3 = False
  1731. try:
  1732. f = open(dbname)
  1733. if f.read(15) == "SQLite format 3":
  1734. is_sqlite3 = True
  1735. f.close()
  1736. except:
  1737. pass
  1738. dbref = DBRef(is_sqlite3, dbname)
  1739. db, dbname = dbref.Open("main")
  1740. glb = Glb(dbref, db, dbname)
  1741. app = QApplication(sys.argv)
  1742. glb.app = app
  1743. mainwindow = MainWindow(glb)
  1744. glb.mainwindow = mainwindow
  1745. mainwindow.show()
  1746. err = app.exec_()
  1747. glb.ShutdownInstances()
  1748. db.close()
  1749. sys.exit(err)
  1750. if __name__ == "__main__":
  1751. Main()