exported-sql-viewer.py 64 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128
  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. self.libxed = CDLL("libxed.so")
  1581. self.xed_tables_init = self.libxed.xed_tables_init
  1582. self.xed_tables_init.restype = None
  1583. self.xed_tables_init.argtypes = []
  1584. self.xed_decoded_inst_zero = self.libxed.xed_decoded_inst_zero
  1585. self.xed_decoded_inst_zero.restype = None
  1586. self.xed_decoded_inst_zero.argtypes = [ c_void_p ]
  1587. self.xed_operand_values_set_mode = self.libxed.xed_operand_values_set_mode
  1588. self.xed_operand_values_set_mode.restype = None
  1589. self.xed_operand_values_set_mode.argtypes = [ c_void_p, c_void_p ]
  1590. self.xed_decoded_inst_zero_keep_mode = self.libxed.xed_decoded_inst_zero_keep_mode
  1591. self.xed_decoded_inst_zero_keep_mode.restype = None
  1592. self.xed_decoded_inst_zero_keep_mode.argtypes = [ c_void_p ]
  1593. self.xed_decode = self.libxed.xed_decode
  1594. self.xed_decode.restype = c_int
  1595. self.xed_decode.argtypes = [ c_void_p, c_void_p, c_uint ]
  1596. self.xed_format_context = self.libxed.xed_format_context
  1597. self.xed_format_context.restype = c_uint
  1598. self.xed_format_context.argtypes = [ c_int, c_void_p, c_void_p, c_int, c_ulonglong, c_void_p, c_void_p ]
  1599. self.xed_tables_init()
  1600. def Instruction(self):
  1601. return XEDInstruction(self)
  1602. def SetMode(self, inst, mode):
  1603. if mode:
  1604. inst.state.mode = 4 # 32-bit
  1605. inst.state.width = 4 # 4 bytes
  1606. else:
  1607. inst.state.mode = 1 # 64-bit
  1608. inst.state.width = 8 # 8 bytes
  1609. self.xed_operand_values_set_mode(inst.xedp, inst.statep)
  1610. def DisassembleOne(self, inst, bytes_ptr, bytes_cnt, ip):
  1611. self.xed_decoded_inst_zero_keep_mode(inst.xedp)
  1612. err = self.xed_decode(inst.xedp, bytes_ptr, bytes_cnt)
  1613. if err:
  1614. return 0, ""
  1615. # Use AT&T mode (2), alternative is Intel (3)
  1616. ok = self.xed_format_context(2, inst.xedp, inst.bufferp, sizeof(inst.buffer), ip, 0, 0)
  1617. if not ok:
  1618. return 0, ""
  1619. # Return instruction length and the disassembled instruction text
  1620. # For now, assume the length is in byte 166
  1621. return inst.xedd[166], inst.buffer.value
  1622. def TryOpen(file_name):
  1623. try:
  1624. return open(file_name, "rb")
  1625. except:
  1626. return None
  1627. def Is64Bit(f):
  1628. result = sizeof(c_void_p)
  1629. # ELF support only
  1630. pos = f.tell()
  1631. f.seek(0)
  1632. header = f.read(7)
  1633. f.seek(pos)
  1634. magic = header[0:4]
  1635. eclass = ord(header[4])
  1636. encoding = ord(header[5])
  1637. version = ord(header[6])
  1638. if magic == chr(127) + "ELF" and eclass > 0 and eclass < 3 and encoding > 0 and encoding < 3 and version == 1:
  1639. result = True if eclass == 2 else False
  1640. return result
  1641. # Global data
  1642. class Glb():
  1643. def __init__(self, dbref, db, dbname):
  1644. self.dbref = dbref
  1645. self.db = db
  1646. self.dbname = dbname
  1647. self.home_dir = os.path.expanduser("~")
  1648. self.buildid_dir = os.getenv("PERF_BUILDID_DIR")
  1649. if self.buildid_dir:
  1650. self.buildid_dir += "/.build-id/"
  1651. else:
  1652. self.buildid_dir = self.home_dir + "/.debug/.build-id/"
  1653. self.app = None
  1654. self.mainwindow = None
  1655. self.instances_to_shutdown_on_exit = weakref.WeakSet()
  1656. try:
  1657. self.disassembler = LibXED()
  1658. self.have_disassembler = True
  1659. except:
  1660. self.have_disassembler = False
  1661. def FileFromBuildId(self, build_id):
  1662. file_name = self.buildid_dir + build_id[0:2] + "/" + build_id[2:] + "/elf"
  1663. return TryOpen(file_name)
  1664. def FileFromNamesAndBuildId(self, short_name, long_name, build_id):
  1665. # Assume current machine i.e. no support for virtualization
  1666. if short_name[0:7] == "[kernel" and os.path.basename(long_name) == "kcore":
  1667. file_name = os.getenv("PERF_KCORE")
  1668. f = TryOpen(file_name) if file_name else None
  1669. if f:
  1670. return f
  1671. # For now, no special handling if long_name is /proc/kcore
  1672. f = TryOpen(long_name)
  1673. if f:
  1674. return f
  1675. f = self.FileFromBuildId(build_id)
  1676. if f:
  1677. return f
  1678. return None
  1679. def AddInstanceToShutdownOnExit(self, instance):
  1680. self.instances_to_shutdown_on_exit.add(instance)
  1681. # Shutdown any background processes or threads
  1682. def ShutdownInstances(self):
  1683. for x in self.instances_to_shutdown_on_exit:
  1684. try:
  1685. x.Shutdown()
  1686. except:
  1687. pass
  1688. # Database reference
  1689. class DBRef():
  1690. def __init__(self, is_sqlite3, dbname):
  1691. self.is_sqlite3 = is_sqlite3
  1692. self.dbname = dbname
  1693. def Open(self, connection_name):
  1694. dbname = self.dbname
  1695. if self.is_sqlite3:
  1696. db = QSqlDatabase.addDatabase("QSQLITE", connection_name)
  1697. else:
  1698. db = QSqlDatabase.addDatabase("QPSQL", connection_name)
  1699. opts = dbname.split()
  1700. for opt in opts:
  1701. if "=" in opt:
  1702. opt = opt.split("=")
  1703. if opt[0] == "hostname":
  1704. db.setHostName(opt[1])
  1705. elif opt[0] == "port":
  1706. db.setPort(int(opt[1]))
  1707. elif opt[0] == "username":
  1708. db.setUserName(opt[1])
  1709. elif opt[0] == "password":
  1710. db.setPassword(opt[1])
  1711. elif opt[0] == "dbname":
  1712. dbname = opt[1]
  1713. else:
  1714. dbname = opt
  1715. db.setDatabaseName(dbname)
  1716. if not db.open():
  1717. raise Exception("Failed to open database " + dbname + " error: " + db.lastError().text())
  1718. return db, dbname
  1719. # Main
  1720. def Main():
  1721. if (len(sys.argv) < 2):
  1722. print >> sys.stderr, "Usage is: exported-sql-viewer.py <database name>"
  1723. raise Exception("Too few arguments")
  1724. dbname = sys.argv[1]
  1725. is_sqlite3 = False
  1726. try:
  1727. f = open(dbname)
  1728. if f.read(15) == "SQLite format 3":
  1729. is_sqlite3 = True
  1730. f.close()
  1731. except:
  1732. pass
  1733. dbref = DBRef(is_sqlite3, dbname)
  1734. db, dbname = dbref.Open("main")
  1735. glb = Glb(dbref, db, dbname)
  1736. app = QApplication(sys.argv)
  1737. glb.app = app
  1738. mainwindow = MainWindow(glb)
  1739. glb.mainwindow = mainwindow
  1740. mainwindow.show()
  1741. err = app.exec_()
  1742. glb.ShutdownInstances()
  1743. db.close()
  1744. sys.exit(err)
  1745. if __name__ == "__main__":
  1746. Main()