| 1 | @[has_globals] |
| 2 | module trace_calls |
| 3 | |
| 4 | @[markused] |
| 5 | __global g_stack_base = &u8(unsafe { nil }) |
| 6 | __global g_start_time = u64(0) |
| 7 | |
| 8 | @[markused] |
| 9 | pub fn on_call(fname string) { |
| 10 | mut volatile pfbase := &u8(unsafe { nil }) |
| 11 | volatile fbase := u8(0) |
| 12 | ns := current_time() - g_start_time |
| 13 | mut ssize := u64(0) |
| 14 | mut tid := u32(0) |
| 15 | unsafe { |
| 16 | $if windows { |
| 17 | tid = C.GetCurrentThreadId() |
| 18 | } $else $if no_gettid ? { |
| 19 | tid = u32(C.pthread_self()) |
| 20 | } $else $if linux && !musl ? { |
| 21 | tid = C.gettid() |
| 22 | } $else { |
| 23 | tid = u32(C.pthread_self()) |
| 24 | } |
| 25 | pfbase = &fbase |
| 26 | ssize = u64(g_stack_base) - u64(pfbase) |
| 27 | } |
| 28 | $if x64 { |
| 29 | C.fprintf(C.stderr, c'> trace %8d %8ld %8ld %s\n', tid, ns, ssize, fname.str) |
| 30 | } $else { |
| 31 | C.fprintf(C.stderr, c'> trace %8d %8lld %8lld %s\n', tid, ns, ssize, fname.str) |
| 32 | } |
| 33 | C.fflush(C.stderr) |
| 34 | } |
| 35 | |
| 36 | @[inline] |
| 37 | fn current_time() u64 { |
| 38 | unsafe { |
| 39 | $if windows { |
| 40 | tm := u64(0) |
| 41 | C.QueryPerformanceCounter(&tm) |
| 42 | return tm |
| 43 | } $else { |
| 44 | ts := C.timespec{} |
| 45 | C.clock_gettime(C.CLOCK_MONOTONIC, &ts) |
| 46 | return u64(ts.tv_sec) * 1000000000 + u64(ts.tv_nsec) |
| 47 | } |
| 48 | } |
| 49 | } |
| 50 | |
| 51 | @[markused] |
| 52 | pub fn on_c_main(should_trace_c_main bool) { |
| 53 | g_start_time = current_time() |
| 54 | // > trace 2128896 714640 28148 fn |
| 55 | C.fprintf(C.stderr, c'# tid ns ssize name\n') |
| 56 | C.fflush(C.stderr) |
| 57 | if should_trace_c_main { |
| 58 | on_call('C.main') |
| 59 | } |
| 60 | } |
| 61 | |