]> The Tcpdump Group git mirrors - libpcap/blob - tests/visopts.py
Don't use non-blocking mode unless we have a timeout or use -n.
[libpcap] / tests / visopts.py
1 #!/usr/bin/env python
2
3 """
4 This program parse the output from pcap_compile() to visualize the CFG after
5 each optimize phase.
6
7 Usage guide:
8 1. Enable optimizier debugging code when configure libpcap,
9 and build libpcap & filtertest
10 ./configure --enable-optimizer-dbg
11 make
12 make filtertest
13 2. Run filtertest to compile BPF expression, save to output a.txt
14 ./filtertest EN10MB host 192.168.1.1 > a.txt
15 3. Send a.txt to this program's standard input
16 cat a.txt | tests/visopts.py
17 4. Step 2&3 can be merged:
18 ./filtertest EN10MB host 192.168.1.1 | tests/visopts.py
19 5. The standard output is something like this:
20 generated files under directory: /tmp/visopts-W9ekBw
21 the directory will be removed when this programs finished.
22 open this link: http://localhost:39062/expr1.html
23 6. Using open link at the 3rd line `http://localhost:39062/expr1.html'
24
25 Note:
26 1. CFG graph is translated to SVG document, expr1.html embeded them as external
27 document. If you open expr1.html as local file using file:// protocol, some
28 browsers will deny such requests so the web pages will not shown properly.
29 For chrome, you can run it using following command to avoid this:
30 chromium --disable-web-security
31 That's why this program start a localhost http server.
32 2. expr1.html use jquery from http://ajax.googleapis.com, so you need internet
33 access to show the web page.
34 """
35
36 import sys, os
37 import string
38 import subprocess
39 import json
40
41 html_template = string.Template("""
42 <html>
43 <head>
44 <title>BPF compiler optimization phases for $expr </title>
45 <style type="text/css">
46 .hc {
47 /* half width container */
48 display: inline-block;
49 float: left;
50 width: 50%;
51 }
52 </style>
53
54 <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"/></script>
55 <!--script type="text/javascript" src="./jquery.min.js"/></script-->
56 <script type="text/javascript">
57 var expr = '$expr';
58 var exprid = 1;
59 var gcount = $gcount;
60 var logs = JSON.parse('$logs');
61 logs[gcount] = "";
62
63 var leftsvg = null;
64 var rightsvg = null;
65
66 function gurl(index) {
67 index += 1;
68 if (index < 10)
69 s = "00" + index;
70 else if (index < 100)
71 s = "0" + index;
72 else
73 s = "" + index;
74 return "./expr" + exprid + "_g" + s + ".svg"
75 }
76
77 function annotate_svgs() {
78 if (!leftsvg || !rightsvg) return;
79
80 $$.each([$$(leftsvg), $$(rightsvg)], function() {
81 $$(this).find("[id|='block'][opacity]").each(function() {
82 $$(this).removeAttr('opacity');
83 });
84 });
85
86 $$(leftsvg).find("[id|='block']").each(function() {
87 var has = $$(rightsvg).find("#" + this.id).length != 0;
88 if (!has) $$(this).attr("opacity", "0.4");
89 else {
90 $$(this).click(function() {
91 var target = $$(rightsvg).find("#" + this.id);
92 var offset = $$("#rightsvgc").offset().top + target.position().top;
93 window.scrollTo(0, offset);
94 target.focus();
95 });
96 }
97 });
98 $$(rightsvg).find("[id|='block']").each(function() {
99 var has = $$(leftsvg).find("#" + this.id).length != 0;
100 if (!has) $$(this).attr("opacity", "0.4");
101 else {
102 $$(this).click(function() {
103 var target = $$(leftsvg).find("#" + this.id);
104 var offset = $$("#leftsvgc").offset().top + target.position().top;
105 window.scrollTo(0, offset);
106 target.focus();
107 });
108 }
109 });
110 }
111
112 function init_svgroot(svg) {
113 svg.setAttribute("width", "100%");
114 svg.setAttribute("height", "100%");
115 }
116 function wait_leftsvg() {
117 if (leftsvg) return;
118 var doc = document.getElementById("leftsvgc").getSVGDocument();
119 if (doc == null) {
120 setTimeout(wait_leftsvg, 500);
121 return;
122 }
123 leftsvg = doc.documentElement;
124 //console.log(leftsvg);
125 // initialize it
126 init_svgroot(leftsvg);
127 annotate_svgs();
128 }
129 function wait_rightsvg() {
130 if (rightsvg) return;
131 var doc = document.getElementById("rightsvgc").getSVGDocument();
132 if (doc == null) {
133 setTimeout(wait_rightsvg, 500);
134 return;
135 }
136 rightsvg = doc.documentElement;
137 //console.log(rightsvg);
138 // initialize it
139 init_svgroot(rightsvg);
140 annotate_svgs();
141 }
142 function load_left(index) {
143 var url = gurl(index);
144 var frag = "<embed id='leftsvgc' type='image/svg+xml' pluginspage='http://www.adobe.com/svg/viewer/install/' src='" + url + "'/>";
145 $$("#lsvg").html(frag);
146 $$("#lcomment").html(logs[index]);
147 $$("#lsvglink").attr("href", url);
148 leftsvg = null;
149 wait_leftsvg();
150 }
151 function load_right(index) {
152 var url = gurl(index);
153 var frag = "<embed id='rightsvgc' type='image/svg+xml' pluginspage='http://www.adobe.com/svg/viewer/install/' src='" + url + "'/>";
154 $$("#rsvg").html(frag);
155 $$("#rcomment").html(logs[index]);
156 $$("#rsvglink").attr("href", url);
157 rightsvg = null;
158 wait_rightsvg();
159 }
160
161 $$(document).ready(function() {
162 for (var i = 0; i < gcount; i++) {
163 var opt = "<option value='" + i + "'>loop" + i + " -- " + logs[i] + "</option>";
164 $$("#lselect").append(opt);
165 $$("#rselect").append(opt);
166 }
167 var on_selected = function() {
168 var index = parseInt($$(this).children("option:selected").val());
169 if (this.id == "lselect")
170 load_left(index);
171 else
172 load_right(index);
173 }
174 $$("#lselect").change(on_selected);
175 $$("#rselect").change(on_selected);
176
177 $$("#backward").click(function() {
178 var index = parseInt($$("#lselect option:selected").val());
179 if (index <= 0) return;
180 $$("#lselect").val(index - 1).change();
181 $$("#rselect").val(index).change();
182 });
183 $$("#forward").click(function() {
184 var index = parseInt($$("#rselect option:selected").val());
185 if (index >= gcount - 1) return;
186 $$("#lselect").val(index).change();
187 $$("#rselect").val(index + 1).change();
188 });
189
190 if (gcount >= 1) $$("#lselect").val(0).change();
191 if (gcount >= 2) $$("#rselect").val(1).change();
192 });
193 </script>
194 </head>
195 <body style="width: 96%">
196 <div>
197 <h1>$expr</h1>
198 <div style="text-align: center;">
199 <button id="backward" type="button">&lt;&lt;</button>
200 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
201 <button id="forward" type="button">&gt;&gt;</button>
202 </div>
203 </div>
204 <br/>
205 <div style="clear: both;">
206 <div class="hc lc">
207 <select id="lselect"></select>
208 <a id="lsvglink" target="_blank">open this svg in browser</a>
209 <p id="lcomment"></p>
210 </div>
211 <div class="hc rc">
212 <select id="rselect"></select>
213 <a id="rsvglink" target="_blank">open this svg in browser</a>
214 <p id="rcomment"></p>
215 </div>
216 </div>
217 <br/>
218 <div style="clear: both;">
219 <div id="lsvg" class="hc lc"></div>
220 <div id="rsvg" class="hc rc"></div>
221 </div>
222 </body>
223 </html>
224 """)
225
226 def write_html(expr, gcount, logs):
227 logs = map(lambda s: s.strip().replace("\n", "<br/>"), logs)
228
229 global html_template
230 html = html_template.safe_substitute(expr=expr.encode("string-escape"), gcount=gcount, logs=json.dumps(logs).encode("string-escape"))
231 with file("expr1.html", "wt") as f:
232 f.write(html)
233
234 def render_on_html(infile):
235 expr = None
236 gid = 1
237 log = ""
238 dot = ""
239 indot = 0
240 logs = []
241
242 for line in infile:
243 if line.startswith("machine codes for filter:"):
244 expr = line[len("machine codes for filter:"):].strip()
245 break
246 elif line.startswith("digraph BPF {"):
247 indot = 1
248 dot = line
249 elif indot:
250 dot += line
251 if line.startswith("}"):
252 indot = 2
253 else:
254 log += line
255
256 if indot == 2:
257 p = subprocess.Popen(['dot', '-Tsvg'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
258 svg = p.communicate(dot)[0]
259 with file("expr1_g%03d.svg" % (gid), "wt") as f:
260 f.write(svg)
261
262 logs.append(log)
263 gid += 1
264 log = ""
265 dot = ""
266 indot = 0
267
268 if indot != 0:
269 #unterminated dot graph for expression
270 return False
271 if expr is None:
272 # BPF parser encounter error(s)
273 return False
274 write_html(expr, gid - 1, logs)
275 return True
276
277 def run_httpd():
278 import SimpleHTTPServer
279 import SocketServer
280
281 class MySocketServer(SocketServer.TCPServer):
282 allow_reuse_address = True
283 Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
284 httpd = MySocketServer(("localhost", 0), Handler)
285 print "open this link: http://localhost:%d/expr1.html" % (httpd.server_address[1])
286 try:
287 httpd.serve_forever()
288 except KeyboardInterrupt as e:
289 pass
290
291 def main():
292 import tempfile
293 import atexit
294 import shutil
295 os.chdir(tempfile.mkdtemp(prefix="visopts-"))
296 atexit.register(shutil.rmtree, os.getcwd())
297 print "generated files under directory: %s" % os.getcwd()
298 print " the directory will be removed when this programs finished."
299
300 if not render_on_html(sys.stdin):
301 return 1
302 run_httpd()
303 return 0
304
305 if __name__ == "__main__":
306 if '-h' in sys.argv or '--help' in sys.argv:
307 print __doc__
308 exit(0)
309 exit(main())