1#!/usr/bin/env python
2#
3#===- exploded-graph-rewriter.py - ExplodedGraph dump tool -----*- python -*--#
4#
5# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
6# See https://llvm.org/LICENSE.txt for license information.
7# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
8#
9#===-----------------------------------------------------------------------===#
10
11
12from __future__ import print_function
13
14import argparse
15import collections
16import difflib
17import json
18import logging
19import os
20import re
21import sys
22
23
24#===-----------------------------------------------------------------------===#
25# These data structures represent a deserialized ExplodedGraph.
26#===-----------------------------------------------------------------------===#
27
28
29# A helper function for finding the difference between two dictionaries.
30def diff_dicts(curr, prev):
31    removed = [k for k in prev if k not in curr or curr[k] != prev[k]]
32    added = [k for k in curr if k not in prev or curr[k] != prev[k]]
33    return (removed, added)
34
35
36# Represents any program state trait that is a dictionary of key-value pairs.
37class GenericMap:
38    def __init__(self, items):
39        self.generic_map = collections.OrderedDict(items)
40
41    def diff(self, prev):
42        return diff_dicts(self.generic_map, prev.generic_map)
43
44    def is_different(self, prev):
45        removed, added = self.diff(prev)
46        return len(removed) != 0 or len(added) != 0
47
48
49# A deserialized source location.
50class SourceLocation:
51    def __init__(self, json_loc):
52        logging.debug('json: %s' % json_loc)
53        self.line = json_loc['line']
54        self.col = json_loc['column']
55        self.filename = os.path.basename(json_loc['file']) \
56            if 'file' in json_loc else '(main file)'
57        self.spelling = SourceLocation(json_loc['spelling']) \
58            if 'spelling' in json_loc else None
59
60    def is_macro(self):
61        return self.spelling is not None
62
63
64# A deserialized program point.
65class ProgramPoint:
66    def __init__(self, json_pp):
67        self.kind = json_pp['kind']
68        self.tag = json_pp['tag']
69        self.node_id = json_pp['node_id']
70        self.is_sink = bool(json_pp['is_sink'])
71        self.has_report = bool(json_pp['has_report'])
72        if self.kind == 'Edge':
73            self.src_id = json_pp['src_id']
74            self.dst_id = json_pp['dst_id']
75        elif self.kind == 'Statement':
76            logging.debug(json_pp)
77            self.stmt_kind = json_pp['stmt_kind']
78            self.cast_kind = json_pp['cast_kind'] \
79                if 'cast_kind' in json_pp else None
80            self.stmt_point_kind = json_pp['stmt_point_kind']
81            self.stmt_id = json_pp['stmt_id']
82            self.pointer = json_pp['pointer']
83            self.pretty = json_pp['pretty']
84            self.loc = SourceLocation(json_pp['location']) \
85                if json_pp['location'] is not None else None
86        elif self.kind == 'BlockEntrance':
87            self.block_id = json_pp['block_id']
88
89
90# A single expression acting as a key in a deserialized Environment.
91class EnvironmentBindingKey:
92    def __init__(self, json_ek):
93        # CXXCtorInitializer is not a Stmt!
94        self.stmt_id = json_ek['stmt_id'] if 'stmt_id' in json_ek \
95            else json_ek['init_id']
96        self.pretty = json_ek['pretty']
97        self.kind = json_ek['kind'] if 'kind' in json_ek else None
98
99    def _key(self):
100        return self.stmt_id
101
102    def __eq__(self, other):
103        return self._key() == other._key()
104
105    def __hash__(self):
106        return hash(self._key())
107
108
109# Deserialized description of a location context.
110class LocationContext:
111    def __init__(self, json_frame):
112        self.lctx_id = json_frame['lctx_id']
113        self.caption = json_frame['location_context']
114        self.decl = json_frame['calling']
115        self.loc = SourceLocation(json_frame['location']) \
116            if json_frame['location'] is not None else None
117
118    def _key(self):
119        return self.lctx_id
120
121    def __eq__(self, other):
122        return self._key() == other._key()
123
124    def __hash__(self):
125        return hash(self._key())
126
127
128# A group of deserialized Environment bindings that correspond to a specific
129# location context.
130class EnvironmentFrame:
131    def __init__(self, json_frame):
132        self.location_context = LocationContext(json_frame)
133        self.bindings = collections.OrderedDict(
134            [(EnvironmentBindingKey(b),
135              b['value']) for b in json_frame['items']]
136            if json_frame['items'] is not None else [])
137
138    def diff_bindings(self, prev):
139        return diff_dicts(self.bindings, prev.bindings)
140
141    def is_different(self, prev):
142        removed, added = self.diff_bindings(prev)
143        return len(removed) != 0 or len(added) != 0
144
145
146# A deserialized Environment. This class can also hold other entities that
147# are similar to Environment, such as Objects Under Construction or
148# Indices Of Elements Under Construction.
149class GenericEnvironment:
150    def __init__(self, json_e):
151        self.frames = [EnvironmentFrame(f) for f in json_e]
152
153    def diff_frames(self, prev):
154        # TODO: It's difficult to display a good diff when frame numbers shift.
155        if len(self.frames) != len(prev.frames):
156            return None
157
158        updated = []
159        for i in range(len(self.frames)):
160            f = self.frames[i]
161            prev_f = prev.frames[i]
162            if f.location_context == prev_f.location_context:
163                if f.is_different(prev_f):
164                    updated.append(i)
165            else:
166                # We have the whole frame replaced with another frame.
167                # TODO: Produce a nice diff.
168                return None
169
170        # TODO: Add support for added/removed.
171        return updated
172
173    def is_different(self, prev):
174        updated = self.diff_frames(prev)
175        return updated is None or len(updated) > 0
176
177
178# A single binding key in a deserialized RegionStore cluster.
179class StoreBindingKey:
180    def __init__(self, json_sk):
181        self.kind = json_sk['kind']
182        self.offset = json_sk['offset']
183
184    def _key(self):
185        return (self.kind, self.offset)
186
187    def __eq__(self, other):
188        return self._key() == other._key()
189
190    def __hash__(self):
191        return hash(self._key())
192
193
194# A single cluster of the deserialized RegionStore.
195class StoreCluster:
196    def __init__(self, json_sc):
197        self.base_region = json_sc['cluster']
198        self.bindings = collections.OrderedDict(
199            [(StoreBindingKey(b), b['value']) for b in json_sc['items']])
200
201    def diff_bindings(self, prev):
202        return diff_dicts(self.bindings, prev.bindings)
203
204    def is_different(self, prev):
205        removed, added = self.diff_bindings(prev)
206        return len(removed) != 0 or len(added) != 0
207
208
209# A deserialized RegionStore.
210class Store:
211    def __init__(self, json_s):
212        self.ptr = json_s['pointer']
213        self.clusters = collections.OrderedDict(
214            [(c['pointer'], StoreCluster(c)) for c in json_s['items']])
215
216    def diff_clusters(self, prev):
217        removed = [k for k in prev.clusters if k not in self.clusters]
218        added = [k for k in self.clusters if k not in prev.clusters]
219        updated = [k for k in prev.clusters if k in self.clusters
220                   and prev.clusters[k].is_different(self.clusters[k])]
221        return (removed, added, updated)
222
223    def is_different(self, prev):
224        removed, added, updated = self.diff_clusters(prev)
225        return len(removed) != 0 or len(added) != 0 or len(updated) != 0
226
227
228# Deserialized messages from a single checker in a single program state.
229# Basically a list of raw strings.
230class CheckerLines:
231    def __init__(self, json_lines):
232        self.lines = json_lines
233
234    def diff_lines(self, prev):
235        lines = difflib.ndiff(prev.lines, self.lines)
236        return [l.strip() for l in lines
237                if l.startswith('+') or l.startswith('-')]
238
239    def is_different(self, prev):
240        return len(self.diff_lines(prev)) > 0
241
242
243# Deserialized messages of all checkers, separated by checker.
244class CheckerMessages:
245    def __init__(self, json_m):
246        self.items = collections.OrderedDict(
247            [(m['checker'], CheckerLines(m['messages'])) for m in json_m])
248
249    def diff_messages(self, prev):
250        removed = [k for k in prev.items if k not in self.items]
251        added = [k for k in self.items if k not in prev.items]
252        updated = [k for k in prev.items if k in self.items
253                   and prev.items[k].is_different(self.items[k])]
254        return (removed, added, updated)
255
256    def is_different(self, prev):
257        removed, added, updated = self.diff_messages(prev)
258        return len(removed) != 0 or len(added) != 0 or len(updated) != 0
259
260
261# A deserialized program state.
262class ProgramState:
263    def __init__(self, state_id, json_ps):
264        logging.debug('Adding ProgramState ' + str(state_id))
265
266        if json_ps is None:
267            json_ps = {
268                'store': None,
269                'environment': None,
270                'constraints': None,
271                'dynamic_types': None,
272                'constructing_objects': None,
273                'index_of_element': None,
274                'checker_messages': None
275            }
276
277        self.state_id = state_id
278
279        self.store = Store(json_ps['store']) \
280            if json_ps['store'] is not None else None
281
282        self.environment = \
283            GenericEnvironment(json_ps['environment']['items']) \
284            if json_ps['environment'] is not None else None
285
286        self.constraints = GenericMap([
287            (c['symbol'], c['range']) for c in json_ps['constraints']
288        ]) if json_ps['constraints'] is not None else None
289
290        self.dynamic_types = GenericMap([
291                (t['region'], '%s%s' % (t['dyn_type'],
292                                        ' (or a sub-class)'
293                                        if t['sub_classable'] else ''))
294                for t in json_ps['dynamic_types']]) \
295            if json_ps['dynamic_types'] is not None else None
296
297        self.constructing_objects = \
298            GenericEnvironment(json_ps['constructing_objects']) \
299            if json_ps['constructing_objects'] is not None else None
300
301        self.index_of_element = \
302            GenericEnvironment(json_ps['index_of_element']) \
303            if json_ps['index_of_element'] is not None else None
304
305        self.checker_messages = CheckerMessages(json_ps['checker_messages']) \
306            if json_ps['checker_messages'] is not None else None
307
308
309# A deserialized exploded graph node. Has a default constructor because it
310# may be referenced as part of an edge before its contents are deserialized,
311# and in this moment we already need a room for predecessors and successors.
312class ExplodedNode:
313    def __init__(self):
314        self.predecessors = []
315        self.successors = []
316
317    def construct(self, node_id, json_node):
318        logging.debug('Adding ' + node_id)
319        self.ptr = node_id[4:]
320        self.points = [ProgramPoint(p) for p in json_node['program_points']]
321        self.node_id = self.points[-1].node_id
322        self.state = ProgramState(json_node['state_id'],
323                                  json_node['program_state']
324            if json_node['program_state'] is not None else None);
325
326        assert self.node_name() == node_id
327
328    def node_name(self):
329        return 'Node' + self.ptr
330
331
332# A deserialized ExplodedGraph. Constructed by consuming a .dot file
333# line-by-line.
334class ExplodedGraph:
335    # Parse .dot files with regular expressions.
336    node_re = re.compile(
337        '^(Node0x[0-9a-f]*) \\[shape=record,.*label="{(.*)\\\\l}"\\];$')
338    edge_re = re.compile(
339        '^(Node0x[0-9a-f]*) -> (Node0x[0-9a-f]*);$')
340
341    def __init__(self):
342        self.nodes = collections.defaultdict(ExplodedNode)
343        self.root_id = None
344        self.incomplete_line = ''
345
346    def add_raw_line(self, raw_line):
347        if raw_line.startswith('//'):
348            return
349
350        # Allow line breaks by waiting for ';'. This is not valid in
351        # a .dot file, but it is useful for writing tests.
352        if len(raw_line) > 0 and raw_line[-1] != ';':
353            self.incomplete_line += raw_line
354            return
355        raw_line = self.incomplete_line + raw_line
356        self.incomplete_line = ''
357
358        # Apply regexps one by one to see if it's a node or an edge
359        # and extract contents if necessary.
360        logging.debug('Line: ' + raw_line)
361        result = self.edge_re.match(raw_line)
362        if result is not None:
363            logging.debug('Classified as edge line.')
364            pred = result.group(1)
365            succ = result.group(2)
366            self.nodes[pred].successors.append(succ)
367            self.nodes[succ].predecessors.append(pred)
368            return
369        result = self.node_re.match(raw_line)
370        if result is not None:
371            logging.debug('Classified as node line.')
372            node_id = result.group(1)
373            if len(self.nodes) == 0:
374                self.root_id = node_id
375            # Note: when writing tests you don't need to escape everything,
376            # even though in a valid dot file everything is escaped.
377            node_label = result.group(2).replace(' ', '') \
378                                        .replace('\\"', '"') \
379                                        .replace('\\{', '{') \
380                                        .replace('\\}', '}') \
381                                        .replace('\\\\', '\\') \
382                                        .replace('\\|', '|') \
383                                        .replace('\\<', '\\\\<') \
384                                        .replace('\\>', '\\\\>') \
385                                        .rstrip(',')
386            # Handle `\l` separately because a string literal can be in code
387            # like "string\\literal" with the `\l` inside.
388            # Also on Windows macros __FILE__ produces specific delimiters `\`
389            # and a directory or file may starts with the letter `l`.
390            # Find all `\l` (like `,\l`, `}\l`, `[\l`) except `\\l`,
391            # because the literal as a rule containes multiple `\` before `\l`.
392            node_label = re.sub(r'(?<!\\)\\l', '', node_label)
393            logging.debug(node_label)
394            json_node = json.loads(node_label)
395            self.nodes[node_id].construct(node_id, json_node)
396            return
397        logging.debug('Skipping.')
398
399
400#===-----------------------------------------------------------------------===#
401# Visitors traverse a deserialized ExplodedGraph and do different things
402# with every node and edge.
403#===-----------------------------------------------------------------------===#
404
405
406# A visitor that dumps the ExplodedGraph into a DOT file with fancy HTML-based
407# syntax highlighing.
408class DotDumpVisitor:
409    def __init__(self, do_diffs, dark_mode, gray_mode,
410                 topo_mode, dump_dot_only):
411        self._do_diffs = do_diffs
412        self._dark_mode = dark_mode
413        self._gray_mode = gray_mode
414        self._topo_mode = topo_mode
415        self._dump_dot_only = dump_dot_only
416        self._output = []
417
418    def _dump_raw(self, s):
419        if self._dump_dot_only:
420            print(s, end='')
421        else:
422            self._output.append(s)
423
424    def output(self):
425        assert not self._dump_dot_only
426        if sys.version_info[0] > 2 and sys.version_info[1] >= 5:
427            return ''.join(self._output).encode()
428        else:
429            return ''.join(self._output)
430
431    def _dump(self, s):
432        s = s.replace('&', '&amp;') \
433             .replace('{', '\\{') \
434             .replace('}', '\\}') \
435             .replace('\\<', '&lt;') \
436             .replace('\\>', '&gt;') \
437             .replace('|', '\\|')
438        s = re.sub(r'(?<!\\)\\l', '<br />', s)
439        if self._gray_mode:
440            s = re.sub(r'<font color="[a-z0-9]*">', '', s)
441            s = re.sub(r'</font>', '', s)
442        self._dump_raw(s)
443
444    @staticmethod
445    def _diff_plus_minus(is_added):
446        if is_added is None:
447            return ''
448        if is_added:
449            return '<font color="forestgreen">+</font>'
450        return '<font color="red">-</font>'
451
452    @staticmethod
453    def _short_pretty(s):
454        if s is None:
455            return None
456        if len(s) < 20:
457            return s
458        left = s.find('{')
459        right = s.rfind('}')
460        if left == -1 or right == -1 or left >= right:
461            return s
462        candidate = s[0:left + 1] + ' ... ' + s[right:]
463        if len(candidate) >= len(s):
464            return s
465        return candidate
466
467    @staticmethod
468    def _make_sloc(loc):
469        if loc is None:
470            return '<i>Invalid Source Location</i>'
471
472        def make_plain_loc(loc):
473            return '%s:<b>%s</b>:<b>%s</b>' \
474                % (loc.filename, loc.line, loc.col)
475
476        if loc.is_macro():
477            return '%s <font color="royalblue1">' \
478                   '(<i>spelling at </i> %s)</font>' \
479                % (make_plain_loc(loc), make_plain_loc(loc.spelling))
480
481        return make_plain_loc(loc)
482
483    def visit_begin_graph(self, graph):
484        self._graph = graph
485        self._dump_raw('digraph "ExplodedGraph" {\n')
486        if self._dark_mode:
487            self._dump_raw('bgcolor="gray10";\n')
488        self._dump_raw('label="";\n')
489
490    def visit_program_point(self, p):
491        if p.kind in ['Edge', 'BlockEntrance', 'BlockExit']:
492            color = 'gold3'
493        elif p.kind in ['PreStmtPurgeDeadSymbols',
494                        'PostStmtPurgeDeadSymbols']:
495            color = 'red'
496        elif p.kind in ['CallEnter', 'CallExitBegin', 'CallExitEnd']:
497            color = 'dodgerblue' if self._dark_mode else 'blue'
498        elif p.kind in ['Statement']:
499            color = 'cyan4'
500        else:
501            color = 'forestgreen'
502
503        self._dump('<tr><td align="left">%s.</td>' % p.node_id)
504
505        if p.kind == 'Statement':
506            # This avoids pretty-printing huge statements such as CompoundStmt.
507            # Such statements show up only at [Pre|Post]StmtPurgeDeadSymbols
508            skip_pretty = 'PurgeDeadSymbols' in p.stmt_point_kind
509            stmt_color = 'cyan3'
510            self._dump('<td align="left" width="0">%s:</td>'
511                       '<td align="left" width="0"><font color="%s">'
512                       '%s</font> </td>'
513                       '<td align="left"><i>S%s</i></td>'
514                       '<td align="left"><font color="%s">%s</font></td>'
515                       '<td align="left">%s</td></tr>'
516                       % (self._make_sloc(p.loc), color,
517                          '%s (%s)' % (p.stmt_kind, p.cast_kind)
518                          if p.cast_kind is not None else p.stmt_kind,
519                          p.stmt_id, stmt_color, p.stmt_point_kind,
520                          self._short_pretty(p.pretty)
521                          if not skip_pretty else ''))
522        elif p.kind == 'Edge':
523            self._dump('<td width="0"></td>'
524                       '<td align="left" width="0">'
525                       '<font color="%s">%s</font></td><td align="left">'
526                       '[B%d] -\\> [B%d]</td></tr>'
527                       % (color, 'BlockEdge', p.src_id, p.dst_id))
528        elif p.kind == 'BlockEntrance':
529            self._dump('<td width="0"></td>'
530                       '<td align="left" width="0">'
531                       '<font color="%s">%s</font></td>'
532                       '<td align="left">[B%d]</td></tr>'
533                       % (color, p.kind, p.block_id))
534        else:
535            # TODO: Print more stuff for other kinds of points.
536            self._dump('<td width="0"></td>'
537                       '<td align="left" width="0" colspan="2">'
538                       '<font color="%s">%s</font></td></tr>'
539                       % (color, p.kind))
540
541        if p.tag is not None:
542            self._dump('<tr><td width="0"></td><td width="0"></td>'
543                       '<td colspan="3" align="left">'
544                       '<b>Tag: </b> <font color="crimson">'
545                       '%s</font></td></tr>' % p.tag)
546
547        if p.has_report:
548            self._dump('<tr><td width="0"></td><td width="0"></td>'
549                       '<td colspan="3" align="left">'
550                       '<font color="red"><b>Bug Report Attached'
551                       '</b></font></td></tr>')
552        if p.is_sink:
553            self._dump('<tr><td width="0"></td><td width="0"></td>'
554                       '<td colspan="3" align="left">'
555                       '<font color="cornflowerblue"><b>Sink Node'
556                       '</b></font></td></tr>')
557
558    def visit_environment(self, e, prev_e=None):
559        self._dump('<table border="0">')
560
561        def dump_location_context(lc, is_added=None):
562            self._dump('<tr><td>%s</td>'
563                       '<td align="left"><b>%s</b></td>'
564                       '<td align="left" colspan="2">'
565                       '<font color="gray60">%s </font>'
566                       '%s</td></tr>'
567                       % (self._diff_plus_minus(is_added),
568                          lc.caption, lc.decl,
569                          ('(%s)' % self._make_sloc(lc.loc))
570                          if lc.loc is not None else ''))
571
572        def dump_binding(f, b, is_added=None):
573            self._dump('<tr><td>%s</td>'
574                       '<td align="left"><i>S%s</i></td>'
575                       '%s'
576                       '<td align="left">%s</td>'
577                       '<td align="left">%s</td></tr>'
578                       % (self._diff_plus_minus(is_added),
579                          b.stmt_id,
580                          '<td align="left"><font color="%s"><i>'
581                          '%s</i></font></td>' % (
582                              'lavender' if self._dark_mode else 'darkgreen',
583                              ('(%s)' % b.kind) if b.kind is not None else ' '
584                          ),
585                          self._short_pretty(b.pretty), f.bindings[b]))
586
587        frames_updated = e.diff_frames(prev_e) if prev_e is not None else None
588        if frames_updated:
589            for i in frames_updated:
590                f = e.frames[i]
591                prev_f = prev_e.frames[i]
592                dump_location_context(f.location_context)
593                bindings_removed, bindings_added = f.diff_bindings(prev_f)
594                for b in bindings_removed:
595                    dump_binding(prev_f, b, False)
596                for b in bindings_added:
597                    dump_binding(f, b, True)
598        else:
599            for f in e.frames:
600                dump_location_context(f.location_context)
601                for b in f.bindings:
602                    dump_binding(f, b)
603
604        self._dump('</table>')
605
606    def visit_environment_in_state(self, selector, title, s, prev_s=None):
607        e = getattr(s, selector)
608        prev_e = getattr(prev_s, selector) if prev_s is not None else None
609        if e is None and prev_e is None:
610            return
611
612        self._dump('<hr /><tr><td align="left"><b>%s: </b>' % title)
613        if e is None:
614            self._dump('<i> Nothing!</i>')
615        else:
616            if prev_e is not None:
617                if e.is_different(prev_e):
618                    self._dump('</td></tr><tr><td align="left">')
619                    self.visit_environment(e, prev_e)
620                else:
621                    self._dump('<i> No changes!</i>')
622            else:
623                self._dump('</td></tr><tr><td align="left">')
624                self.visit_environment(e)
625
626        self._dump('</td></tr>')
627
628    def visit_store(self, s, prev_s=None):
629        self._dump('<table border="0">')
630
631        def dump_binding(s, c, b, is_added=None):
632            self._dump('<tr><td>%s</td>'
633                       '<td align="left">%s</td>'
634                       '<td align="left">%s</td>'
635                       '<td align="left">%s</td>'
636                       '<td align="left">%s</td></tr>'
637                       % (self._diff_plus_minus(is_added),
638                          s.clusters[c].base_region, b.offset,
639                          '(<i>Default</i>)' if b.kind == 'Default'
640                          else '',
641                          s.clusters[c].bindings[b]))
642
643        if prev_s is not None:
644            clusters_removed, clusters_added, clusters_updated = \
645                s.diff_clusters(prev_s)
646            for c in clusters_removed:
647                for b in prev_s.clusters[c].bindings:
648                    dump_binding(prev_s, c, b, False)
649            for c in clusters_updated:
650                bindings_removed, bindings_added = \
651                    s.clusters[c].diff_bindings(prev_s.clusters[c])
652                for b in bindings_removed:
653                    dump_binding(prev_s, c, b, False)
654                for b in bindings_added:
655                    dump_binding(s, c, b, True)
656            for c in clusters_added:
657                for b in s.clusters[c].bindings:
658                    dump_binding(s, c, b, True)
659        else:
660            for c in s.clusters:
661                for b in s.clusters[c].bindings:
662                    dump_binding(s, c, b)
663
664        self._dump('</table>')
665
666    def visit_store_in_state(self, s, prev_s=None):
667        st = s.store
668        prev_st = prev_s.store if prev_s is not None else None
669        if st is None and prev_st is None:
670            return
671
672        self._dump('<hr /><tr><td align="left"><b>Store: </b>')
673        if st is None:
674            self._dump('<i> Nothing!</i>')
675        else:
676            if self._dark_mode:
677                self._dump(' <font color="gray30">(%s)</font>' % st.ptr)
678            else:
679                self._dump(' <font color="gray">(%s)</font>' % st.ptr)
680            if prev_st is not None:
681                if s.store.is_different(prev_st):
682                    self._dump('</td></tr><tr><td align="left">')
683                    self.visit_store(st, prev_st)
684                else:
685                    self._dump('<i> No changes!</i>')
686            else:
687                self._dump('</td></tr><tr><td align="left">')
688                self.visit_store(st)
689        self._dump('</td></tr>')
690
691    def visit_generic_map(self, m, prev_m=None):
692        self._dump('<table border="0">')
693
694        def dump_pair(m, k, is_added=None):
695            self._dump('<tr><td>%s</td>'
696                       '<td align="left">%s</td>'
697                       '<td align="left">%s</td></tr>'
698                       % (self._diff_plus_minus(is_added),
699                          k, m.generic_map[k]))
700
701        if prev_m is not None:
702            removed, added = m.diff(prev_m)
703            for k in removed:
704                dump_pair(prev_m, k, False)
705            for k in added:
706                dump_pair(m, k, True)
707        else:
708            for k in m.generic_map:
709                dump_pair(m, k, None)
710
711        self._dump('</table>')
712
713    def visit_generic_map_in_state(self, selector, title, s, prev_s=None):
714        m = getattr(s, selector)
715        prev_m = getattr(prev_s, selector) if prev_s is not None else None
716        if m is None and prev_m is None:
717            return
718
719        self._dump('<hr />')
720        self._dump('<tr><td align="left">'
721                   '<b>%s: </b>' % title)
722        if m is None:
723            self._dump('<i> Nothing!</i>')
724        else:
725            if prev_m is not None:
726                if m.is_different(prev_m):
727                    self._dump('</td></tr><tr><td align="left">')
728                    self.visit_generic_map(m, prev_m)
729                else:
730                    self._dump('<i> No changes!</i>')
731            else:
732                self._dump('</td></tr><tr><td align="left">')
733                self.visit_generic_map(m)
734
735        self._dump('</td></tr>')
736
737    def visit_checker_messages(self, m, prev_m=None):
738        self._dump('<table border="0">')
739
740        def dump_line(l, is_added=None):
741            self._dump('<tr><td>%s</td>'
742                       '<td align="left">%s</td></tr>'
743                       % (self._diff_plus_minus(is_added), l))
744
745        def dump_chk(chk, is_added=None):
746            dump_line('<i>%s</i>:' % chk, is_added)
747
748        if prev_m is not None:
749            removed, added, updated = m.diff_messages(prev_m)
750            for chk in removed:
751                dump_chk(chk, False)
752                for l in prev_m.items[chk].lines:
753                    dump_line(l, False)
754            for chk in updated:
755                dump_chk(chk)
756                for l in m.items[chk].diff_lines(prev_m.items[chk]):
757                    dump_line(l[1:], l.startswith('+'))
758            for chk in added:
759                dump_chk(chk, True)
760                for l in m.items[chk].lines:
761                    dump_line(l, True)
762        else:
763            for chk in m.items:
764                dump_chk(chk)
765                for l in m.items[chk].lines:
766                    dump_line(l)
767
768        self._dump('</table>')
769
770    def visit_checker_messages_in_state(self, s, prev_s=None):
771        m = s.checker_messages
772        prev_m = prev_s.checker_messages if prev_s is not None else None
773        if m is None and prev_m is None:
774            return
775
776        self._dump('<hr />')
777        self._dump('<tr><td align="left">'
778                   '<b>Checker State: </b>')
779        if m is None:
780            self._dump('<i> Nothing!</i>')
781        else:
782            if prev_m is not None:
783                if m.is_different(prev_m):
784                    self._dump('</td></tr><tr><td align="left">')
785                    self.visit_checker_messages(m, prev_m)
786                else:
787                    self._dump('<i> No changes!</i>')
788            else:
789                self._dump('</td></tr><tr><td align="left">')
790                self.visit_checker_messages(m)
791
792        self._dump('</td></tr>')
793
794    def visit_state(self, s, prev_s):
795        self.visit_store_in_state(s, prev_s)
796        self.visit_environment_in_state('environment', 'Expressions',
797                                        s, prev_s)
798        self.visit_generic_map_in_state('constraints', 'Ranges',
799                                        s, prev_s)
800        self.visit_generic_map_in_state('dynamic_types', 'Dynamic Types',
801                                        s, prev_s)
802        self.visit_environment_in_state('constructing_objects',
803                                        'Objects Under Construction',
804                                        s, prev_s)
805        self.visit_environment_in_state('index_of_element',
806                                        'Indices Of Elements Under Construction',
807                                        s, prev_s)
808        self.visit_checker_messages_in_state(s, prev_s)
809
810    def visit_node(self, node):
811        self._dump('%s [shape=record,'
812                   % (node.node_name()))
813        if self._dark_mode:
814            self._dump('color="white",fontcolor="gray80",')
815        self._dump('label=<<table border="0">')
816
817        self._dump('<tr><td bgcolor="%s"><b>State %s</b></td></tr>'
818                   % ("gray20" if self._dark_mode else "gray70",
819                      node.state.state_id
820                      if node.state is not None else 'Unspecified'))
821        if not self._topo_mode:
822            self._dump('<tr><td align="left" width="0">')
823            if len(node.points) > 1:
824                self._dump('<b>Program points:</b></td></tr>')
825            else:
826                self._dump('<b>Program point:</b></td></tr>')
827        self._dump('<tr><td align="left" width="0">'
828                   '<table border="0" align="left" width="0">')
829        for p in node.points:
830            self.visit_program_point(p)
831        self._dump('</table></td></tr>')
832
833        if node.state is not None and not self._topo_mode:
834            prev_s = None
835            # Do diffs only when we have a unique predecessor.
836            # Don't do diffs on the leaf nodes because they're
837            # the important ones.
838            if self._do_diffs and len(node.predecessors) == 1 \
839               and len(node.successors) > 0:
840                prev_s = self._graph.nodes[node.predecessors[0]].state
841            self.visit_state(node.state, prev_s)
842        self._dump_raw('</table>>];\n')
843
844    def visit_edge(self, pred, succ):
845        self._dump_raw('%s -> %s%s;\n' % (
846            pred.node_name(), succ.node_name(),
847            ' [color="white"]' if self._dark_mode else ''
848        ))
849
850    def visit_end_of_graph(self):
851        self._dump_raw('}\n')
852
853        if not self._dump_dot_only:
854            import sys
855            import tempfile
856
857            def write_temp_file(suffix, data):
858                fd, filename = tempfile.mkstemp(suffix=suffix)
859                print('Writing "%s"...' % filename)
860                with os.fdopen(fd, 'w') as fp:
861                    fp.write(data)
862                print('Done! Please remember to remove the file.')
863                return filename
864
865            try:
866                import graphviz
867            except ImportError:
868                # The fallback behavior if graphviz is not installed!
869                print('Python graphviz not found. Please invoke')
870                print('  $ pip install graphviz')
871                print('in order to enable automatic conversion to HTML.')
872                print()
873                print('You may also convert DOT to SVG manually via')
874                print('  $ dot -Tsvg input.dot -o output.svg')
875                print()
876                write_temp_file('.dot', self.output())
877                return
878
879            svg = graphviz.pipe('dot', 'svg', self.output())
880
881            filename = write_temp_file(
882                '.html', '<html><body bgcolor="%s">%s</body></html>' % (
883                             '#1a1a1a' if self._dark_mode else 'white', svg))
884            if sys.platform == 'win32':
885                os.startfile(filename)
886            elif sys.platform == 'darwin':
887                os.system('open "%s"' % filename)
888            else:
889                os.system('xdg-open "%s"' % filename)
890
891
892#===-----------------------------------------------------------------------===#
893# Explorers know how to traverse the ExplodedGraph in a certain order.
894# They would invoke a Visitor on every node or edge they encounter.
895#===-----------------------------------------------------------------------===#
896
897
898# BasicExplorer explores the whole graph in no particular order.
899class BasicExplorer:
900    def explore(self, graph, visitor):
901        visitor.visit_begin_graph(graph)
902        for node in sorted(graph.nodes):
903            logging.debug('Visiting ' + node)
904            visitor.visit_node(graph.nodes[node])
905            for succ in sorted(graph.nodes[node].successors):
906                logging.debug('Visiting edge: %s -> %s ' % (node, succ))
907                visitor.visit_edge(graph.nodes[node], graph.nodes[succ])
908        visitor.visit_end_of_graph()
909
910
911#===-----------------------------------------------------------------------===#
912# Trimmers cut out parts of the ExplodedGraph so that to focus on other parts.
913# Trimmers can be combined together by applying them sequentially.
914#===-----------------------------------------------------------------------===#
915
916
917# SinglePathTrimmer keeps only a single path - the leftmost path from the root.
918# Useful when the trimmed graph is still too large.
919class SinglePathTrimmer:
920    def trim(self, graph):
921        visited_nodes = set()
922        node_id = graph.root_id
923        while True:
924            visited_nodes.add(node_id)
925            node = graph.nodes[node_id]
926            if len(node.successors) > 0:
927                succ_id = node.successors[0]
928                succ = graph.nodes[succ_id]
929                node.successors = [succ_id]
930                succ.predecessors = [node_id]
931                if succ_id in visited_nodes:
932                    break
933                node_id = succ_id
934            else:
935                break
936        graph.nodes = {node_id: graph.nodes[node_id]
937                       for node_id in visited_nodes}
938
939
940# TargetedTrimmer keeps paths that lead to specific nodes and discards all
941# other paths. Useful when you cannot use -trim-egraph (e.g. when debugging
942# a crash).
943class TargetedTrimmer:
944    def __init__(self, target_nodes):
945        self._target_nodes = target_nodes
946
947    @staticmethod
948    def parse_target_node(node, graph):
949        if node.startswith('0x'):
950            ret = 'Node' + node
951            assert ret in graph.nodes
952            return ret
953        else:
954            for other_id in graph.nodes:
955                other = graph.nodes[other_id]
956                if other.node_id == int(node):
957                    return other_id
958
959    @staticmethod
960    def parse_target_nodes(target_nodes, graph):
961        return [TargetedTrimmer.parse_target_node(node, graph)
962                for node in target_nodes.split(',')]
963
964    def trim(self, graph):
965        queue = self._target_nodes
966        visited_nodes = set()
967
968        while len(queue) > 0:
969            node_id = queue.pop()
970            visited_nodes.add(node_id)
971            node = graph.nodes[node_id]
972            for pred_id in node.predecessors:
973                if pred_id not in visited_nodes:
974                    queue.append(pred_id)
975        graph.nodes = {node_id: graph.nodes[node_id]
976                       for node_id in visited_nodes}
977        for node_id in graph.nodes:
978            node = graph.nodes[node_id]
979            node.successors = [succ_id for succ_id in node.successors
980                               if succ_id in visited_nodes]
981            node.predecessors = [succ_id for succ_id in node.predecessors
982                                 if succ_id in visited_nodes]
983
984
985#===-----------------------------------------------------------------------===#
986# The entry point to the script.
987#===-----------------------------------------------------------------------===#
988
989
990def main():
991    parser = argparse.ArgumentParser(
992        description='Display and manipulate Exploded Graph dumps.')
993    parser.add_argument('filename', type=str,
994                        help='the .dot file produced by the Static Analyzer')
995    parser.add_argument('-v', '--verbose', action='store_const',
996                        dest='loglevel', const=logging.DEBUG,
997                        default=logging.WARNING,
998                        help='enable info prints')
999    parser.add_argument('-d', '--diff', action='store_const', dest='diff',
1000                        const=True, default=False,
1001                        help='display differences between states')
1002    parser.add_argument('-t', '--topology', action='store_const',
1003                        dest='topology', const=True, default=False,
1004                        help='only display program points, omit states')
1005    parser.add_argument('-s', '--single-path', action='store_const',
1006                        dest='single_path', const=True, default=False,
1007                        help='only display the leftmost path in the graph '
1008                             '(useful for trimmed graphs that still '
1009                             'branch too much)')
1010    parser.add_argument('--to', type=str, default=None,
1011                        help='only display execution paths from the root '
1012                             'to the given comma-separated list of nodes '
1013                             'identified by a pointer or a stable ID; '
1014                             'compatible with --single-path')
1015    parser.add_argument('--dark', action='store_const', dest='dark',
1016                        const=True, default=False,
1017                        help='dark mode')
1018    parser.add_argument('--gray', action='store_const', dest='gray',
1019                        const=True, default=False,
1020                        help='black-and-white mode')
1021    parser.add_argument('--dump-dot-only', action='store_const',
1022                        dest='dump_dot_only', const=True, default=False,
1023                        help='instead of writing an HTML file and immediately '
1024                             'displaying it, dump the rewritten dot file '
1025                             'to stdout')
1026    args = parser.parse_args()
1027    logging.basicConfig(level=args.loglevel)
1028
1029    graph = ExplodedGraph()
1030    with open(args.filename) as fd:
1031        for raw_line in fd:
1032            raw_line = raw_line.strip()
1033            graph.add_raw_line(raw_line)
1034
1035    trimmers = []
1036    if args.to is not None:
1037        trimmers.append(TargetedTrimmer(
1038            TargetedTrimmer.parse_target_nodes(args.to, graph)))
1039    if args.single_path:
1040        trimmers.append(SinglePathTrimmer())
1041
1042    explorer = BasicExplorer()
1043
1044    visitor = DotDumpVisitor(args.diff, args.dark, args.gray, args.topology,
1045                             args.dump_dot_only)
1046
1047    for trimmer in trimmers:
1048        trimmer.trim(graph)
1049
1050    explorer.explore(graph, visitor)
1051
1052
1053if __name__ == '__main__':
1054    main()
1055