Debian Codegraph @

Nasal/debug.nas

raw
1 # SPDX-License-Identifier: GPL-2.0-or-later
2 #
3 # NOTE! This copyright does *not* cover user models that use these Nasal
4 # services by normal function calls - this is merely considered normal use
5 # of the code, and does *not* fall under the heading of "derived work."
6 #
7 # Copyright (C) 2003-2007 by andy
8 # Copyright (C) 2005-2008 by mfranz
9 # Copyright (C) 2012-2014 by Thomas Geymayer
10 # Copyright (C) 2017-2019 by Stuart Buchanan
11 # Copyright (C) 2019-2020 by Henning Stahlke
12
13 # debug.nas -- debugging helpers
14 #------------------------------------------------------------------------------
15 #
16 # debug.dump(<variable>) ... dumps contents of variable to terminal;
17 # abbreviation for print(debug.string(v))
18 #
19 # debug.local([<frame:int>]) ... dump local variables of current
20 # or given frame
21 #
22 # debug.backtrace([<comment:string>], [<dump:bool=1>], [<skip_level:int=0>]}
23 # ... writes backtrace (similar to gdb's "bt full)
24 # dump=0: only call stack
25 # dump=1 (default): with local variables
26 # skip_level: remove this many levels from
27 # call stack
28 #
29 # debug.proptrace([<property [, <frames>]]) ... trace property write/add/remove
30 # events under the <property> subtree for
31 # a number of frames. Defaults are "/" and
32 # 2 frames (of which the first one is incomplete).
33 #
34 # debug.tree([<property> [, <mode>]) ... dump property tree under property path
35 # or props.Node hash (default: root). If
36 # <mode> is unset or 0, use flat mode
37 # (similar to props.dump()), otherwise
38 # use space indentation
39 #
40 # debug.bt() ... abbreviation for debug.backtrace()
41 #
42 # debug.string(<variable>) ... returns contents of variable as string
43 #
44 # debug.attributes(<property> [, <verb>]) ... returns attribute string for a given property.
45 # <verb>ose is by default 1, and suppressed the
46 # node's refcounter if 0.
47 #
48 # debug.isnan() returns 1 if argument is an invalid number (NaN),
49 # 0 if it's a valid number, and nil in all other cases
50 #
51 # debug.benchmark(<label:string>, <func> [, <repeat:int> [, <output:vector>]])
52 # ... runs function <repeat> times (default: nil)
53 # and prints total execution time in seconds,
54 # prefixed with <label>, while adding results
55 # to <output>, or returning the only result
56 # if <repeat> is nil.
57 #
58 # debug.benchmark_time(<func> [, <repeat:int> [, <output:vector>]])
59 # ... like debug.benchmark, but returns total
60 # execution time and does not print anything.
61 #
62 # debug.rank(<list:vector> [, <repeat:int>])
63 # ... sorts the list of functions based on execution
64 # time over <repeat> samples (default: 1).
65 #
66 # debug.print_rank(<result:vector>, <names:int>)
67 # ... prints the <result> of debug.rank with <names>
68 # (which can be a vector of [name, func] or
69 # [func, name], or a hash of name:func).
70 #
71 # debug.printerror(<err-vector>) ... prints error vector as set by call()
72 #
73 # debug.warn(<message>, <level>) ... generate debug message followed by caller stack trace
74 # skipping <level> caller levels (default: 0).
75 #
76 # debug.propify(<variable>) ... turn about everything into a props.Node
77 #
78 # debug.Probe class ... base class to collect stats; details below
79 # debug.Breakpoint class ... conditional backtrace; details below
80 #
81 # debug.addProbeToFunc(label, func) ... wraps a function with a probe
82 # debug.findFunctions(ns, recursive=0) ... find all functions in a hash (namespace)
83 #
84 # debug.addProbesToNamespace(ns, label="", recursive=0)
85 # ... combines findFunctions and addProbeToFunc
86 #
87 # CAVE: this file makes extensive use of ANSI color codes. These are
88 # interpreted by UNIX shells and MS Windows with ANSI.SYS extension
89 # installed. If the color codes aren't interpreted correctly, then
90 # set property /sim/startup/terminal-ansi-colors=0
91 #
92
93 # ANSI color code wrappers (see $ man console_codes)
94 #
95 var _title = func(s, color=nil) globals.string.color("33;42;1", s, color); # backtrace header
96 var _section = func(s, color=nil) globals.string.color("37;41;1", s, color); # backtrace frame
97 var _error = func(s, color=nil) globals.string.color("31;1", s, color); # internal errors
98 var _bench = func(s, color=nil) globals.string.color("37;45;1", s); # benchmark info
99
100 var _nil = func(s, color=nil) globals.string.color("32", s, color); # nil
101 var _string = func(s, color=nil) globals.string.color("31", s, color); # "foo"
102 var _num = func(s, color=nil) globals.string.color("31", s, color); # 0.0
103 var _bracket = func(s, color=nil) globals.string.color("", s, color); # [ ]
104 var _brace = func(s, color=nil) globals.string.color("", s, color); # { }
105 var _angle = func(s, color=nil) globals.string.color("", s, color); # < >
106 var _vartype = func(s, color=nil) globals.string.color("33", s, color); # func ghost
107 var _proptype = func(s, color=nil) globals.string.color("34", s, color); # BOOL INT LONG DOUBLE ...
108 var _path = func(s, color=nil) globals.string.color("36", s, color); # /some/property/path
109 var _internal = func(s, color=nil) globals.string.color("35", s, color); # me parents
110 var _varname = func(s, color=nil) s; # variable_name
111
112
113 ##
114 # Turn p into props.Node (if it isn't yet), or return nil.
115 #
116 var propify = func(p, create = 0) {
117 if (isghost(p) and ghosttype(p) == "prop")
118 return props.wrapNode(p);
119 if (isscalar(p) and num(p) == nil)
120 return props.globals.getNode(p, create);
121 if (isa(p, props.Node))
122 return p;
123 return nil;
124 }
125
126
127 var tree = func(n = "", graph = 1) {
128 n = propify(n);
129 if (n == nil)
130 return dump(n);
131 _tree(n, graph);
132 }
133
134
135 var _tree = func(n, graph = 1, prefix = "", level = 0) {
136 var path = n.getPath();
137 var children = n.getChildren();
138 var s = "";
139
140 if (graph) {
141 s = prefix ~ n.getName();
142 var index = n.getIndex();
143 if (index)
144 s ~= "[" ~ index ~ "]";
145 } else {
146 s = n.getPath();
147 }
148
149 if (size(children)) {
150 s ~= "/";
151 if (n.getType() != "NONE")
152 s ~= " = " ~ debug.string(n.getValue()) ~ " " ~ attributes(n)
153 ~ " " ~ _section(" PARENT-VALUE ");
154 } else {
155 s ~= " = " ~ debug.string(n.getValue()) ~ " " ~ attributes(n);
156 }
157
158 if ((var a = n.getAliasTarget()) != nil)
159 s ~= " " ~ _title(" alias to ") ~ " " ~ a.getPath();
160
161 print(s);
162
163 if (n.getType() != "ALIAS")
164 forindex (var i; children)
165 _tree(children[i], graph, prefix ~ ". ", level + 1);
166 }
167
168
169 var attributes = func(p, verbose = 1, color=nil) {
170 var r = p.getAttribute("readable") ? "" : "r";
171 var w = p.getAttribute("writable") ? "" : "w";
172 var R = p.getAttribute("trace-read") ? "R" : "";
173 var W = p.getAttribute("trace-write") ? "W" : "";
174 var A = p.getAttribute("archive") ? "A" : "";
175 var U = p.getAttribute("userarchive") ? "U" : "";
176 var P = p.getAttribute("preserve") ? "P" : "";
177 var T = p.getAttribute("tied") ? "T" : "";
178 var attr = r ~ w ~ R ~ W ~ A ~ U ~ P ~ T;
179 var type = "(" ~ p.getType();
180 if (size(attr))
181 type ~= ", " ~ attr;
182 if (var l = p.getAttribute("listeners"))
183 type ~= ", L" ~ l;
184 if (verbose and (var c = p.getAttribute("references")) > 2)
185 type ~= ", #" ~ (c - 2);
186 return _proptype(type ~ ")", color);
187 }
188
189
190 var _dump_prop = func(p, color=nil) {
191 _path(p.getPath(), color) ~ " = " ~ debug.string(p.getValue(), color)
192 ~ " " ~ attributes(p, 1, color);
193 }
194
195
196 var _dump_var = func(v, color=nil) {
197 if (v == "me" or v == "parents")
198 return _internal(v, color);
199 else
200 return _varname(v, color);
201 }
202
203
204 var _dump_string = func(str, color=nil) {
205 var s = "'";
206 for (var i = 0; i < size(str); i += 1) {
207 var c = str[i];
208 if (c == `\``)
209 s ~= "\\`";
210 elsif (c == `\n`)
211 s ~= "\\n";
212 elsif (c == `\r`)
213 s ~= "\\r";
214 elsif (c == `\t`)
215 s ~= "\\t";
216 elsif (globals.string.isprint(c))
217 s ~= chr(c);
218 else
219 s ~= sprintf("\\x%02x", c);
220 }
221 return _string(s ~ "'", color);
222 }
223
224
225 # dump hash keys as variables if they are valid variable names, or as string otherwise
226 var _dump_key = func(s, color=nil) {
227 if (num(s) != nil)
228 return _num(s, color);
229 if (!size(s))
230 return _dump_string(s, color);
231 if (!globals.string.isalpha(s[0]) and s[0] != `_`)
232 return _dump_string(s, color);
233 for (var i = 1; i < size(s); i += 1)
234 if (!globals.string.isalnum(s[i]) and s[i] != `_`)
235 return _dump_string(s, color);
236 _dump_var(s, color);
237 }
238
239
240 var string = func(o, color=nil, ttl=5) {
241 if (o == globals and ttl < 5) return "<globals>"; # do not loop int globals
242 if (!ttl) return "<...>";
243 var t = typeof(o);
244 if (t == "nil") {
245 return _nil("null", color);
246
247 } elsif (isscalar(o)) {
248 return num(o) == nil ? _dump_string(o, color) : _num(o~"", color);
249
250 } elsif (isvec(o)) {
251 var s = "";
252 forindex (var i; o)
253 s ~= (i == 0 ? "" : ", ") ~ debug.string(o[i], color, ttl - 1);
254 return _bracket("[", color) ~ s ~ _bracket("]", color);
255
256 } elsif (ishash(o)) {
257 if (contains(o, "parents") and isvec(o.parents)
258 and size(o.parents) == 1 and o.parents[0] == props.Node)
259 return _angle("'<", color) ~ _dump_prop(o, color) ~ _angle(">'", color);
260
261 var k = keys(o);
262 var s = "";
263 forindex (var i; k)
264 s ~= (i == 0 ? "" : ", ") ~ _dump_key(k[i], color) ~ ": " ~ debug.string(o[k[i]], color, ttl - 1);
265 return _brace("{", color) ~ " " ~ s ~ " " ~ _brace("}", color);
266
267 } elsif (isghost(o)) {
268 return _angle("'<", color) ~ _nil(ghosttype(o), color) ~ _angle(">'", color);
269
270 } else {
271 return _angle("'<", color) ~ _vartype(t, color) ~ _angle(">'", color);
272 }
273 }
274
275
276 var dump = func(vars...) {
277 if (!size(vars))
278 return local(1);
279 if (size(vars) == 1)
280 return print(debug.string(vars[0]));
281 forindex (var i; vars)
282 print(globals.string.color("33;40;1", "#" ~ i) ~ " ", debug.string(vars[i]));
283 }
284
285
286 var local = func(frame = 0) {
287 var v = caller(frame + 1);
288 print(v == nil ? _error("<no such frame>") : debug.string(v[0]));
289 return v;
290 }
291
292 # According to the Nasal design doc funtions do not have unique internal names.
293 # Nevertheless you can sometimes find a matching symbol, so funcname may help to
294 # make debug output more helpful, but unfortunately you cannot rely on it.
295 var funcname = func(f) {
296 if (!isfunc(f)) return "";
297 var namespace = closure(f);
298
299 foreach (var k; keys(namespace)) {
300 if (isfunc(namespace[k])) {
301 if (namespace[k] == f)
302 return k;
303 }
304 }
305 return "-unknown-";
306 }
307
308 # Write backtrace information.
309 #
310 # desc:
311 # Text to write in first line.
312 # dump_vars:
313 # If true, show info about variables.
314 # skip_level:
315 # How many top-level stack frames to skip.
316 # shorten:
317 # If greater than 10, max filename length before being trimmed.
318 #
319 var backtrace = func(desc = nil, dump_vars = 1, skip_level = 0, shorten = 50) {
320 var d = (desc == nil) ? "" : " '" ~ desc ~ "'";
321 print("");
322 print(_title("### backtrace" ~ d ~ " ###"));
323 skip_level += 1;
324 for (var i = skip_level; 1; i += 1) {
325 if ((var v = caller(i)) == nil) return caller(i - 1);
326 var filename = v[2];
327 var line = v[3];
328 if (shorten >= 10 and size(filename) > shorten)
329 filename = substr(filename, 0, 5)~"[...]"~substr(filename, -(shorten-10));
330 print(_section(sprintf("#%-2d called from %s:%d (%s) (locals %s):",
331 i - skip_level, filename, line, funcname(v[1]), id(v[0]))));
332 if (dump_vars) dump(v[0]);
333 }
334 }
335 var bt = backtrace;
336
337
338 var proptrace = func(root = "/", frames = 2) {
339 var events = 0;
340 var trace = setlistener(propify(root), func(this, base, type) {
341 events += 1;
342 if (type > 0)
343 print(_nil("ADD "), this.getPath());
344 elsif (type < 0)
345 print(_num("DEL "), this.getPath());
346 else
347 print("SET ", this.getPath(), " = ", debug.string(this.getValue()), " ", attributes(this));
348 }, 0, 2);
349 var mark = setlistener("/sim/signals/frame", func {
350 print("-------------------- FRAME --------------------");
351 if (!frames) {
352 removelistener(trace);
353 removelistener(mark);
354 print("proptrace: stop (", events, " calls)");
355 }
356 frames -= 1;
357 });
358 }
359
360
361 ##
362 # Executes function fn "repeat" times and prints execution time in seconds. If repeat
363 # is an integer and an optional "output" argument is specified, each test's result
364 # is appended to that vector, then the vector is returned. If repeat is nil, then
365 # the function is run once and the result returned. Otherwise, the result is discarded.
366 # Examples:
367 #
368 # var test = func { getprop("/sim/aircraft"); }
369 # debug.benchmark("test()/1", test, 1000);
370 # debug.benchmark("test()/2", func setprop("/sim/aircraft", ""), 1000);
371 #
372 # var results = debug.benchmark("test()", test, 1000, []);
373 # print(" Results were:");
374 # print(" ", debug.string(results));
375 #
376 var benchmark = func(label, fn, repeat = nil, output=nil) {
377 var start = var end = nil;
378 if (repeat == nil) {
379 start = systime();
380 output = fn();
381 } elsif (isvec(output)) {
382 start = systime();
383 for (var i = 0; i < repeat; i += 1)
384 append(output, fn());
385 } else {
386 start = systime();
387 for (var i = 0; i < repeat; i += 1)
388 fn();
389 }
390 end = systime();
391 print(_bench(sprintf(" %s --> %.6f s ", label, end - start)));
392 return output;
393 }
394
395 var benchmark_time = func(fn, repeat = 1, output = nil) {
396 var start = var end = nil;
397 if (repeat == nil) {
398 start = systime();
399 output = fn();
400 } elsif (isvec(output)) {
401 start = systime();
402 for (var i = 0; i < repeat; i += 1)
403 append(output, fn());
404 } else {
405 start = systime();
406 for (var i = 0; i < repeat; i += 1)
407 fn();
408 }
409 end = systime();
410 return end - start;
411 }
412
413 ##
414 # Executes each function in the list and returns a sorted vector with the fastest
415 # on top (i.e. first). Each position in the result is a vector of [func, time].
416 #
417 var rank = func(list, repeat = nil) {
418 var result = [];
419 foreach (var fn; list) {
420 var time = benchmark_time(fn, repeat);
421 append(result, [fn, time]);
422 }
423 return sort(result, func(a,b) a[1] < b[1] ? -1 : a[1] > b[1] ? 1 : 0);
424 }
425
426 var print_rank = func(label, list, names) {
427 print("Test results for "~label);
428 var first = 1;
429 var longest = list[-1][1];
430 foreach (var item; list) {
431 var (fn, time) = item;
432 var name = nil;
433 if (isvec(names)) {
434 foreach (var l; names) {
435 if (l[1] == fn) {
436 name = l[0]; break;
437 } elsif (l[0] == fn) {
438 name = l[1]; break;
439 }
440 }
441 } else {
442 foreach (var name; keys(names)) {
443 if (names[name] == fn) break;
444 else name = nil;
445 }
446 }
447 if (name == nil) die("function not found");
448 print(" "~name~(first?" (fastest)":"")~" took "~(time*1000)~" ms ("~(time/longest*100)~"%) time");
449 first = 0;
450 }
451 return list;
452 }
453
454
455 ##
456 # print error vector as set by call(). By using call() one can execute
457 # code that catches "exceptions" (by a die() call or errors). The Nasal
458 # code doesn't abort in this case. Example:
459 #
460 # var possibly_buggy = func { ... }
461 # call(possibly_buggy, nil, var err = []);
462 # debug.printerror(err);
463 #
464 var printerror = func(err) {
465 if (!size(err))
466 return;
467 printf("%s:\n at %s, line %d", err[0], err[1], err[2]);
468 for (var i = 3; i < size(err); i += 2)
469 printf(" called from: %s, line %d", err[i], err[i + 1]);
470 }
471
472
473 # like die(), but code execution continues. The level argument defines
474 # how many caller() levels to omit. One is automatically omitted, as
475 # this would only point to debug.warn(), where the event in question
476 # didn't happen.
477 #
478 var warn = func(msg, level = 0) {
479 var c = caller(level += 1);
480 if (c == nil)
481 die("debug.warn with invalid level argument");
482 printf("%s:\n at %s, line %d", msg, c[2], c[3]);
483 while ((c = caller(level += 1)) != nil)
484 printf(" called from: %s, line %d", c[2], c[3]);
485 }
486
487
488 var isnan = func {
489 call(math.sin, arg, var err = []);
490 return !!size(err);
491 }
492
493 # Probe class - collect statistics; controlled via property tree
494 # Data can be viewed / modified in the prop tree /_debug/nas/probe/<myLabel>/*
495 # ./enable bool,
496 # ./reset bool, reset hit counters to 0 and _start_time to now
497 # ./hits[i] number of hits, by default i=0 -> hits
498 # secondary counters can be added under the same path
499 # with addCounter()
500 # ./time after generateStats() show how long the probe was enabled
501 # ./hps after generateStats() show avg. hits/second
502 # ./hitratio after generateStats() if two counters: hits[1]/hits[0]
503 #
504 # == Example ==
505 # var myProbe = debug.Probe.new("myLabel").enable();
506 # var cnt2 = myProbe.addCounter(); # create a 2nd counter
507 #
508 # #at the place of interest (e.g. in some loop or class method) insert:
509 # myProbe.hit(); # count how often this place in the code is hit
510 # if (condition)
511 # myProbe.hit(cnt2); # count how often condition is true
512 #
513 # print(myProbe.getHits());
514 # print(myProbe.getHits(cnt2)/myProbe.getHits()); # print hit ratio
515 #
516 var Probe = {
517 _instances: {},
518
519 _uid: func(label, class) {
520 class = globals.string.replace(class, " ", "_");
521 label = globals.string.replace(label, " ", "_");
522 label = globals.string.replace(label, "/", "_");
523 label = globals.string.replace(label, "\\", "_");
524 return class~"-"~label;
525 },
526
527 # label: Used in property path
528 # prefix: Optional
529 new: func(label, class = "probe") {
530 if (!isscalar(label) or !isscalar(class)) {
531 die("Invalid argument type to Probe.new");
532 }
533 var uid = me._uid(label,class);
534 if (Probe._instances[uid] != nil) return Probe._instances[uid];
535
536 var obj = {
537 parents: [Probe],
538 uid: uid,
539 label: label,
540 hits: [0],
541 node: nil,
542 _enableN: nil,
543 _resetN: nil,
544 _hitsN: [],
545 _start_time: 0,
546 _stop_time: 0,
547 _timeoutN: nil, # > 0, disable probe after _timeout seconds
548 _L: [],
549 };
550
551 obj.node = props.globals.getNode("/_debug/nas/"~class~"/"~label, 1);
552 obj.node.removeChildren();
553 obj._enableN = obj.node.addChild("enable");
554 obj._enableN.setBoolValue(0);
555 append(obj._L,
556 setlistener(obj._enableN, func(n) {
557 if (n.getValue()) obj.enable();
558 else obj.disable();
559 }, 0, 0)
560 );
561
562 obj._resetN = obj.node.addChild("reset");
563 obj._resetN.setBoolValue(0);
564 append(obj._L,
565 setlistener(obj._resetN, func(n) {
566 if (n.getValue()) {
567 obj.reset();
568 n.setValue(0);
569 }
570 }, 0, 0)
571 );
572
573 append(obj._hitsN, obj.node.addChild("hits"));
574 obj._hitsN[0].setIntValue(0);
575 # for live monitoring via prop browser, alias all hit counters in one place
576 props.globals.getNode("/_debug/nas/_stats/"~obj.uid, 1)
577 .alias(obj._hitsN[0]);
578 Probe._instances[obj.uid] = obj;
579 return obj;
580 },
581
582 del: func () {
583 foreach (var l; me._L) {
584 removelistener(l);
585 }
586 me.node.remove();
587 Probe._instances[me.uid] = nil;
588 },
589
590 reset: func {
591 forindex (var i; me.hits) {
592 me.hits[i] = 0;
593 me._hitsN[i].setValue(0);
594 }
595 me._start_time = systime();
596 },
597
598 # set timeout, next hit() after timeout will disable()
599 setTimeout: func(seconds) {
600 if (!isa(me._timeoutN, props.Node))
601 me._timeoutN = me.node.getNode("timeout", 1);
602 me._timeoutN.setValue(num(seconds) or 0);
603 return me;
604 },
605
606 #enable counting
607 enable: func {
608 me._enableN.setValue(1);
609 me._start_time = systime();
610 return me;
611 },
612
613 #disable counting, write time and hit/s to property tree
614 disable: func {
615 me._enableN.setValue(0);
616 me._stop_time = systime();
617 me.generateStats();
618 return me;
619 },
620
621 generateStats: func {
622 if (me._start_time) {
623 if (me._enableN.getValue())
624 me._stop_time = systime();
625 var dt = me._stop_time - me._start_time;
626 me.node.getNode("time", 1).setValue(dt);
627 me.node.getNode("hps", 1).setValue(me.hits[0] / dt );
628 if (size(me.hits) == 2)
629 me.node.getNode("hitratio",1).setValue(me.hits[1] / me.hits[0] or 1);
630 }
631 },
632
633 getHits: func(counter_id = 0) {
634 return me.hits[counter_id];
635 },
636
637 # add secondary counter(s)
638 # returns counter id
639 addCounter: func {
640 append(me._hitsN, me.node.addChild("hits"));
641 append(me.hits, 0);
642 return size(me._hitsN) - 1;
643 },
644
645 # increment counter (if enabled)
646 # use addCounter() before using counter_id > 0
647 hit: func(counter_id = 0, callback = nil) {
648 if (me._enableN.getValue()) {
649 if (counter_id >= size(me._hitsN)) {
650 print("debug.Probe.hit(): Invalid counter_id");
651 me.disable();
652 return nil;
653 }
654 if (isa(me._timeoutN, props.Node)) {
655 var timeout = me._timeoutN.getValue();
656 if (timeout and systime() - me._start_time > timeout) {
657 return me.disable();
658 }
659 }
660 me.hits[counter_id] += 1;
661 me._hitsN[counter_id].increment();
662 if (isfunc(callback)) {
663 callback(me.hits);
664 }
665 }
666 return me;
667 },
668 };
669
670 # Breakpoint (BP) - do conditional backtrace (BT) controlled via property tree
671 # * count how often the BP was hit
672 # * do only a limited number of BT, avoid flooding the log / console
673 #
674 # Data can be viewed / modified in the prop tree /_debug/nas/bp/<myLabel>/*
675 # * tokens: number of backtraces to do; each hit will decrement this by 1
676 # * hits: total number of hits
677 #
678 # == Example ==
679 # var myBP = debug.Breakpoint.new("myLabel", 0);
680 # myBP.enable(4); # allow 4 hits, then be quiet
681 #
682 # #at the place of interest (e.g. in some loop or class method) insert:
683 # myBP.hit(); # do backtrace here if tokens > 0, reduce tokens by 1
684 # myBP.hit(myFunction); # same but call myFunction instead of backtrace
685 #
686 # print(myBP.getHits()); # print total number of hits
687 #
688 var Breakpoint = {
689
690 # label: Used in property path and as text for backtrace.
691 # dump_locals: bool passed to backtrace. Dump variables in BT.
692 # skip_level: int passed to backtrace.
693 new: func(label, dump_locals = 0, skip_level=0) {
694 var obj = {
695 parents: [Breakpoint, Probe.new(label, "bp")],
696 tokens: 0,
697 skip_level: num(skip_level+1), # +1 for Breakpoint.hit()
698 dump_locals: num(dump_locals),
699 };
700 obj._enableN.remove();
701 obj._enableN = obj.node.getNode("tokens", 1);
702 obj._enableN.setIntValue(0);
703
704 return obj;
705 },
706
707 # enable BP and set hit limit;
708 # tokens: int > 0; default: 1 (single shot); 0 allowed (=disable);
709 enable: func(tokens = 1) {
710 if (num(tokens) == nil) tokens = 1;
711 if (tokens < 0) tokens = 0;
712 me.tokens = tokens;
713 me._enableN.setIntValue(tokens);
714 return me;
715 },
716
717 # hit the breakpoint, e.g. do backtrace if we have tokens available
718 hit: func(callback = nil) {
719 me.hits[0] += 1;
720 me._hitsN[0].increment();
721 me.tokens = me._enableN.getValue() or 0;
722 if (me.tokens > 0) {
723 me.tokens -= 1;
724 if (isfunc(callback)) {
725 callback(me.hits[0], me.tokens);
726 }
727 else {
728 debug.backtrace(me.label, me.dump_locals, me.skip_level);
729 }
730 me._enableN.setValue(me.tokens);
731 }
732 return me;
733 },
734
735 };
736
737 # Tracer - perform conditional backtraces / statistics controlled via property tree
738 # * backtraces are written to property tree
739 # * do only a limited number of BT, avoid flooding the log / console
740 # * trace statistics can be dumped to XML file
741 #
742 # Data can be viewed / modified in the prop tree /_debug/nas/trc/<myLabel>/*
743 # * tokens: number of backtraces to do; each hit will decrement this by 1
744 # * hits: total number of hits
745 #
746 # == Example ==
747 # var myBP = debug.Tracer.new("myLabel", 0);
748 # myBP.enable(4); # allow 4 hits, then be quiet
749 #
750 # #at the place of interest (e.g. in some loop or class method) insert:
751 # myBP.hit(); # do backtrace here if tokens > 0, reduce tokens by 1
752 # myBP.hit(myFunction); # same but call myFunction instead of backtrace
753 #
754 # print(myBP.getHits()); # print total number of hits
755 #
756 var Tracer = {
757
758 # label: Used in property path and as text for backtrace.
759 # dump_locals: bool passed to backtrace. Dump variables in BT.
760 # skip_level: int passed to backtrace.
761 new: func(label, dump_locals = 0, skip_level=0) {
762 var obj = {
763 parents: [Tracer, Probe.new(label, "trc")],
764 tokens: 0,
765 skip_level: num(skip_level+1), # +1 for Tracer.hit()
766 dump_locals: num(dump_locals),
767 };
768 obj._enableN.remove();
769 obj._enableN = obj.node.getNode("tokens", 1);
770 obj._enableN.setIntValue(0);
771
772 obj._dumpN = obj.node.addChild("dump-trace");
773 obj._dumpN.setBoolValue(0);
774 append(obj._L,
775 setlistener(obj._dumpN, func(n) {
776 if (n.getValue() == 1) obj.dumpTrace();
777 n.setBoolValue(0);
778 }, 0, 0)
779 );
780
781 obj._resetTraceN = obj.node.addChild("reset-trace");
782 obj._resetTraceN.setBoolValue(0);
783 append(obj._L,
784 setlistener(obj._resetTraceN, func(n) {
785 if (n.getValue() == 1) obj.resetTrace();
786 n.setBoolValue(0);
787 }, 0, 0)
788 );
789 return obj;
790 },
791
792 # enable BP and set hit limit;
793 # tokens: int > 0; default: 1 (single shot); 0 allowed (=disable);
794 enable: func(tokens = 1) {
795 if (num(tokens) == nil) tokens = 1;
796 if (tokens < 0) tokens = 0;
797 me.tokens = tokens;
798 me._enableN.setIntValue(tokens);
799 return me;
800 },
801
802 disableTracing: func() {
803 me._enableN.setIntValue(0);
804 return me;
805 },
806
807 resetTrace: func () {
808 me.node.getNode("trace",1).remove();
809 },
810
811
812 hit: func(callback = nil) {
813 me.hits[0] += 1;
814 me._hitsN[0].increment();
815 me.tokens = me._enableN.getValue() or 0;
816 if (me.tokens > 0) {
817 me.tokens -= 1;
818 if (isfunc(callback)) {
819 callback(me.hits[0], me.tokens);
820 }
821 me._enableN.setValue(me.tokens);
822 me._trace(1);
823 }
824 return me;
825 },
826
827 #write backtrace to prop tree with counters
828 _trace: func(skip=0) {
829 var flat_mode = 0;
830 if (!me._enableN.getValue()) return;
831 me._enableN.decrement();
832 var tn = me.node.getNode("trace",1);
833 for (var i = skip + 1; 1; i += 1) {
834 var c = caller(i);
835 if (c == nil) break;
836 var fn = io.basename(c[2]);
837 #invalid chars are : [ ] < > =
838 fn = globals.string.replace(fn,":","_");
839 fn = globals.string.replace(fn,"#","_");
840 fn = globals.string.replace(fn,"<","_");
841 fn = globals.string.replace(fn,">","_");
842 if (!fn) fn = "_unknown_";
843 var line = num(c[3]);
844 var sid = fn~":"~line;
845 if (flat_mode) {
846 if (tn.getChild(fn,line) == nil) {
847 tn.getChild(fn,line,1).setIntValue(1);
848 }
849 else {
850 tn.getChild(fn,line).increment();
851 }
852 }
853 else {
854 tn = tn.getChild(fn,line,1);
855 if (tn.getNode("hits") == nil) {
856 tn.getNode("hits",1).setIntValue(1);
857 }
858 else {
859 tn.getNode("hits").increment();
860 }
861 }
862 }
863 },
864
865 dumpTrace: func (path = nil) {
866 #props.dump(me.node.getNode("trace",1));
867 if (path == nil) {
868 path = getprop("/sim/fg-home")~"/Export/dumpTrace-"~me.uid~".xml";
869 }
870 me.node.getNode("dump-result", 1).setValue(
871 io.write_properties(path, me.node.getNode("trace",1))
872 );
873 },
874 }; #Tracer
875
876
877 # addProbeToFunc - wrap a function with a debug probe
878 # f: function to wrap with a debug probe (hit counter)
879 # label: description, passed to probe
880 #
881 # WARNING: call() currently breaks the call stack which affects backtrace and
882 # the use of caller(i>0). Do not use addProbeToFunc on functions which rely on
883 # caller (which is probably bad coding style, but allowed).
884 #
885 var addProbeToFunc = func (f, label) {
886 if (!isfunc(f)) {
887 logprint(DEV_ALERT, "wrapFunc() error: argument is not a function.");
888 return nil;
889 }
890 if (!isstr(label)) {
891 logprint(DEV_ALERT, "wrapFunc() error: argument is not a string.");
892 return nil;
893 }
894 var __probe = Probe.new(label).enable();
895 var wrapped = func() {
896 __probe.hit();
897 return call(f, arg, me, );
898 }
899 return wrapped;
900 }
901
902 # addTracerToFunc - wrap a function with a debug breakpoint for tracing
903 # f: function to wrap with a tracer
904 # label: description, passed to breakpoint
905 #
906 # WARNING: call() currently breaks the call stack which affects backtrace and
907 # the use of caller(i>0). Do not use addTracerToFunc on functions which rely on
908 # caller (which is probably bad coding style, but allowed).
909 #
910 var addTracerToFunc = func (f, label) {
911 if (!isfunc(f)) {
912 logprint(DEV_ALERT, "wrapFunc() error: argument is not a function.");
913 return nil;
914 }
915 if (!isstr(label)) {
916 logprint(DEV_ALERT, "wrapFunc() error: argument is not a string.");
917 return nil;
918 }
919 var __trc = Tracer.new(label).enable();
920 var wrapped = func() {
921 __trc.hit();
922 return call(f, arg, me, );
923 }
924 return wrapped;
925 }
926
927 # scan a hash for function references
928 # ns: the hash to be searched
929 # recursive: if you want to search sub hashes (e.g. classes), set this to 1
930 var findFunctions = func (ns, recursive = 0) {
931 var functions = {};
932 foreach (var key; keys(ns)) {
933 if (recursive and ishash(ns[key]) and id(ns) != id(ns[key])) {
934 print(key);
935 var f = findFunctions(ns[key]);
936 foreach (var k; keys(f)) {
937 functions[key~"."~k] = f[k];
938 }
939 }
940 if (isfunc(ns[key])) {
941 functions[key] = ns[key];
942 }
943 }
944 return functions;
945 }
946
947 # add probes to all functions in a namespace for finding hotspots
948 # use property browser at runtime to check /_debug/nas/_stats/
949 # ns: hash
950 # label: description, passed to probe
951
952 var _probed_ns = {};
953 var addProbesToNamespace = func (ns, label = "") {
954 var nsid = id(ns);
955 if (_probed_ns[nsid] != nil) return;
956 else _probed_ns[nsid] = {};
957
958 var funcs = findFunctions(ns, 0);
959 foreach (var key; keys(funcs)) {
960 _probed_ns[nsid][key] = funcs[key];
961 ns[key] = addProbeToFunc(funcs[key], label~"-"~key);
962 }
963 }
964
965 var removeProbesFromNamespace = func (ns) {
966 var nsid = id(ns);
967 if (_probed_ns[nsid] == nil) {
968 logprint(DEV_ALERT, "removeProbesFromNamespace: namespace not found");
969 return;
970 }
971
972 foreach (var key; keys(_probed_ns[nsid])) {
973 ns[key] = _probed_ns[nsid][key];
974 }
975 _probed_ns[nsid] = nil;
976 }
977
978 # dump a sorted list of hit counters to console
979 var dumpProbeStats = func () {
980 var nodes = props.getNode("/_debug/nas/_stats/", 1).getChildren();
981 var data = [];
982 foreach (var n; nodes) {
983 append(data, {name: n.getName(), value: n.getValue()});
984 }
985 var mysort = func(a,b) {
986 if (a.value > b.value) return -1;
987 elsif (a.value == b.value) return 0;
988 else return 1;
989 }
990
991 foreach (var probe; sort(data, mysort)) {
992 print(probe.name," ",probe.value);
993 }
994 return;
995 }
996
997 #-- Init -----------------------------------------------------------------------
998 # General purpose breakpoint for the lazy ones.
999 var bp = Breakpoint.new("default", 0);
1000
1001 var dumpN = props.getNode("/_debug/nas/_dumpstats", 1);
1002 dumpN.setBoolValue(0);
1003 setlistener(dumpN, func(n) {
1004 n.setBoolValue(0);
1005 debug.dumpProbeStats();
1006 }, 0, 0);
1007
1008 # --prop:debug=1 enables debug mode with additional warnings
1009 #
1010
1011 if (getprop("debug")) {
1012 var writewarn = func(f, p, r) {
1013 if (!r) {
1014 var hint = "";
1015 if ((var n = props.globals.getNode(p)) != nil) {
1016 if (!n.getAttribute("writable"))
1017 hint = " (write protected)";
1018 elsif (n.getAttribute("tied"))
1019 hint = " (tied)";
1020 }
1021 warn("Warning: " ~ f ~ " -> writing to " ~ p ~ " failed" ~ hint, 2);
1022 }
1023 return r;
1024 }
1025
1026 setprop = (func { var _ = setprop; func writewarn("setprop",
1027 globals.string.join("", arg[:-2]), call(_, arg)) })();
1028 props.Node.setDoubleValue = func writewarn("setDoubleValue", me.getPath(),
1029 props._setDoubleValue(me._g, arg));
1030 props.Node.setBoolValue = func writewarn("setBoolValue", me.getPath(),
1031 props._setBoolValue(me._g, arg));
1032 props.Node.setIntValue = func writewarn("setIntValue", me.getPath(),
1033 props._setIntValue(me._g, arg));
1034 props.Node.setValue = func writewarn("setValue", me.getPath(),
1035 props._setValue(me._g, arg));
1036 }