xref: /llvm-project/clang/utils/analyzer/exploded-graph-rewriter.py (revision 14f4de9bb9dd04bbdf784082b78b25f0d41b186e)
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 json
17import logging
18import re
19
20
21# A helper function for finding the difference between two dictionaries.
22def diff_dicts(curr, prev):
23    removed = [k for k in prev if k not in curr or curr[k] != prev[k]]
24    added = [k for k in curr if k not in prev or curr[k] != prev[k]]
25    return (removed, added)
26
27
28# Represents any program state trait that is a dictionary of key-value pairs.
29class GenericMap(object):
30    def __init__(self, generic_map):
31        self.generic_map = generic_map
32
33    def diff(self, prev):
34        return diff_dicts(self.generic_map, prev.generic_map)
35
36    def is_different(self, prev):
37        removed, added = self.diff(prev)
38        return len(removed) != 0 or len(added) != 0
39
40
41# A deserialized source location.
42class SourceLocation(object):
43    def __init__(self, json_loc):
44        super(SourceLocation, self).__init__()
45        self.line = json_loc['line']
46        self.col = json_loc['column']
47        self.filename = json_loc['filename'] \
48            if 'filename' in json_loc else '(main file)'
49
50
51# A deserialized program point.
52class ProgramPoint(object):
53    def __init__(self, json_pp):
54        super(ProgramPoint, self).__init__()
55        self.kind = json_pp['kind']
56        self.tag = json_pp['tag']
57        if self.kind == 'Edge':
58            self.src_id = json_pp['src_id']
59            self.dst_id = json_pp['dst_id']
60        elif self.kind == 'Statement':
61            self.stmt_kind = json_pp['stmt_kind']
62            self.pointer = json_pp['pointer']
63            self.pretty = json_pp['pretty']
64            self.loc = SourceLocation(json_pp['location']) \
65                if json_pp['location'] is not None else None
66        elif self.kind == 'BlockEntrance':
67            self.block_id = json_pp['block_id']
68
69
70# A single expression acting as a key in a deserialized Environment.
71class EnvironmentBindingKey(object):
72    def __init__(self, json_ek):
73        super(EnvironmentBindingKey, self).__init__()
74        self.stmt_id = json_ek['stmt_id']
75        self.pretty = json_ek['pretty']
76
77    def _key(self):
78        return self.stmt_id
79
80    def __eq__(self, other):
81        return self._key() == other._key()
82
83    def __hash__(self):
84        return hash(self._key())
85
86
87# Deserialized description of a location context.
88class LocationContext(object):
89    def __init__(self, json_frame):
90        super(LocationContext, self).__init__()
91        self.lctx_id = json_frame['lctx_id']
92        self.caption = json_frame['location_context']
93        self.decl = json_frame['calling']
94        self.line = json_frame['call_line']
95
96    def _key(self):
97        return self.lctx_id
98
99    def __eq__(self, other):
100        return self._key() == other._key()
101
102    def __hash__(self):
103        return hash(self._key())
104
105
106# A group of deserialized Environment bindings that correspond to a specific
107# location context.
108class EnvironmentFrame(object):
109    def __init__(self, json_frame):
110        super(EnvironmentFrame, self).__init__()
111        self.location_context = LocationContext(json_frame)
112        self.bindings = collections.OrderedDict(
113            [(EnvironmentBindingKey(b),
114              b['value']) for b in json_frame['items']]
115            if json_frame['items'] is not None else [])
116
117    def diff_bindings(self, prev):
118        return diff_dicts(self.bindings, prev.bindings)
119
120    def is_different(self, prev):
121        removed, added = self.diff_bindings(prev)
122        return len(removed) != 0 or len(added) != 0
123
124
125# A deserialized Environment.
126class Environment(object):
127    def __init__(self, json_e):
128        super(Environment, self).__init__()
129        self.frames = [EnvironmentFrame(f) for f in json_e]
130
131    def diff_frames(self, prev):
132        # TODO: It's difficult to display a good diff when frame numbers shift.
133        if len(self.frames) != len(prev.frames):
134            return None
135
136        updated = []
137        for i in range(len(self.frames)):
138            f = self.frames[i]
139            prev_f = prev.frames[i]
140            if f.location_context == prev_f.location_context:
141                if f.is_different(prev_f):
142                    updated.append(i)
143            else:
144                # We have the whole frame replaced with another frame.
145                # TODO: Produce a nice diff.
146                return None
147
148        # TODO: Add support for added/removed.
149        return updated
150
151    def is_different(self, prev):
152        updated = self.diff_frames(prev)
153        return updated is None or len(updated) > 0
154
155
156# A single binding key in a deserialized RegionStore cluster.
157class StoreBindingKey(object):
158    def __init__(self, json_sk):
159        super(StoreBindingKey, self).__init__()
160        self.kind = json_sk['kind']
161        self.offset = json_sk['offset']
162
163    def _key(self):
164        return (self.kind, self.offset)
165
166    def __eq__(self, other):
167        return self._key() == other._key()
168
169    def __hash__(self):
170        return hash(self._key())
171
172
173# A single cluster of the deserialized RegionStore.
174class StoreCluster(object):
175    def __init__(self, json_sc):
176        super(StoreCluster, self).__init__()
177        self.base_region = json_sc['cluster']
178        self.bindings = collections.OrderedDict(
179            [(StoreBindingKey(b), b['value']) for b in json_sc['items']])
180
181    def diff_bindings(self, prev):
182        return diff_dicts(self.bindings, prev.bindings)
183
184    def is_different(self, prev):
185        removed, added = self.diff_bindings(prev)
186        return len(removed) != 0 or len(added) != 0
187
188
189# A deserialized RegionStore.
190class Store(object):
191    def __init__(self, json_s):
192        super(Store, self).__init__()
193        self.clusters = collections.OrderedDict(
194            [(c['pointer'], StoreCluster(c)) for c in json_s])
195
196    def diff_clusters(self, prev):
197        removed = [k for k in prev.clusters if k not in self.clusters]
198        added = [k for k in self.clusters if k not in prev.clusters]
199        updated = [k for k in prev.clusters if k in self.clusters
200                   and prev.clusters[k].is_different(self.clusters[k])]
201        return (removed, added, updated)
202
203    def is_different(self, prev):
204        removed, added, updated = self.diff_clusters(prev)
205        return len(removed) != 0 or len(added) != 0 or len(updated) != 0
206
207
208# A deserialized program state.
209class ProgramState(object):
210    def __init__(self, state_id, json_ps):
211        super(ProgramState, self).__init__()
212        logging.debug('Adding ProgramState ' + str(state_id))
213
214        self.state_id = state_id
215        self.store = Store(json_ps['store']) \
216            if json_ps['store'] is not None else None
217        self.environment = Environment(json_ps['environment']) \
218            if json_ps['environment'] is not None else None
219        self.constraints = GenericMap(collections.OrderedDict([
220            (c['symbol'], c['range']) for c in json_ps['constraints']
221        ])) if json_ps['constraints'] is not None else None
222        # TODO: Objects under construction.
223        # TODO: Dynamic types of objects.
224        # TODO: Checker messages.
225
226
227# A deserialized exploded graph node. Has a default constructor because it
228# may be referenced as part of an edge before its contents are deserialized,
229# and in this moment we already need a room for predecessors and successors.
230class ExplodedNode(object):
231    def __init__(self):
232        super(ExplodedNode, self).__init__()
233        self.predecessors = []
234        self.successors = []
235
236    def construct(self, node_id, json_node):
237        logging.debug('Adding ' + node_id)
238        self.node_id = json_node['node_id']
239        self.ptr = json_node['pointer']
240        self.points = [ProgramPoint(p) for p in json_node['program_points']]
241        self.state = ProgramState(json_node['state_id'],
242                                  json_node['program_state']) \
243            if json_node['program_state'] is not None else None
244
245        assert self.node_name() == node_id
246
247    def node_name(self):
248        return 'Node' + self.ptr
249
250
251# A deserialized ExplodedGraph. Constructed by consuming a .dot file
252# line-by-line.
253class ExplodedGraph(object):
254    # Parse .dot files with regular expressions.
255    node_re = re.compile(
256        '^(Node0x[0-9a-f]*) \\[shape=record,.*label="{(.*)\\\\l}"\\];$')
257    edge_re = re.compile(
258        '^(Node0x[0-9a-f]*) -> (Node0x[0-9a-f]*);$')
259
260    def __init__(self):
261        super(ExplodedGraph, self).__init__()
262        self.nodes = collections.defaultdict(ExplodedNode)
263        self.root_id = None
264        self.incomplete_line = ''
265
266    def add_raw_line(self, raw_line):
267        if raw_line.startswith('//'):
268            return
269
270        # Allow line breaks by waiting for ';'. This is not valid in
271        # a .dot file, but it is useful for writing tests.
272        if len(raw_line) > 0 and raw_line[-1] != ';':
273            self.incomplete_line += raw_line
274            return
275        raw_line = self.incomplete_line + raw_line
276        self.incomplete_line = ''
277
278        # Apply regexps one by one to see if it's a node or an edge
279        # and extract contents if necessary.
280        logging.debug('Line: ' + raw_line)
281        result = self.edge_re.match(raw_line)
282        if result is not None:
283            logging.debug('Classified as edge line.')
284            pred = result.group(1)
285            succ = result.group(2)
286            self.nodes[pred].successors.append(succ)
287            self.nodes[succ].predecessors.append(pred)
288            return
289        result = self.node_re.match(raw_line)
290        if result is not None:
291            logging.debug('Classified as node line.')
292            node_id = result.group(1)
293            if len(self.nodes) == 0:
294                self.root_id = node_id
295            # Note: when writing tests you don't need to escape everything,
296            # even though in a valid dot file everything is escaped.
297            node_label = result.group(2).replace('\\l', '') \
298                                        .replace(' ', '') \
299                                        .replace('\\"', '"') \
300                                        .replace('\\{', '{') \
301                                        .replace('\\}', '}') \
302                                        .replace('\\\\', '\\') \
303                                        .replace('\\|', '|') \
304                                        .replace('\\<', '\\\\<') \
305                                        .replace('\\>', '\\\\>') \
306                                        .rstrip(',')
307            logging.debug(node_label)
308            json_node = json.loads(node_label)
309            self.nodes[node_id].construct(node_id, json_node)
310            return
311        logging.debug('Skipping.')
312
313
314# A visitor that dumps the ExplodedGraph into a DOT file with fancy HTML-based
315# syntax highlighing.
316class DotDumpVisitor(object):
317    def __init__(self, do_diffs):
318        super(DotDumpVisitor, self).__init__()
319        self._do_diffs = do_diffs
320
321    @staticmethod
322    def _dump_raw(s):
323        print(s, end='')
324
325    @staticmethod
326    def _dump(s):
327        print(s.replace('&', '&amp;')
328               .replace('{', '\\{')
329               .replace('}', '\\}')
330               .replace('\\<', '&lt;')
331               .replace('\\>', '&gt;')
332               .replace('\\l', '<br />')
333               .replace('|', '\\|'), end='')
334
335    @staticmethod
336    def _diff_plus_minus(is_added):
337        if is_added is None:
338            return ''
339        if is_added:
340            return '<font color="forestgreen">+</font>'
341        return '<font color="red">-</font>'
342
343    def visit_begin_graph(self, graph):
344        self._graph = graph
345        self._dump_raw('digraph "ExplodedGraph" {\n')
346        self._dump_raw('label="";\n')
347
348    def visit_program_point(self, p):
349        if p.kind in ['Edge', 'BlockEntrance', 'BlockExit']:
350            color = 'gold3'
351        elif p.kind in ['PreStmtPurgeDeadSymbols',
352                        'PostStmtPurgeDeadSymbols']:
353            color = 'red'
354        elif p.kind in ['CallEnter', 'CallExitBegin', 'CallExitEnd']:
355            color = 'blue'
356        elif p.kind in ['Statement']:
357            color = 'cyan3'
358        else:
359            color = 'forestgreen'
360
361        if p.kind == 'Statement':
362            if p.loc is not None:
363                self._dump('<tr><td align="left" width="0">'
364                           '%s:<b>%s</b>:<b>%s</b>:</td>'
365                           '<td align="left" width="0"><font color="%s">'
366                           '%s</font></td><td>%s</td></tr>'
367                           % (p.loc.filename, p.loc.line,
368                              p.loc.col, color, p.stmt_kind, p.pretty))
369            else:
370                self._dump('<tr><td align="left" width="0">'
371                           '<i>Invalid Source Location</i>:</td>'
372                           '<td align="left" width="0">'
373                           '<font color="%s">%s</font></td><td>%s</td></tr>'
374                           % (color, p.stmt_kind, p.pretty))
375        elif p.kind == 'Edge':
376            self._dump('<tr><td width="0"></td>'
377                       '<td align="left" width="0">'
378                       '<font color="%s">%s</font></td><td align="left">'
379                       '[B%d] -\\> [B%d]</td></tr>'
380                       % (color, p.kind, p.src_id, p.dst_id))
381        else:
382            # TODO: Print more stuff for other kinds of points.
383            self._dump('<tr><td width="0"></td>'
384                       '<td align="left" width="0" colspan="2">'
385                       '<font color="%s">%s</font></td></tr>'
386                       % (color, p.kind))
387
388    def visit_environment(self, e, prev_e=None):
389        self._dump('<table border="0">')
390
391        def dump_location_context(lc, is_added=None):
392            self._dump('<tr><td>%s</td>'
393                       '<td align="left"><b>%s</b></td>'
394                       '<td align="left"><font color="grey60">%s </font>'
395                       '%s</td></tr>'
396                       % (self._diff_plus_minus(is_added),
397                          lc.caption, lc.decl,
398                          ('(line %s)' % lc.line) if lc.line is not None
399                          else ''))
400
401        def dump_binding(f, b, is_added=None):
402            self._dump('<tr><td>%s</td>'
403                       '<td align="left"><i>S%s</i></td>'
404                       '<td align="left">%s</td>'
405                       '<td align="left">%s</td></tr>'
406                       % (self._diff_plus_minus(is_added),
407                          b.stmt_id, b.pretty, f.bindings[b]))
408
409        frames_updated = e.diff_frames(prev_e) if prev_e is not None else None
410        if frames_updated:
411            for i in frames_updated:
412                f = e.frames[i]
413                prev_f = prev_e.frames[i]
414                dump_location_context(f.location_context)
415                bindings_removed, bindings_added = f.diff_bindings(prev_f)
416                for b in bindings_removed:
417                    dump_binding(prev_f, b, False)
418                for b in bindings_added:
419                    dump_binding(f, b, True)
420        else:
421            for f in e.frames:
422                dump_location_context(f.location_context)
423                for b in f.bindings:
424                    dump_binding(f, b)
425
426        self._dump('</table>')
427
428    def visit_environment_in_state(self, s, prev_s=None):
429        self._dump('<tr><td align="left">'
430                   '<b>Environment: </b>')
431        if s.environment is None:
432            self._dump('<i> Nothing!</i>')
433        else:
434            if prev_s is not None and prev_s.environment is not None:
435                if s.environment.is_different(prev_s.environment):
436                    self._dump('</td></tr><tr><td align="left">')
437                    self.visit_environment(s.environment, prev_s.environment)
438                else:
439                    self._dump('<i> No changes!</i>')
440            else:
441                self._dump('</td></tr><tr><td align="left">')
442                self.visit_environment(s.environment)
443
444        self._dump('</td></tr>')
445
446    def visit_store(self, s, prev_s=None):
447        self._dump('<table border="0">')
448
449        def dump_binding(s, c, b, is_added=None):
450            self._dump('<tr><td>%s</td>'
451                       '<td align="left">%s</td>'
452                       '<td align="left">%s</td>'
453                       '<td align="left">%s</td>'
454                       '<td align="left">%s</td></tr>'
455                       % (self._diff_plus_minus(is_added),
456                          s.clusters[c].base_region, b.offset,
457                          '(<i>Default</i>)' if b.kind == 'Default'
458                          else '',
459                          s.clusters[c].bindings[b]))
460
461        if prev_s is not None:
462            clusters_removed, clusters_added, clusters_updated = \
463                s.diff_clusters(prev_s)
464            for c in clusters_removed:
465                for b in prev_s.clusters[c].bindings:
466                    dump_binding(prev_s, c, b, False)
467            for c in clusters_updated:
468                bindings_removed, bindings_added = \
469                    s.clusters[c].diff_bindings(prev_s.clusters[c])
470                for b in bindings_removed:
471                    dump_binding(prev_s, c, b, False)
472                for b in bindings_added:
473                    dump_binding(s, c, b, True)
474            for c in clusters_added:
475                for b in s.clusters[c].bindings:
476                    dump_binding(s, c, b, True)
477        else:
478            for c in s.clusters:
479                for b in s.clusters[c].bindings:
480                    dump_binding(s, c, b)
481
482        self._dump('</table>')
483
484    def visit_store_in_state(self, s, prev_s=None):
485        self._dump('<tr><td align="left"><b>Store: </b>')
486        if s.store is None:
487            self._dump('<i> Nothing!</i>')
488        else:
489            if prev_s is not None and prev_s.store is not None:
490                if s.store.is_different(prev_s.store):
491                    self._dump('</td></tr><tr><td align="left">')
492                    self.visit_store(s.store, prev_s.store)
493                else:
494                    self._dump('<i> No changes!</i>')
495            else:
496                self._dump('</td></tr><tr><td align="left">')
497                self.visit_store(s.store)
498        self._dump('</td></tr>')
499
500    def visit_generic_map(self, m, prev_m=None):
501        self._dump('<table border="0">')
502
503        def dump_pair(m, k, is_added=None):
504            self._dump('<tr><td>%s</td>'
505                       '<td align="left">%s</td>'
506                       '<td align="left">%s</td></tr>'
507                       % (self._diff_plus_minus(is_added),
508                          k, m.generic_map[k]))
509
510        if prev_m is not None:
511            removed, added = m.diff(prev_m)
512            for k in removed:
513                dump_pair(prev_m, k, False)
514            for k in added:
515                dump_pair(m, k, True)
516        else:
517            for k in m.generic_map:
518                dump_pair(m, k, None)
519
520        self._dump('</table>')
521
522    def visit_generic_map_in_state(self, selector, s, prev_s=None):
523        self._dump('<tr><td align="left">'
524                   '<b>Ranges: </b>')
525        m = getattr(s, selector)
526        if m is None:
527            self._dump('<i> Nothing!</i>')
528        else:
529            prev_m = None
530            if prev_s is not None:
531                prev_m = getattr(prev_s, selector)
532                if prev_m is not None:
533                    if m.is_different(prev_m):
534                        self._dump('</td></tr><tr><td align="left">')
535                        self.visit_generic_map(m, prev_m)
536                    else:
537                        self._dump('<i> No changes!</i>')
538            if prev_m is None:
539                self._dump('</td></tr><tr><td align="left">')
540                self.visit_generic_map(m)
541        self._dump('</td></tr>')
542
543    def visit_state(self, s, prev_s):
544        self.visit_store_in_state(s, prev_s)
545        self._dump('<hr />')
546        self.visit_environment_in_state(s, prev_s)
547        self._dump('<hr />')
548        self.visit_generic_map_in_state('constraints', s, prev_s)
549
550    def visit_node(self, node):
551        self._dump('%s [shape=record,label=<<table border="0">'
552                   % (node.node_name()))
553
554        self._dump('<tr><td bgcolor="grey"><b>Node %d (%s) - '
555                   'State %s</b></td></tr>'
556                   % (node.node_id, node.ptr, node.state.state_id
557                      if node.state is not None else 'Unspecified'))
558        self._dump('<tr><td align="left" width="0">')
559        if len(node.points) > 1:
560            self._dump('<b>Program points:</b></td></tr>')
561        else:
562            self._dump('<b>Program point:</b></td></tr>')
563        self._dump('<tr><td align="left" width="0">'
564                   '<table border="0" align="left" width="0">')
565        for p in node.points:
566            self.visit_program_point(p)
567        self._dump('</table></td></tr>')
568
569        if node.state is not None:
570            self._dump('<hr />')
571            prev_s = None
572            # Do diffs only when we have a unique predecessor.
573            # Don't do diffs on the leaf nodes because they're
574            # the important ones.
575            if self._do_diffs and len(node.predecessors) == 1 \
576               and len(node.successors) > 0:
577                prev_s = self._graph.nodes[node.predecessors[0]].state
578            self.visit_state(node.state, prev_s)
579        self._dump_raw('</table>>];\n')
580
581    def visit_edge(self, pred, succ):
582        self._dump_raw('%s -> %s;\n' % (pred.node_name(), succ.node_name()))
583
584    def visit_end_of_graph(self):
585        self._dump_raw('}\n')
586
587
588# A class that encapsulates traversal of the ExplodedGraph. Different explorer
589# kinds could potentially traverse specific sub-graphs.
590class Explorer(object):
591    def __init__(self):
592        super(Explorer, self).__init__()
593
594    def explore(self, graph, visitor):
595        visitor.visit_begin_graph(graph)
596        for node in sorted(graph.nodes):
597            logging.debug('Visiting ' + node)
598            visitor.visit_node(graph.nodes[node])
599            for succ in sorted(graph.nodes[node].successors):
600                logging.debug('Visiting edge: %s -> %s ' % (node, succ))
601                visitor.visit_edge(graph.nodes[node], graph.nodes[succ])
602        visitor.visit_end_of_graph()
603
604
605def main():
606    parser = argparse.ArgumentParser()
607    parser.add_argument('filename', type=str)
608    parser.add_argument('-v', '--verbose', action='store_const',
609                        dest='loglevel', const=logging.DEBUG,
610                        default=logging.WARNING,
611                        help='enable info prints')
612    parser.add_argument('-d', '--diff', action='store_const', dest='diff',
613                        const=True, default=False,
614                        help='display differences between states')
615    args = parser.parse_args()
616    logging.basicConfig(level=args.loglevel)
617
618    graph = ExplodedGraph()
619    with open(args.filename) as fd:
620        for raw_line in fd:
621            raw_line = raw_line.strip()
622            graph.add_raw_line(raw_line)
623
624    explorer = Explorer()
625    visitor = DotDumpVisitor(args.diff)
626    explorer.explore(graph, visitor)
627
628
629if __name__ == '__main__':
630    main()
631