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 21 22 23#===-----------------------------------------------------------------------===# 24# These data structures represent a deserialized ExplodedGraph. 25#===-----------------------------------------------------------------------===# 26 27 28# A helper function for finding the difference between two dictionaries. 29def diff_dicts(curr, prev): 30 removed = [k for k in prev if k not in curr or curr[k] != prev[k]] 31 added = [k for k in curr if k not in prev or curr[k] != prev[k]] 32 return (removed, added) 33 34 35# Represents any program state trait that is a dictionary of key-value pairs. 36class GenericMap(object): 37 def __init__(self, items): 38 self.generic_map = collections.OrderedDict(items) 39 40 def diff(self, prev): 41 return diff_dicts(self.generic_map, prev.generic_map) 42 43 def is_different(self, prev): 44 removed, added = self.diff(prev) 45 return len(removed) != 0 or len(added) != 0 46 47 48# A deserialized source location. 49class SourceLocation(object): 50 def __init__(self, json_loc): 51 super(SourceLocation, self).__init__() 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(object): 66 def __init__(self, json_pp): 67 super(ProgramPoint, self).__init__() 68 self.kind = json_pp['kind'] 69 self.tag = json_pp['tag'] 70 if self.kind == 'Edge': 71 self.src_id = json_pp['src_id'] 72 self.dst_id = json_pp['dst_id'] 73 elif self.kind == 'Statement': 74 logging.debug(json_pp) 75 self.stmt_kind = json_pp['stmt_kind'] 76 self.stmt_point_kind = json_pp['stmt_point_kind'] 77 self.stmt_id = json_pp['stmt_id'] 78 self.pointer = json_pp['pointer'] 79 self.pretty = json_pp['pretty'] 80 self.loc = SourceLocation(json_pp['location']) \ 81 if json_pp['location'] is not None else None 82 elif self.kind == 'BlockEntrance': 83 self.block_id = json_pp['block_id'] 84 85 86# A single expression acting as a key in a deserialized Environment. 87class EnvironmentBindingKey(object): 88 def __init__(self, json_ek): 89 super(EnvironmentBindingKey, self).__init__() 90 # CXXCtorInitializer is not a Stmt! 91 self.stmt_id = json_ek['stmt_id'] if 'stmt_id' in json_ek \ 92 else json_ek['init_id'] 93 self.pretty = json_ek['pretty'] 94 self.kind = json_ek['kind'] if 'kind' in json_ek else None 95 96 def _key(self): 97 return self.stmt_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# Deserialized description of a location context. 107class LocationContext(object): 108 def __init__(self, json_frame): 109 super(LocationContext, self).__init__() 110 self.lctx_id = json_frame['lctx_id'] 111 self.caption = json_frame['location_context'] 112 self.decl = json_frame['calling'] 113 self.loc = SourceLocation(json_frame['location']) \ 114 if json_frame['location'] is not None else None 115 116 def _key(self): 117 return self.lctx_id 118 119 def __eq__(self, other): 120 return self._key() == other._key() 121 122 def __hash__(self): 123 return hash(self._key()) 124 125 126# A group of deserialized Environment bindings that correspond to a specific 127# location context. 128class EnvironmentFrame(object): 129 def __init__(self, json_frame): 130 super(EnvironmentFrame, self).__init__() 131 self.location_context = LocationContext(json_frame) 132 self.bindings = collections.OrderedDict( 133 [(EnvironmentBindingKey(b), 134 b['value']) for b in json_frame['items']] 135 if json_frame['items'] is not None else []) 136 137 def diff_bindings(self, prev): 138 return diff_dicts(self.bindings, prev.bindings) 139 140 def is_different(self, prev): 141 removed, added = self.diff_bindings(prev) 142 return len(removed) != 0 or len(added) != 0 143 144 145# A deserialized Environment. This class can also hold other entities that 146# are similar to Environment, such as Objects Under Construction. 147class GenericEnvironment(object): 148 def __init__(self, json_e): 149 super(GenericEnvironment, self).__init__() 150 self.frames = [EnvironmentFrame(f) for f in json_e] 151 152 def diff_frames(self, prev): 153 # TODO: It's difficult to display a good diff when frame numbers shift. 154 if len(self.frames) != len(prev.frames): 155 return None 156 157 updated = [] 158 for i in range(len(self.frames)): 159 f = self.frames[i] 160 prev_f = prev.frames[i] 161 if f.location_context == prev_f.location_context: 162 if f.is_different(prev_f): 163 updated.append(i) 164 else: 165 # We have the whole frame replaced with another frame. 166 # TODO: Produce a nice diff. 167 return None 168 169 # TODO: Add support for added/removed. 170 return updated 171 172 def is_different(self, prev): 173 updated = self.diff_frames(prev) 174 return updated is None or len(updated) > 0 175 176 177# A single binding key in a deserialized RegionStore cluster. 178class StoreBindingKey(object): 179 def __init__(self, json_sk): 180 super(StoreBindingKey, self).__init__() 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(object): 196 def __init__(self, json_sc): 197 super(StoreCluster, self).__init__() 198 self.base_region = json_sc['cluster'] 199 self.bindings = collections.OrderedDict( 200 [(StoreBindingKey(b), b['value']) for b in json_sc['items']]) 201 202 def diff_bindings(self, prev): 203 return diff_dicts(self.bindings, prev.bindings) 204 205 def is_different(self, prev): 206 removed, added = self.diff_bindings(prev) 207 return len(removed) != 0 or len(added) != 0 208 209 210# A deserialized RegionStore. 211class Store(object): 212 def __init__(self, json_s): 213 super(Store, self).__init__() 214 self.ptr = json_s['pointer'] 215 self.clusters = collections.OrderedDict( 216 [(c['pointer'], StoreCluster(c)) for c in json_s['items']]) 217 218 def diff_clusters(self, prev): 219 removed = [k for k in prev.clusters if k not in self.clusters] 220 added = [k for k in self.clusters if k not in prev.clusters] 221 updated = [k for k in prev.clusters if k in self.clusters 222 and prev.clusters[k].is_different(self.clusters[k])] 223 return (removed, added, updated) 224 225 def is_different(self, prev): 226 removed, added, updated = self.diff_clusters(prev) 227 return len(removed) != 0 or len(added) != 0 or len(updated) != 0 228 229 230# Deserialized messages from a single checker in a single program state. 231# Basically a list of raw strings. 232class CheckerLines(object): 233 def __init__(self, json_lines): 234 super(CheckerLines, self).__init__() 235 self.lines = json_lines 236 237 def diff_lines(self, prev): 238 lines = difflib.ndiff(prev.lines, self.lines) 239 return [l.strip() for l in lines 240 if l.startswith('+') or l.startswith('-')] 241 242 def is_different(self, prev): 243 return len(self.diff_lines(prev)) > 0 244 245 246# Deserialized messages of all checkers, separated by checker. 247class CheckerMessages(object): 248 def __init__(self, json_m): 249 super(CheckerMessages, self).__init__() 250 self.items = collections.OrderedDict( 251 [(m['checker'], CheckerLines(m['messages'])) for m in json_m]) 252 253 def diff_messages(self, prev): 254 removed = [k for k in prev.items if k not in self.items] 255 added = [k for k in self.items if k not in prev.items] 256 updated = [k for k in prev.items if k in self.items 257 and prev.items[k].is_different(self.items[k])] 258 return (removed, added, updated) 259 260 def is_different(self, prev): 261 removed, added, updated = self.diff_messages(prev) 262 return len(removed) != 0 or len(added) != 0 or len(updated) != 0 263 264 265# A deserialized program state. 266class ProgramState(object): 267 def __init__(self, state_id, json_ps): 268 super(ProgramState, self).__init__() 269 logging.debug('Adding ProgramState ' + str(state_id)) 270 271 self.state_id = state_id 272 273 self.store = Store(json_ps['store']) \ 274 if json_ps['store'] is not None else None 275 276 self.environment = \ 277 GenericEnvironment(json_ps['environment']['items']) \ 278 if json_ps['environment'] is not None else None 279 280 self.constraints = GenericMap([ 281 (c['symbol'], c['range']) for c in json_ps['constraints'] 282 ]) if json_ps['constraints'] is not None else None 283 284 self.dynamic_types = GenericMap([ 285 (t['region'], '%s%s' % (t['dyn_type'], 286 ' (or a sub-class)' 287 if t['sub_classable'] else '')) 288 for t in json_ps['dynamic_types']]) \ 289 if json_ps['dynamic_types'] is not None else None 290 291 self.constructing_objects = \ 292 GenericEnvironment(json_ps['constructing_objects']) \ 293 if json_ps['constructing_objects'] is not None else None 294 295 self.checker_messages = CheckerMessages(json_ps['checker_messages']) \ 296 if json_ps['checker_messages'] is not None else None 297 298 299# A deserialized exploded graph node. Has a default constructor because it 300# may be referenced as part of an edge before its contents are deserialized, 301# and in this moment we already need a room for predecessors and successors. 302class ExplodedNode(object): 303 def __init__(self): 304 super(ExplodedNode, self).__init__() 305 self.predecessors = [] 306 self.successors = [] 307 308 def construct(self, node_id, json_node): 309 logging.debug('Adding ' + node_id) 310 self.node_id = json_node['node_id'] 311 self.ptr = json_node['pointer'] 312 self.has_report = json_node['has_report'] 313 self.is_sink = json_node['is_sink'] 314 self.points = [ProgramPoint(p) for p in json_node['program_points']] 315 self.state = ProgramState(json_node['state_id'], 316 json_node['program_state']) \ 317 if json_node['program_state'] is not None else None 318 319 assert self.node_name() == node_id 320 321 def node_name(self): 322 return 'Node' + self.ptr 323 324 325# A deserialized ExplodedGraph. Constructed by consuming a .dot file 326# line-by-line. 327class ExplodedGraph(object): 328 # Parse .dot files with regular expressions. 329 node_re = re.compile( 330 '^(Node0x[0-9a-f]*) \\[shape=record,.*label="{(.*)\\\\l}"\\];$') 331 edge_re = re.compile( 332 '^(Node0x[0-9a-f]*) -> (Node0x[0-9a-f]*);$') 333 334 def __init__(self): 335 super(ExplodedGraph, self).__init__() 336 self.nodes = collections.defaultdict(ExplodedNode) 337 self.root_id = None 338 self.incomplete_line = '' 339 340 def add_raw_line(self, raw_line): 341 if raw_line.startswith('//'): 342 return 343 344 # Allow line breaks by waiting for ';'. This is not valid in 345 # a .dot file, but it is useful for writing tests. 346 if len(raw_line) > 0 and raw_line[-1] != ';': 347 self.incomplete_line += raw_line 348 return 349 raw_line = self.incomplete_line + raw_line 350 self.incomplete_line = '' 351 352 # Apply regexps one by one to see if it's a node or an edge 353 # and extract contents if necessary. 354 logging.debug('Line: ' + raw_line) 355 result = self.edge_re.match(raw_line) 356 if result is not None: 357 logging.debug('Classified as edge line.') 358 pred = result.group(1) 359 succ = result.group(2) 360 self.nodes[pred].successors.append(succ) 361 self.nodes[succ].predecessors.append(pred) 362 return 363 result = self.node_re.match(raw_line) 364 if result is not None: 365 logging.debug('Classified as node line.') 366 node_id = result.group(1) 367 if len(self.nodes) == 0: 368 self.root_id = node_id 369 # Note: when writing tests you don't need to escape everything, 370 # even though in a valid dot file everything is escaped. 371 node_label = result.group(2).replace('\\l', '') \ 372 .replace(' ', '') \ 373 .replace('\\"', '"') \ 374 .replace('\\{', '{') \ 375 .replace('\\}', '}') \ 376 .replace('\\\\', '\\') \ 377 .replace('\\|', '|') \ 378 .replace('\\<', '\\\\<') \ 379 .replace('\\>', '\\\\>') \ 380 .rstrip(',') 381 logging.debug(node_label) 382 json_node = json.loads(node_label) 383 self.nodes[node_id].construct(node_id, json_node) 384 return 385 logging.debug('Skipping.') 386 387 388#===-----------------------------------------------------------------------===# 389# Visitors traverse a deserialized ExplodedGraph and do different things 390# with every node and edge. 391#===-----------------------------------------------------------------------===# 392 393 394# A visitor that dumps the ExplodedGraph into a DOT file with fancy HTML-based 395# syntax highlighing. 396class DotDumpVisitor(object): 397 def __init__(self, do_diffs, dark_mode, gray_mode, topo_mode): 398 super(DotDumpVisitor, self).__init__() 399 self._do_diffs = do_diffs 400 self._dark_mode = dark_mode 401 self._gray_mode = gray_mode 402 self._topo_mode = topo_mode 403 404 @staticmethod 405 def _dump_raw(s): 406 print(s, end='') 407 408 def _dump(self, s): 409 s = s.replace('&', '&') \ 410 .replace('{', '\\{') \ 411 .replace('}', '\\}') \ 412 .replace('\\<', '<') \ 413 .replace('\\>', '>') \ 414 .replace('\\l', '<br />') \ 415 .replace('|', '\\|') 416 if self._gray_mode: 417 s = re.sub(r'<font color="[a-z0-9]*">', '', s) 418 s = re.sub(r'</font>', '', s) 419 self._dump_raw(s) 420 421 @staticmethod 422 def _diff_plus_minus(is_added): 423 if is_added is None: 424 return '' 425 if is_added: 426 return '<font color="forestgreen">+</font>' 427 return '<font color="red">-</font>' 428 429 @staticmethod 430 def _short_pretty(s): 431 if s is None: 432 return None 433 if len(s) < 20: 434 return s 435 left = s.find('{') 436 right = s.rfind('}') 437 if left == -1 or right == -1 or left >= right: 438 return s 439 candidate = s[0:left + 1] + ' ... ' + s[right:] 440 if len(candidate) >= len(s): 441 return s 442 return candidate 443 444 @staticmethod 445 def _make_sloc(loc): 446 if loc is None: 447 return '<i>Invalid Source Location</i>' 448 449 def make_plain_loc(loc): 450 return '%s:<b>%s</b>:<b>%s</b>' \ 451 % (loc.filename, loc.line, loc.col) 452 453 if loc.is_macro(): 454 return '%s <font color="royalblue1">' \ 455 '(<i>spelling at </i> %s)</font>' \ 456 % (make_plain_loc(loc), make_plain_loc(loc.spelling)) 457 458 return make_plain_loc(loc) 459 460 def visit_begin_graph(self, graph): 461 self._graph = graph 462 self._dump_raw('digraph "ExplodedGraph" {\n') 463 if self._dark_mode: 464 self._dump_raw('bgcolor="gray10";\n') 465 self._dump_raw('label="";\n') 466 467 def visit_program_point(self, p): 468 if p.kind in ['Edge', 'BlockEntrance', 'BlockExit']: 469 color = 'gold3' 470 elif p.kind in ['PreStmtPurgeDeadSymbols', 471 'PostStmtPurgeDeadSymbols']: 472 color = 'red' 473 elif p.kind in ['CallEnter', 'CallExitBegin', 'CallExitEnd']: 474 color = 'dodgerblue' if self._dark_mode else 'blue' 475 elif p.kind in ['Statement']: 476 color = 'cyan4' 477 else: 478 color = 'forestgreen' 479 480 if p.kind == 'Statement': 481 # This avoids pretty-printing huge statements such as CompoundStmt. 482 # Such statements show up only at [Pre|Post]StmtPurgeDeadSymbols 483 skip_pretty = 'PurgeDeadSymbols' in p.stmt_point_kind 484 stmt_color = 'cyan3' 485 self._dump('<tr><td align="left" width="0">%s:</td>' 486 '<td align="left" width="0"><font color="%s">' 487 '%s</font> </td>' 488 '<td align="left"><i>S%s</i></td>' 489 '<td align="left"><font color="%s">%s</font></td>' 490 '<td align="left">%s</td></tr>' 491 % (self._make_sloc(p.loc), color, p.stmt_kind, 492 p.stmt_id, stmt_color, p.stmt_point_kind, 493 self._short_pretty(p.pretty) 494 if not skip_pretty else '')) 495 elif p.kind == 'Edge': 496 self._dump('<tr><td width="0"></td>' 497 '<td align="left" width="0">' 498 '<font color="%s">%s</font></td><td align="left">' 499 '[B%d] -\\> [B%d]</td></tr>' 500 % (color, 'BlockEdge', p.src_id, p.dst_id)) 501 elif p.kind == 'BlockEntrance': 502 self._dump('<tr><td width="0"></td>' 503 '<td align="left" width="0">' 504 '<font color="%s">%s</font></td>' 505 '<td align="left">[B%d]</td></tr>' 506 % (color, p.kind, p.block_id)) 507 else: 508 # TODO: Print more stuff for other kinds of points. 509 self._dump('<tr><td width="0"></td>' 510 '<td align="left" width="0" colspan="2">' 511 '<font color="%s">%s</font></td></tr>' 512 % (color, p.kind)) 513 514 if p.tag is not None: 515 self._dump('<tr><td width="0"></td>' 516 '<td colspan="3" align="left">' 517 '<b>Tag: </b> <font color="crimson">' 518 '%s</font></td></tr>' % p.tag) 519 520 def visit_environment(self, e, prev_e=None): 521 self._dump('<table border="0">') 522 523 def dump_location_context(lc, is_added=None): 524 self._dump('<tr><td>%s</td>' 525 '<td align="left"><b>%s</b></td>' 526 '<td align="left" colspan="2">' 527 '<font color="gray60">%s </font>' 528 '%s</td></tr>' 529 % (self._diff_plus_minus(is_added), 530 lc.caption, lc.decl, 531 ('(%s)' % self._make_sloc(lc.loc)) 532 if lc.loc is not None else '')) 533 534 def dump_binding(f, b, is_added=None): 535 self._dump('<tr><td>%s</td>' 536 '<td align="left"><i>S%s</i></td>' 537 '%s' 538 '<td align="left">%s</td>' 539 '<td align="left">%s</td></tr>' 540 % (self._diff_plus_minus(is_added), 541 b.stmt_id, 542 '<td align="left"><font color="%s"><i>' 543 '%s</i></font></td>' % ( 544 'lavender' if self._dark_mode else 'darkgreen', 545 ('(%s)' % b.kind) if b.kind is not None else ' ' 546 ), 547 self._short_pretty(b.pretty), f.bindings[b])) 548 549 frames_updated = e.diff_frames(prev_e) if prev_e is not None else None 550 if frames_updated: 551 for i in frames_updated: 552 f = e.frames[i] 553 prev_f = prev_e.frames[i] 554 dump_location_context(f.location_context) 555 bindings_removed, bindings_added = f.diff_bindings(prev_f) 556 for b in bindings_removed: 557 dump_binding(prev_f, b, False) 558 for b in bindings_added: 559 dump_binding(f, b, True) 560 else: 561 for f in e.frames: 562 dump_location_context(f.location_context) 563 for b in f.bindings: 564 dump_binding(f, b) 565 566 self._dump('</table>') 567 568 def visit_environment_in_state(self, selector, title, s, prev_s=None): 569 e = getattr(s, selector) 570 prev_e = getattr(prev_s, selector) if prev_s is not None else None 571 if e is None and prev_e is None: 572 return 573 574 self._dump('<hr /><tr><td align="left"><b>%s: </b>' % title) 575 if e is None: 576 self._dump('<i> Nothing!</i>') 577 else: 578 if prev_e is not None: 579 if e.is_different(prev_e): 580 self._dump('</td></tr><tr><td align="left">') 581 self.visit_environment(e, prev_e) 582 else: 583 self._dump('<i> No changes!</i>') 584 else: 585 self._dump('</td></tr><tr><td align="left">') 586 self.visit_environment(e) 587 588 self._dump('</td></tr>') 589 590 def visit_store(self, s, prev_s=None): 591 self._dump('<table border="0">') 592 593 def dump_binding(s, c, b, is_added=None): 594 self._dump('<tr><td>%s</td>' 595 '<td align="left">%s</td>' 596 '<td align="left">%s</td>' 597 '<td align="left">%s</td>' 598 '<td align="left">%s</td></tr>' 599 % (self._diff_plus_minus(is_added), 600 s.clusters[c].base_region, b.offset, 601 '(<i>Default</i>)' if b.kind == 'Default' 602 else '', 603 s.clusters[c].bindings[b])) 604 605 if prev_s is not None: 606 clusters_removed, clusters_added, clusters_updated = \ 607 s.diff_clusters(prev_s) 608 for c in clusters_removed: 609 for b in prev_s.clusters[c].bindings: 610 dump_binding(prev_s, c, b, False) 611 for c in clusters_updated: 612 bindings_removed, bindings_added = \ 613 s.clusters[c].diff_bindings(prev_s.clusters[c]) 614 for b in bindings_removed: 615 dump_binding(prev_s, c, b, False) 616 for b in bindings_added: 617 dump_binding(s, c, b, True) 618 for c in clusters_added: 619 for b in s.clusters[c].bindings: 620 dump_binding(s, c, b, True) 621 else: 622 for c in s.clusters: 623 for b in s.clusters[c].bindings: 624 dump_binding(s, c, b) 625 626 self._dump('</table>') 627 628 def visit_store_in_state(self, s, prev_s=None): 629 st = s.store 630 prev_st = prev_s.store if prev_s is not None else None 631 if st is None and prev_st is None: 632 return 633 634 self._dump('<hr /><tr><td align="left"><b>Store: </b>') 635 if st is None: 636 self._dump('<i> Nothing!</i>') 637 else: 638 if prev_st is not None: 639 if s.store.is_different(prev_st): 640 self._dump('</td></tr><tr><td align="left">') 641 self.visit_store(st, prev_st) 642 else: 643 self._dump('<i> No changes!</i>') 644 else: 645 self._dump('</td></tr><tr><td align="left">') 646 self.visit_store(st) 647 self._dump('</td></tr>') 648 649 def visit_generic_map(self, m, prev_m=None): 650 self._dump('<table border="0">') 651 652 def dump_pair(m, k, is_added=None): 653 self._dump('<tr><td>%s</td>' 654 '<td align="left">%s</td>' 655 '<td align="left">%s</td></tr>' 656 % (self._diff_plus_minus(is_added), 657 k, m.generic_map[k])) 658 659 if prev_m is not None: 660 removed, added = m.diff(prev_m) 661 for k in removed: 662 dump_pair(prev_m, k, False) 663 for k in added: 664 dump_pair(m, k, True) 665 else: 666 for k in m.generic_map: 667 dump_pair(m, k, None) 668 669 self._dump('</table>') 670 671 def visit_generic_map_in_state(self, selector, title, s, prev_s=None): 672 m = getattr(s, selector) 673 prev_m = getattr(prev_s, selector) if prev_s is not None else None 674 if m is None and prev_m is None: 675 return 676 677 self._dump('<hr />') 678 self._dump('<tr><td align="left">' 679 '<b>%s: </b>' % title) 680 if m is None: 681 self._dump('<i> Nothing!</i>') 682 else: 683 if prev_m is not None: 684 if m.is_different(prev_m): 685 self._dump('</td></tr><tr><td align="left">') 686 self.visit_generic_map(m, prev_m) 687 else: 688 self._dump('<i> No changes!</i>') 689 else: 690 self._dump('</td></tr><tr><td align="left">') 691 self.visit_generic_map(m) 692 693 self._dump('</td></tr>') 694 695 def visit_checker_messages(self, m, prev_m=None): 696 self._dump('<table border="0">') 697 698 def dump_line(l, is_added=None): 699 self._dump('<tr><td>%s</td>' 700 '<td align="left">%s</td></tr>' 701 % (self._diff_plus_minus(is_added), l)) 702 703 def dump_chk(chk, is_added=None): 704 dump_line('<i>%s</i>:' % chk, is_added) 705 706 if prev_m is not None: 707 removed, added, updated = m.diff_messages(prev_m) 708 for chk in removed: 709 dump_chk(chk, False) 710 for l in prev_m.items[chk].lines: 711 dump_line(l, False) 712 for chk in updated: 713 dump_chk(chk) 714 for l in m.items[chk].diff_lines(prev_m.items[chk]): 715 dump_line(l[1:], l.startswith('+')) 716 for chk in added: 717 dump_chk(chk, True) 718 for l in m.items[chk].lines: 719 dump_line(l, True) 720 else: 721 for chk in m.items: 722 dump_chk(chk) 723 for l in m.items[chk].lines: 724 dump_line(l) 725 726 self._dump('</table>') 727 728 def visit_checker_messages_in_state(self, s, prev_s=None): 729 m = s.checker_messages 730 prev_m = prev_s.checker_messages if prev_s is not None else None 731 if m is None and prev_m is None: 732 return 733 734 self._dump('<hr />') 735 self._dump('<tr><td align="left">' 736 '<b>Checker State: </b>') 737 if m is None: 738 self._dump('<i> Nothing!</i>') 739 else: 740 if prev_m is not None: 741 if m.is_different(prev_m): 742 self._dump('</td></tr><tr><td align="left">') 743 self.visit_checker_messages(m, prev_m) 744 else: 745 self._dump('<i> No changes!</i>') 746 else: 747 self._dump('</td></tr><tr><td align="left">') 748 self.visit_checker_messages(m) 749 750 self._dump('</td></tr>') 751 752 def visit_state(self, s, prev_s): 753 self.visit_store_in_state(s, prev_s) 754 self.visit_environment_in_state('environment', 'Environment', 755 s, prev_s) 756 self.visit_generic_map_in_state('constraints', 'Ranges', 757 s, prev_s) 758 self.visit_generic_map_in_state('dynamic_types', 'Dynamic Types', 759 s, prev_s) 760 self.visit_environment_in_state('constructing_objects', 761 'Objects Under Construction', 762 s, prev_s) 763 self.visit_checker_messages_in_state(s, prev_s) 764 765 def visit_node(self, node): 766 self._dump('%s [shape=record,' 767 % (node.node_name())) 768 if self._dark_mode: 769 self._dump('color="white",fontcolor="gray80",') 770 self._dump('label=<<table border="0">') 771 772 self._dump('<tr><td bgcolor="%s"><b>Node %d (%s) - ' 773 'State %s</b></td></tr>' 774 % ("gray20" if self._dark_mode else "gray", 775 node.node_id, node.ptr, node.state.state_id 776 if node.state is not None else 'Unspecified')) 777 if node.has_report: 778 self._dump('<tr><td><font color="red"><b>Bug Report Attached' 779 '</b></font></td></tr>') 780 if node.is_sink: 781 self._dump('<tr><td><font color="cornflowerblue"><b>Sink Node' 782 '</b></font></td></tr>') 783 if not self._topo_mode: 784 self._dump('<tr><td align="left" width="0">') 785 if len(node.points) > 1: 786 self._dump('<b>Program points:</b></td></tr>') 787 else: 788 self._dump('<b>Program point:</b></td></tr>') 789 self._dump('<tr><td align="left" width="0">' 790 '<table border="0" align="left" width="0">') 791 for p in node.points: 792 self.visit_program_point(p) 793 self._dump('</table></td></tr>') 794 795 if node.state is not None and not self._topo_mode: 796 prev_s = None 797 # Do diffs only when we have a unique predecessor. 798 # Don't do diffs on the leaf nodes because they're 799 # the important ones. 800 if self._do_diffs and len(node.predecessors) == 1 \ 801 and len(node.successors) > 0: 802 prev_s = self._graph.nodes[node.predecessors[0]].state 803 self.visit_state(node.state, prev_s) 804 self._dump_raw('</table>>];\n') 805 806 def visit_edge(self, pred, succ): 807 self._dump_raw('%s -> %s%s;\n' % ( 808 pred.node_name(), succ.node_name(), 809 ' [color="white"]' if self._dark_mode else '' 810 )) 811 812 def visit_end_of_graph(self): 813 self._dump_raw('}\n') 814 815 816#===-----------------------------------------------------------------------===# 817# Explorers know how to traverse the ExplodedGraph in a certain order. 818# They would invoke a Visitor on every node or edge they encounter. 819#===-----------------------------------------------------------------------===# 820 821 822# BasicExplorer explores the whole graph in no particular order. 823class BasicExplorer(object): 824 def __init__(self): 825 super(BasicExplorer, self).__init__() 826 827 def explore(self, graph, visitor): 828 visitor.visit_begin_graph(graph) 829 for node in sorted(graph.nodes): 830 logging.debug('Visiting ' + node) 831 visitor.visit_node(graph.nodes[node]) 832 for succ in sorted(graph.nodes[node].successors): 833 logging.debug('Visiting edge: %s -> %s ' % (node, succ)) 834 visitor.visit_edge(graph.nodes[node], graph.nodes[succ]) 835 visitor.visit_end_of_graph() 836 837 838# SinglePathExplorer traverses only a single path - the leftmost path 839# from the root. Useful when the trimmed graph is still too large 840# due to a large amount of equivalent reports. 841class SinglePathExplorer(object): 842 def __init__(self): 843 super(SinglePathExplorer, self).__init__() 844 845 def explore(self, graph, visitor): 846 visitor.visit_begin_graph(graph) 847 848 # Keep track of visited nodes in order to avoid loops. 849 visited = set() 850 node_id = graph.root_id 851 while True: 852 visited.add(node_id) 853 node = graph.nodes[node_id] 854 logging.debug('Visiting ' + node_id) 855 visitor.visit_node(node) 856 if len(node.successors) == 0: 857 break 858 859 succ_id = node.successors[0] 860 succ = graph.nodes[succ_id] 861 logging.debug('Visiting edge: %s -> %s ' % (node_id, succ_id)) 862 visitor.visit_edge(node, succ) 863 if succ_id in visited: 864 break 865 866 node_id = succ_id 867 868 visitor.visit_end_of_graph() 869 870 871#===-----------------------------------------------------------------------===# 872# The entry point to the script. 873#===-----------------------------------------------------------------------===# 874 875 876def main(): 877 parser = argparse.ArgumentParser() 878 parser.add_argument('filename', type=str) 879 parser.add_argument('-v', '--verbose', action='store_const', 880 dest='loglevel', const=logging.DEBUG, 881 default=logging.WARNING, 882 help='enable info prints') 883 parser.add_argument('-d', '--diff', action='store_const', dest='diff', 884 const=True, default=False, 885 help='display differences between states') 886 parser.add_argument('-t', '--topology', action='store_const', 887 dest='topology', const=True, default=False, 888 help='only display program points, omit states') 889 parser.add_argument('-s', '--single-path', action='store_const', 890 dest='single_path', const=True, default=False, 891 help='only display the leftmost path in the graph ' 892 '(useful for trimmed graphs that still ' 893 'branch too much)') 894 parser.add_argument('--dark', action='store_const', dest='dark', 895 const=True, default=False, 896 help='dark mode') 897 parser.add_argument('--gray', action='store_const', dest='gray', 898 const=True, default=False, 899 help='black-and-white mode') 900 args = parser.parse_args() 901 logging.basicConfig(level=args.loglevel) 902 903 graph = ExplodedGraph() 904 with open(args.filename) as fd: 905 for raw_line in fd: 906 raw_line = raw_line.strip() 907 graph.add_raw_line(raw_line) 908 909 explorer = SinglePathExplorer() if args.single_path else BasicExplorer() 910 visitor = DotDumpVisitor(args.diff, args.dark, args.gray, args.topology) 911 912 explorer.explore(graph, visitor) 913 914 915if __name__ == '__main__': 916 main() 917