Debian Codegraph @

js/src/gdb/mozilla/IonGraph.py

raw
1 # This Source Code Form is subject to the terms of the Mozilla Public
2 # License, v. 2.0. If a copy of the MPL was not distributed with this file,
3 # You can obtain one at http://mozilla.org/MPL/2.0/.
4
5 """
6 Debugging JIT Compilations can be obscure without large context. This python
7 script provide commands to let GDB open an image viewer to display the graph of
8 any compilation, as they are executed within GDB.
9
10 This python script should be sourced within GDB after loading the python scripts
11 provided with SpiderMonkey.
12 """
13
14 import os
15 import subprocess
16 import tempfile
17 import time
18
19 import gdb
20
21 import mozilla.prettyprinters
22 from mozilla.prettyprinters import pretty_printer
23
24 # Forget any printers from previous loads of this module.
25 mozilla.prettyprinters.clear_module_printers(__name__)
26
27 # Cache information about the JSString type for this objfile.
28
29
30 class jsvmPrinterCache:
31 def __init__(self):
32 self.d = None
33
34 def __getattr__(self, name):
35 if self.d is None:
36 self.initialize()
37 return self.d[name]
38
39 def initialize(self):
40 self.d = {}
41 self.d["char"] = gdb.lookup_type("char")
42
43
44 # Dummy class used to store the content of the type cache in the context of the
45 # iongraph command, which uses the jsvmLSprinter.
46
47
48 class ModuleCache:
49 def __init__(self):
50 self.mod_IonGraph = None
51
52
53 @pretty_printer("js::vm::LSprinter")
54 class jsvmLSprinter:
55 def __init__(self, value, cache):
56 self.value = value
57 if not cache.mod_IonGraph:
58 cache.mod_IonGraph = jsvmPrinterCache()
59 self.cache = cache.mod_IonGraph
60
61 def to_string(self):
62 next = self.value["head_"]
63 tail = self.value["tail_"]
64 if next == 0:
65 return ""
66 res = ""
67 while next != tail:
68 chars = (next + 1).cast(self.cache.char.pointer())
69 res = res + chars.string("ascii", "ignore", next["length"])
70 next = next["next"]
71 length = next["length"] - self.value["unused_"]
72 chars = (next + 1).cast(self.cache.char.pointer())
73 res = res + chars.string("ascii", "ignore", length)
74 return res
75
76
77 def search_in_path(bin):
78 paths = os.getenv("PATH", "")
79 if paths == "":
80 return ""
81 for d in paths.split(":"):
82 f = os.path.join(d, bin)
83 if os.access(f, os.X_OK):
84 return f
85 return ""
86
87
88 class IonGraphBinParameter(gdb.Parameter):
89 set_doc = "Set the path to iongraph binary, used by iongraph command."
90 show_doc = "Show the path to iongraph binary, used by iongraph command."
91
92 def get_set_string(self):
93 return "Path to iongraph binary changed to: %s" % self.value
94
95 def get_show_string(self, value):
96 return "Path to iongraph binary set to: %s" % value
97
98 def __init__(self):
99 super(IonGraphBinParameter, self).__init__(
100 "iongraph-bin", gdb.COMMAND_SUPPORT, gdb.PARAM_FILENAME
101 )
102 self.value = os.getenv("GDB_IONGRAPH", "")
103 if self.value == "":
104 self.value = search_in_path("iongraph")
105
106
107 class DotBinParameter(gdb.Parameter):
108 set_doc = "Set the path to dot binary, used by iongraph command."
109 show_doc = "Show the path to dot binary, used by iongraph command."
110
111 def get_set_string(self):
112 return "Path to dot binary changed to: %s" % self.value
113
114 def get_show_string(self, value):
115 return "Path to dot binary set to: %s" % value
116
117 def __init__(self):
118 super(DotBinParameter, self).__init__(
119 "dot-bin", gdb.COMMAND_SUPPORT, gdb.PARAM_FILENAME
120 )
121 self.value = os.getenv("GDB_DOT", "")
122 if self.value == "":
123 self.value = search_in_path("dot")
124
125
126 class PngViewerBinParameter(gdb.Parameter):
127 set_doc = "Set the path to a png viewer binary, used by iongraph command."
128 show_doc = "Show the path to a png viewer binary, used by iongraph command."
129
130 def get_set_string(self):
131 return "Path to a png viewer binary changed to: %s" % self.value
132
133 def get_show_string(self):
134 return "Path to a png viewer binary set to: %s" % self.value
135
136 def __init__(self):
137 super(PngViewerBinParameter, self).__init__(
138 "pngviewer-bin", gdb.COMMAND_SUPPORT, gdb.PARAM_FILENAME
139 )
140 self.value = os.getenv("GDB_PNGVIEWER", "")
141 if self.value == "":
142 self.value = search_in_path("xdg-open")
143
144
145 iongraph = IonGraphBinParameter()
146 dot = DotBinParameter()
147 pngviewer = PngViewerBinParameter()
148
149
150 class IonGraphCommand(gdb.Command):
151 """Command used to display the current state of the MIR graph in a png
152 viewer by providing an expression to access the MIRGenerator.
153 """
154
155 def __init__(self):
156 super(IonGraphCommand, self).__init__(
157 "iongraph", gdb.COMMAND_DATA, gdb.COMPLETE_EXPRESSION
158 )
159 self.typeCache = ModuleCache()
160
161 def invoke(self, mirGenExpr, from_tty):
162 """Call function from the graph spewer to populate the json printer with
163 the content generated by the jsonSpewer. Then we read the json content
164 from the jsonPrinter internal data, and gives that as input of iongraph
165 command."""
166
167 # From the MIRGenerator, find the graph spewer which contains both the
168 # jsonPrinter (containing the result of the output), and the jsonSpewer
169 # (continaining methods for spewing the graph).
170 mirGen = gdb.parse_and_eval(mirGenExpr)
171 jsonPrinter = mirGen["gs_"]["jsonPrinter_"]
172 jsonSpewer = mirGen["gs_"]["jsonSpewer_"]
173 graph = mirGen["graph_"]
174
175 # These commands are doing side-effects which are saving the state of
176 # the compiled code on the LSprinter dedicated for logging. Fortunately,
177 # if you are using these gdb command, this probably means that other
178 # ways of getting this content failed you already, so making a mess in
179 # these logging strings should not cause much issues.
180 gdb.parse_and_eval(
181 "(*(%s*)(%s)).clear()"
182 % (
183 jsonPrinter.type,
184 jsonPrinter.address,
185 )
186 )
187 gdb.parse_and_eval(
188 "(*(%s*)(%s)).beginFunction((JSScript*)0)"
189 % (
190 jsonSpewer.type,
191 jsonSpewer.address,
192 )
193 )
194 gdb.parse_and_eval(
195 '(*(%s*)(%s)).beginPass("gdb")'
196 % (
197 jsonSpewer.type,
198 jsonSpewer.address,
199 )
200 )
201 gdb.parse_and_eval(
202 "(*(%s*)(%s)).spewMIR((%s)%s)"
203 % (
204 jsonSpewer.type,
205 jsonSpewer.address,
206 graph.type,
207 graph,
208 )
209 )
210 gdb.parse_and_eval(
211 "(*(%s*)(%s)).spewLIR((%s)%s)"
212 % (
213 jsonSpewer.type,
214 jsonSpewer.address,
215 graph.type,
216 graph,
217 )
218 )
219 gdb.parse_and_eval(
220 "(*(%s*)(%s)).endPass()"
221 % (
222 jsonSpewer.type,
223 jsonSpewer.address,
224 )
225 )
226 gdb.parse_and_eval(
227 "(*(%s*)(%s)).endFunction()"
228 % (
229 jsonSpewer.type,
230 jsonSpewer.address,
231 )
232 )
233
234 # Dump the content of the LSprinter containing the JSON view of the
235 # graph into a python string.
236 json = jsvmLSprinter(jsonPrinter, self.typeCache).to_string()
237
238 # We are in the middle of the program execution and are messing up with
239 # the state of the logging data. As this might not be the first time we
240 # call beginFunction, we might have an extra comma at the beginning of
241 # the output, just strip it.
242 if json[0] == ",":
243 json = json[1:]
244
245 # Usually this is added by the IonSpewer.
246 json = '{ "functions": [%s] }' % json
247
248 # Display the content of the json with iongraph and other tools.
249 self.displayMIRGraph(json)
250
251 def displayMIRGraph(self, jsonStr):
252 png = tempfile.NamedTemporaryFile()
253
254 # start all processes in a shell-like equivalent of:
255 # iongraph < json | dot > tmp.png; xdg-open tmp.png
256 i = subprocess.Popen(
257 [iongraph.value, "--funcnum", "0", "--passnum", "0", "--out-mir", "-", "-"],
258 stdin=subprocess.PIPE,
259 stdout=subprocess.PIPE,
260 )
261 d = subprocess.Popen([dot.value, "-Tpng"], stdin=i.stdout, stdout=png)
262
263 # Write the json file as the input of the iongraph command.
264 i.stdin.write(jsonStr.encode("utf8"))
265 i.stdin.close()
266 i.stdout.close()
267
268 # Wait for iongraph and dot, such that the png file contains all the
269 # bits needed to by the png viewer.
270 i.wait()
271 d.communicate()[0]
272
273 # Spawn & detach the png viewer, to which we give the name of the
274 # temporary file. Note, as we do not want to wait on the image viewer,
275 # there is a minor race between the removal of the temporary file, which
276 # would happen at the next garbage collection cycle, and the start of
277 # the png viewer. We could use a pipe, but unfortunately, this does not
278 # seems to be supported by xdg-open.
279 subprocess.Popen([pngviewer.value, png.name], stdin=None, stdout=None)
280 time.sleep(1)
281
282
283 iongraph_cmd = IonGraphCommand()