| 1 | #include <u.h> |
| 2 | #include <libc.h> |
| 3 | #include <ureg.h> |
| 4 | #include "dat.h" |
| 5 | #include "fns.h" |
| 6 | |
| 7 | #undef trace |
| 8 | |
| 9 | static char magic[] = "TRACEBUF"; |
| 10 | |
| 11 | typedef struct Tracebuf Tracebuf; |
| 12 | struct Tracebuf |
| 13 | { |
| 14 | char magic[8]; |
| 15 | int wp; |
| 16 | char lines[256][80]; |
| 17 | }; |
| 18 | |
| 19 | static void* |
| 20 | alloctrace(void) |
| 21 | { |
| 22 | Tracebuf *t; |
| 23 | |
| 24 | t = kmallocz(sizeof(*t), 1); |
| 25 | memmove(t->magic, magic, sizeof(t->magic)); |
| 26 | return t; |
| 27 | } |
| 28 | |
| 29 | static void |
| 30 | checktrace(Tracebuf *t) |
| 31 | { |
| 32 | if(memcmp(t->magic, magic, sizeof(t->magic)) != 0) |
| 33 | panic("tracebuffer corrupted"); |
| 34 | } |
| 35 | |
| 36 | static void |
| 37 | freetrace(Tracebuf *t) |
| 38 | { |
| 39 | if(t == nil) |
| 40 | return; |
| 41 | checktrace(t); |
| 42 | memset(t, 0, sizeof(*t)); |
| 43 | free(t); |
| 44 | } |
| 45 | |
| 46 | static void |
| 47 | vputtrace(Tracebuf *t, char *fmt, va_list a) |
| 48 | { |
| 49 | char *s; |
| 50 | |
| 51 | checktrace(t); |
| 52 | s = t->lines[t->wp++ % nelem(t->lines)]; |
| 53 | vsnprint(s, sizeof(t->lines[0]), fmt, a); |
| 54 | if(debug > 1) |
| 55 | fprint(2, "%d\t%s\n", (current != nil) ? current->tid : 0, s); |
| 56 | } |
| 57 | |
| 58 | void inittrace(void) |
| 59 | { |
| 60 | if(debug > 0) |
| 61 | current->trace = alloctrace(); |
| 62 | } |
| 63 | |
| 64 | void exittrace(Uproc *proc) |
| 65 | { |
| 66 | Tracebuf *t; |
| 67 | |
| 68 | if(t = proc->trace){ |
| 69 | proc->trace = nil; |
| 70 | freetrace(t); |
| 71 | } |
| 72 | } |
| 73 | |
| 74 | void clonetrace(Uproc *new, int copy) |
| 75 | { |
| 76 | Tracebuf *t; |
| 77 | |
| 78 | if((t = current->trace) == nil){ |
| 79 | new->trace = nil; |
| 80 | return; |
| 81 | } |
| 82 | |
| 83 | if(copy){ |
| 84 | Tracebuf *x; |
| 85 | |
| 86 | x = kmalloc(sizeof(*t)); |
| 87 | memmove(x, t, sizeof(*t)); |
| 88 | new->trace = x; |
| 89 | |
| 90 | return; |
| 91 | } |
| 92 | |
| 93 | new->trace = alloctrace(); |
| 94 | } |
| 95 | |
| 96 | void tprint(char *fmt, ...) |
| 97 | { |
| 98 | va_list a; |
| 99 | Uproc *p; |
| 100 | |
| 101 | p = current; |
| 102 | if(p && p->trace){ |
| 103 | va_start(a, fmt); |
| 104 | vputtrace((Tracebuf*)p->trace, fmt, a); |
| 105 | va_end(a); |
| 106 | } |
| 107 | } |