(* The run time: ending the program, and what the compiler's code calls, fail when a check fails; stop, for the library's own failures; and the handlers that say where the program was when a signal stops it. The compiler finds fail, exit, cExit, places, profiler, startProfile, teller, calls, placer and place by these names. After a failed check or a signal, and on demand with trace, Rt says the calls under way and their variables, from the frames' chain of rbp and the compiler's tables in places. A program run with RAZ_PROFILE set is sampled every millisecond of its time, and at its end Rt says which procedures and places in the source took it: each procedure's samples in its own code, and in all, with those in the procedures it was calling. A program built with raz -s or -noprofile has no profiler: the entry point leaves profiler nil, nothing reaches startProfile, and the linker leaves it out with all it uses. Built with -s it has no places either, and no teller or placer: a failure is told by its address, and calls and place, which would need the places, are left out the same way. The handlers are Linux's on x86-64, set by system calls: what the kernel hands them is laid out as it is there. A program built with raz -bare, for the bare machine, runs no body of Rt, so has no handlers and no profiler. *) module Rt; import Sys; import SYSTEM; const Full*: ERROR = "too many procedures to run at exit"; (* atExit's *) MaxAtExit = 32; SigFpe = 8; SigSegv = 11; Low = 10000H; (* no address below this is ever mapped *) Digits = "0123456789abcdef"; SigProf = 27; (* SA_SIGINFO, SA_ONSTACK, SA_RESTORER and SA_RESTART, so that a system call a sample interrupts goes on *) ProfFlags = 4H + 8000000H + 4000000H + 10000000H; MaxSamples = 100000; MaxProcs = 8192; MaxPlaces = 65536; (* the line table's special opcodes, as the compiler makes them *) LineBase = -5; LineRange = 14; OpcodeBase = 13; Depth = 24; (* the callers noted with each sample, at most *) (* SA_SIGINFO, SA_ONSTACK, SA_RESTORER and SA_RESETHAND *) Flags = 4H + 8000000H + 4000000H + 80000000H; type (* A row of the line table: the code from address at on comes from line and column col of file, numbered from 1 *) Row = record at: UINT; file, line, col: INT; end; (* A procedure, from address start to stop, called name, and its count variables from first on; it saves the registers of its variables, bits of regs, a quadword each from saveAt in its frame *) Proc = record start, stop, name, first, count, saves: U32; saveAt: I32; end; (* A variable of a procedure, at off from its frame, shown by kind: 1 a signed integer, 2 an unsigned one, 3 a BOOL, 4 an address, 5 a real; plus its size times 16, and 256 if the frame holds its address, or 512 times 1 + i if it is in register i of regs *) Local = record name: U32; off: I32; kind: U32; end; (* What rt_sigaction and sigaltstack take *) Action = record handler: proc(sig: INT; info, ctx: ^U8); flags: U64; restorer: proc; mask: U64; end; Stack = record sp: ^U8; flags, size: INT; end; var atExits: [MaxAtExit]proc; numAtExit: INT; ending: INT; (* the status exit was given, once it has been *) cExit: proc(status: I32); (* C's exit, set first thing in a program that uses C *) (* Set first thing too: where the line table is in them, where the program's code starts and stops, the numbers of procedures and variables; the procedures and variables, and their names; and the line table, DWARF's line program, which gdb reads as .debug_line. The linker makes them. *) places: ^INT; line: [256]U8; (* the message being made *) (* rbx, r12, r13, r14 and r15 in the frame being told of, where the compiler keeps a procedure's busiest variables; then rdi and rsi where the program stopped, where a procedure that calls nothing keeps the parameters that arrive in them *) regs: [7]UINT; lineLen: INT; act: Action; alt: Stack; altStack: [16384]U8; (* where the handlers run, even when the stack is full *) (* the profile: where the program was at each sample, and how many samples fell in each procedure and at each place *) samples: [MaxSamples]UINT; (* the callers at each sample, by their return addresses: a row of Depth for each, a short one ended by 0; mapped when profiling *) chains: ^UINT; numSamples: INT; profiler: proc; (* startProfile, put here by the entry point, or nil *) (* calls, put here by the entry point, or nil: a failure in a program built with raz -s, which has no places, tells no calls *) teller: proc(ip, bp: UINT; vars: BOOL); (* place, put here by the entry point, or nil, as teller *) placer: proc(a: UINT); procCount: [MaxProcs]INT; procTotal: [MaxProcs]INT; (* the samples each procedure was on the chain of *) placeCount: [MaxPlaces]INT; timerv: [4]INT; (* setitimer's interval and value *) (* Registers p to run when the program ends by exit. *) proc atExit*(p: proc): ERROR; begin if numAtExit = MaxAtExit then return Full; end; atExits[numAtExit] := p; INC(numAtExit); return nil; end; proc profile; forward; (* The status exit was given, while the procedures atExit registered run; 0 before. A failed check and stop both end with 2. *) proc exitStatus*: INT; begin return ending; end; (* Runs the procedures registered with atExit, the last first, then ends the program with status: through C's exit in a program that uses C, so that C flushes its buffers too. Each procedure is taken off the list before it runs, so it runs once even if it fails or calls exit itself. *) proc exit*(status: INT); var p: proc; begin ending := status; while numAtExit > 0 do DEC(numAtExit); p := atExits[numAtExit]; p(); end; if cExit # nil then cExit(I32(status)); end; Sys.exit(status); end; (* Stops the program: says msg, and then a line feed, on standard error, then ends it by exit with status 2, as a failed check does. *) proc stop*(msg: []const U8); begin _ := Sys.write(Sys.stderr, msg); _ := Sys.write(Sys.stderr, "\n"); exit(2); end; (* Messages, made in line, one byte kept for the line feed, and written by say in one piece *) proc put(s: []const U8); var i: INT; begin for i := 0 to LEN(s) - 1 do if lineLen < LEN(line) - 1 then line[lineLen] := s[i]; INC(lineLen); end; end; end; (* The digits are made from the last, those of a negative n from its negative remainders, so that the lowest INT comes out too. *) proc putInt(n: INT); var buf: [20]U8; i: INT; neg: BOOL; begin neg := n < 0; i := 20; repeat DEC(i); if neg then buf[i] := U8(-(n mod 10)) + '0'; else buf[i] := U8(n mod 10) + '0'; end; n := n div 10; until n = 0; if neg then put("-"); end; put(buf[i..20]); end; proc putStr(s: ^U8); var n: INT; begin n := 0; while s[n] # 0 do INC(n); end; put(s[0..n]); end; proc say; begin line[lineLen] := '\n'; _ := Sys.write(Sys.stderr, line[0..lineLen + 1]); lineLen := 0; end; (* The names, after the procedures and variables *) proc names: ^U8; begin return ^U8(places + 5) + 28 * places[3] + 12 * places[4]; end; (* The line table *) proc lines: ^U8; begin return ^U8(places) + places[0]; end; (* The number p points at, in LEB128, unsigned, and where the next thing starts *) proc uleb(p: ^U8): (INT, ^U8); var n, shift: INT; begin n := 0; shift := 0; while p^ >= 80H do n := n | INT(p^ & 7FH) shl shift; INC(shift, 7); p := p + 1; end; return n | INT(p^) shl shift, p + 1; end; (* The same, signed *) proc sleb(p: ^U8): (INT, ^U8); var n, shift, b: INT; begin n := 0; shift := 0; repeat b := INT(p^); p := p + 1; n := n | (b & 7FH) shl shift; INC(shift, 7); until b < 80H; if (shift < 64) and (b & 40H # 0) then n := n | (-1 shl shift); end; (* its sign *) return n, p; end; (* The path of the line table's file f, as a C string: the files' names follow the table's header of 29 bytes, each ending in a zero and followed by three numbers *) proc path(f: INT): ^U8; var p: ^U8; i, k: INT; begin p := lines() + 29; for i := 2 to f do while p^ # 0 do p := p + 1; end; p := p + 1; for k := 1 to 3 do _, p := uleb(p); end; end; return p; end; (* The row of the line table that the code at address a comes from, the one with the highest address up to a, and its number; or, if k >= 0, row number k. The number is -1 if there is none. The table is run as DWARF says, each opcode changing the row being made; the compiler uses only those below, a row made by copy or by a special opcode, which adds to the address and the line at once. *) proc row(a: UINT; k: INT): (Row, INT); var p, stop: ^U8; q: ^U32; at: ^UINT; r, best: Row; n, found, op, v: INT; begin p := lines(); q := ^U32(p); stop := p + 4 + INT(q^); q := ^U32(p + 6); p := p + 10 + INT(q^); (* the program, past the header *) r := {file: 1, line: 1}; n := 0; found := -1; while p < stop do op := INT(p^); p := p + 1; if op >= OpcodeBase then op := op - OpcodeBase; r.at := r.at + UINT(op div LineRange); r.line := r.line + LineBase + op mod LineRange; op := 1; elsif op = 0 then (* extended: its length, then which *) v, p := uleb(p); if p^ = 1 then r := {file: 1, line: 1}; (* end_sequence *) elsif p^ = 2 then at := ^UINT(p + 1); r.at := at^; (* set_address *) end; p := p + v; elsif op = 2 then v, p := uleb(p); r.at := r.at + UINT(v); (* advance_pc *) elsif op = 3 then v, p := sleb(p); r.line := r.line + v; (* advance_line *) elsif op = 4 then r.file, p := uleb(p); (* set_file *) elsif op = 5 then r.col, p := uleb(p); (* set_column *) end; if op = 1 then (* copy, or a special opcode: the row r *) if n = k then return r, n; end; if (k < 0) and (r.at <= a) and ((found < 0) or (r.at >= best.at)) then best := r; found := n; end; INC(n); end; end; return best, found; end; (* Puts where row r comes from, as file:line:col *) proc putRow(r: Row); begin putStr(path(r.file)); put(":"); putInt(r.line); put(":"); putInt(r.col); end; proc putHex(u: UINT); var buf: [16]U8; i: INT; begin i := 16; repeat DEC(i); buf[i] := Digits[INT(u & 15)]; u := u shr 4; until u = 0; put("0x"); put(buf[i..16]); end; (* The compiler's, as fail is: puts where the code at address a comes from, as file:line:col: and a space, if a is in the program's code: the row of the line table with the highest address up to a. *) proc place*(a: UINT); var r: Row; n: INT; begin if (a < UINT(places[1])) or (a >= UINT(places[2])) then return; end; r, n := row(a, -1); if n < 0 then return; end; putRow(r); put(": "); end; (* Puts where the code at address a is: place, or, in a program built with raz -s, which keeps no places, the address *) proc where(a: UINT); begin if placer # nil then placer(a); else put("at "); putHex(a); put(": "); end; end; (* The frame pointer of the procedure that calls it, which a code procedure leaves as it is *) proc framePtr: UINT; code mov rax, rbp; ret; end framePtr; (* The frame of the procedure that called the one calling this *) proc callerFrame: UINT; var q: ^UINT; begin q := ^UINT(framePtr()); (* callerFrame's own: its caller's frame is in it *) q := ^UINT(q^); return q^; end; (* The procedure whose code holds address a, or nil. A procedure's start and stop are the low 32 bits of its addresses, which are all the compiler keeps; the program's code lies in the low or the top 2 GB (raz -base), and in either the low 32 bits of a, which is in the code, are in the same order as a itself. *) proc procAt(a: UINT): ^Proc; var p: ^Proc; i: INT; begin if (places = nil) or (a < UINT(places[1])) or (a >= UINT(places[2])) then return nil; end; p := ^Proc(places + 5); a := a & 0FFFFFFFFH; for i := 0 to places[3] - 1 do if (UINT(p[i].start) <= a) and (a < UINT(p[i].stop)) then return p + i; end; end; return nil; end; (* x with six figures after the point, or as m e n beyond them *) proc putReal(x: F64); var e, i: INT; f: U64; begin if x # x then put("nan"); return; end; if x < 0.0 then put("-"); x := -x; end; if (x > 1.0) and (x * 2.0 = x) then put("inf"); return; end; e := 0; while x >= 1.0E15 do x := x / 10.0; INC(e); end; while (x # 0.0) and (x < 0.001) do x := x * 10.0; DEC(e); end; f := U64(x * 1000000.0 + 0.5); putInt(INT(f div 1000000)); put("."); for i := 1 to 6 do f := f mod 1000000 * 10; put(Digits[INT(f div 1000000)..INT(f div 1000000) + 1]); end; if e # 0 then put("e"); putInt(e); end; end; (* The value of variable l of the frame at bp *) proc putValue(bp: UINT; l: ^Local); var a: ^U8; w: ^UINT; h: ^U16; s: ^U32; f: ^F32; d: ^F64; v: UINT; bits: INT; begin a := ^U8(bp) + INT(l^.off); if l^.kind shr 9 # 0 then a := ^U8(SYSTEM.ADR(regs[INT(l^.kind shr 9) - 1])); end; w := ^UINT(a); if l^.kind & 256 # 0 then a := ^U8(w^); w := ^UINT(a); end; h := ^U16(a); s := ^U32(a); f := ^F32(a); d := ^F64(a); bits := INT(l^.kind shr 4 & 15) * 8; match bits of | 8: v := UINT(a^); | 16: v := UINT(h^); | 32: v := UINT(s^); | else: v := w^; end; match l^.kind & 15 of | 1: if (bits < 64) and (v shr (bits - 1) # 0) then putInt(INT(v) - INT(1) shl bits); else putInt(INT(v)); end; | 2: putInt(INT(v)); | 3: if v # 0 then put("true"); else put("false"); end; | 4: if v = 0 then put("nil"); else putHex(v); end; | else: if bits = 32 then putReal(F64(f^)); else putReal(d^); end; end; end; (* Says that n more calls are as the one before, if there are any; the lines it takes *) proc more(n: INT): INT; begin if n = 0 then return 0; end; put(" and "); putInt(n); put(" more the same"); say; return 1; end; (* rbx, r12, r13, r14 and r15, into p[0] to p[4] *) proc liveRegs(p: ^UINT); code mov [rdi], rbx; mov [rdi + 8], r12; mov [rdi + 16], r13; mov [rdi + 24], r14; mov [rdi + 32], r15; ret; end liveRegs; (* An address in the code of the procedure that calls it *) proc here: UINT; code mov rax, [rsp]; ret; end here; (* regs as the caller of p's frame at bp left them, where p saved them *) proc restore(p: ^Proc; bp: UINT); var i, j: INT; q: ^UINT; begin if p = nil then return; end; j := 0; for i := 0 to 4 do if p^.saves shr i & 1 # 0 then q := ^UINT(^U8(bp) + INT(p^.saveAt) + 8 * j); regs[i] := q^; INC(j); end; end; end; (* Says the calls under way, a line each, from the one at address ip whose frame is at bp: where each is, and its variables, unless vars is false for the first. At most 20 lines; a frame that isn't the program's ends them. Calls of one procedure from one place, as in a recursion that overflowed the stack, are told once, and counted. *) proc calls(ip, bp: UINT; vars: BOOL); var p, last: ^Proc; l: ^Local; i, n, same: INT; q: ^UINT; lastIp, x, xip: UINT; saved: BOOL; begin (* the registers as they are, then as each frame from this one out to bp's found them *) liveRegs(SYSTEM.ADR(regs[0])); x := framePtr(); xip := here(); while (x # bp) and (x & 7 = 0) and (x # 0) do restore(procAt(xip), x); q := ^UINT(x); if q[0] <= x then break; end; xip := q[1] - 1; x := q[0]; end; saved := vars; (* not in a prologue: the frame has saved them *) n := 0; same := 0; last := nil; lastIp := 0; while n < 20 do p := procAt(ip); if p = nil then break; end; if (p = last) and (ip = lastIp) then INC(same); else n := n + more(same); same := 0; last := p; lastIp := ip; put(" in "); putStr(names() + INT(p^.name)); put(" at "); where(ip); l := ^Local(^U8(places + 5) + 28 * places[3]) + INT(p^.first); if not vars or (p^.count = 0) then DEC(lineLen, 2); end; (* where's ": " *) for i := 0 to INT(p^.count) - 1 do if vars then if i > 0 then put(", "); end; putStr(names() + INT(l[i].name)); put(" = "); putValue(bp, l + i); end; end; say; INC(n); vars := true; end; if saved then restore(p, bp); end; saved := true; q := ^UINT(bp); if (bp & 7 # 0) or (q[0] <= bp) then break; end; ip := q[1] - 1; (* the call, by its return address *) bp := q[0]; end; _ := more(same); end; (* Says on standard error the calls under way, from the one that calls it, each with its variables, as after a failed check. *) proc trace*; var q: ^UINT; begin q := ^UINT(framePtr()); calls(q[1] - 1, q[0], true); end; (* A check failed in the code at address at: says where, and what failed, on standard error, then ends the program by exit with status 2. what is 0 for an index a and 1 for a slice a..b, of something whose length is len; 2 for a, which is no position of the enumeration called name; 3 for a slice a..b of a pointer, which runs backwards; 7 for a view at index a that runs past the end of something whose length is len. What a target's machine doesn't catch the code tests for, and stops at with what 4, a nil pointer; 5, a division by zero; 6, a stack overflow; these end the program by exit with status 2 too, as the signal handler does. rdi and rsi are the registers as the failing code had them. *) proc fail*(what, a, b, len: INT; at: UINT; name: ^U8; rdi, rsi: UINT); begin regs[5] := rdi; regs[6] := rsi; where(at); if (what >= 4) and (what <= 6) then put("stopped by "); if what = 4 then put("a nil pointer"); elsif what = 5 then put("a division fault"); else put("a stack overflow"); end; say; if teller # nil then teller(at, callerFrame(), true); end; exit(2); end; if what = 0 then put("index "); putInt(a); elsif what = 7 then put("a view at index "); putInt(a); put(" runs past a length of "); putInt(len); elsif (what = 1) or (what = 3) then put("slice "); putInt(a); put(".."); putInt(b); if what = 3 then put(" runs backwards"); end; else putInt(a); put(" isn't a position of "); putStr(name); end; if what < 2 then put(" is out of range for a length of "); putInt(len); end; say; if teller # nil then teller(at, callerFrame(), true); end; exit(2); end; (* Returns from a signal handler: rt_sigreturn *) proc sigReturn; code mov eax, 15; syscall; end sigReturn; (* A signal stops the program: says where it was and why on standard error, then ends the program by exit with status 2, as a failed check does. info and ctx are the kernel's siginfo and ucontext. *) proc onSignal(sig: INT; info, ctx: ^U8); var adr, sp, ip, bp: UINT; q: ^UINT; why: []const U8; begin q := ^UINT(ctx + 104); (* uc_mcontext's rdi, then rsi, then rbp *) regs[5] := q[0]; regs[6] := q[1]; bp := q[2]; q := ^UINT(info + 16); (* si_addr *) adr := q^; q := ^UINT(ctx + 160); (* uc_mcontext's rsp, then rip *) sp := q[0]; ip := q[1]; if sig = SigFpe then why := "a division fault"; elsif ip < Low then why := "a nil procedure"; q := ^UINT(sp); ip := q^ - 1; (* the call, by its return address *) elsif adr < Low then why := "a nil pointer"; elsif adr - sp + 100000H < 200000H then why := "a stack overflow"; (* within a megabyte of rsp *) else why := "a bad address"; end; where(ip); put("stopped by "); put(why); say; (* the variables of a frame the stack overflowed in may be past it *) if teller # nil then teller(ip, bp, why # "a stack overflow"); end; exit(2); end; (* Whether a is in the program's own code, not C's *) proc inCode(a: UINT): BOOL; begin return (a >= UINT(places[1])) and (a < UINT(places[2])); end; (* SIGPROF, every millisecond the program runs, in any of its threads: notes where it was, and the calls under way, up the chain of frames. The chain is followed only through the program's own code, whose frames all keep it in rbp: C's code may use rbp for anything. *) proc onProf(_sig: INT; _info, ctx: ^U8); var n, k: INT; q, f, row: ^UINT; ip, bp: UINT; begin n := XADD(numSamples, 1); if n >= MaxSamples then return; end; q := ^UINT(ctx + 120); (* uc_mcontext's rbp *) bp := q^; q := ^UINT(ctx + 168); (* uc_mcontext's rip *) ip := q^; samples[n] := ip; row := chains + n * Depth; k := 0; if (places # nil) and inCode(ip) then while (k < Depth) and (bp # 0) and (bp & 7 = 0) do f := ^UINT(bp); if not inCode(f[1]) then break; end; row[k] := f[1] - 1; (* the call, by its return address *) INC(k); if f[0] <= bp then break; end; bp := f[0]; end; end; if k < Depth then row[k] := 0; end; end; (* The number of the procedure the code at address a is in, or -1 *) proc procNum(a: UINT): INT; var p: ^Proc; begin p := procAt(a); if p = nil then return -1; end; return p - ^Proc(places + 5); end; (* The number of the line table's row the code at address a comes from, or -1 *) proc placeAt(a: UINT): INT; var n: INT; begin _, n := row(a, -1); return n; end; (* Puts the share of n that k is, as a percentage four wide *) proc putShare(k, n: INT); var i: INT; begin i := k * 100 div n; if i < 10 then put(" "); elsif i < 100 then put(" "); else put(" "); end; putInt(i); put("%"); end; (* Says the ten that took most of count's n samples, by name, with their totals beside them if total isn't empty *) proc top(count: []INT; total: []const INT; n: INT; byPlace: BOOL); var i, k, best: INT; p: ^Proc; r: Row; begin p := ^Proc(places + 5); for k := 1 to 10 do best := 0; for i := 1 to LEN(count) - 1 do if count[i] > count[best] then best := i; end; end; if count[best] = 0 then return; end; putShare(count[best], n); if LEN(total) > 0 then put(" "); putShare(total[best], n); end; put(" "); if byPlace then r, _ := row(0, best); putRow(r); else putStr(names() + INT(p[best].name)); end; say; count[best] := 0; end; end; (* The compiler's, as fail is: if RAZ_PROFILE is set, samples the program every millisecond of its time, and says at its end what took it (profile) *) proc startProfile*; begin if LEN(Sys.env("RAZ_PROFILE")) = 0 then return; end; chains := ^UINT(Sys.mmap(MaxSamples * Depth * SIZE(UINT))); if chains = nil then return; end; act := {handler: onProf, flags: ProfFlags, restorer: sigReturn}; _ := SYSTEM.SYSCALL(13, SigProf, SYSTEM.ADR(act), 0, 8); timerv := [0, 1000, 0, 1000]; (* every millisecond, from one on *) _ := SYSTEM.SYSCALL(38, 2, SYSTEM.ADR(timerv), 0); (* setitimer(ITIMER_PROF) *) _ := atExit(profile); end; (* At the end of a profiled run: which procedures, and which places in the source, took the time, as shares of the samples *) proc profile; var t: [4]INT; i, n, k, j, m, s: INT; seen: [Depth + 1]INT; row: ^UINT; begin t := [0, 0, 0, 0]; _ := SYSTEM.SYSCALL(38, 2, SYSTEM.ADR(t), 0); (* setitimer(ITIMER_PROF): no more *) n := numSamples; if n > MaxSamples then n := MaxSamples; end; if (places = nil) or (n = 0) then return; end; for i := 0 to n - 1 do k := procNum(samples[i]); if (k >= 0) and (k < MaxProcs) then INC(procCount[k]); end; (* each procedure on the sample's chain counts once in its total, however often it is there *) row := chains + i * Depth; m := 0; for j := -1 to Depth - 1 do if j < 0 then k := procNum(samples[i]); elsif row[j] = 0 then break; else k := procNum(row[j]); end; if (k >= 0) and (k < MaxProcs) then s := 0; while (s < m) and (seen[s] # k) do INC(s); end; if s = m then seen[m] := k; INC(m); INC(procTotal[k]); end; end; end; k := placeAt(samples[i]); if (k >= 0) and (k < MaxPlaces) then INC(placeCount[k]); end; end; put("profile: "); putInt(n); put(" samples of a millisecond; each procedure's own, then with its calls'"); say; top(procCount[0..places[3]], procTotal[0..places[3]], n, false); put("by place:"); say; top(placeCount, placeCount[0..0], n, true); end; begin alt := {sp: SYSTEM.ADR(altStack[0]), size: LEN(altStack)}; _ := SYSTEM.SYSCALL(131, SYSTEM.ADR(alt), 0); (* sigaltstack *) act := {handler: onSignal, flags: Flags, restorer: sigReturn}; _ := SYSTEM.SYSCALL(13, SigSegv, SYSTEM.ADR(act), 0, 8); (* rt_sigaction *) _ := SYSTEM.SYSCALL(13, SigFpe, SYSTEM.ADR(act), 0, 8); if profiler # nil then profiler(); end; end Rt.