raz / lib / Rt.raz

797 lines · 25.7 KiB · raw · history · last change e0d008cd

1(* The run time: ending the program, and what the compiler's code
2 calls, fail when a check fails; stop, for the library's own
3 failures; and the handlers that say where the program was when a
4 signal stops it.
5 The compiler finds fail, exit, cExit, places, profiler,
6 startProfile, teller, calls, placer and place by these names.
7 After a failed check or a signal, and on demand with trace, Rt says
8 the calls under way and their variables, from the frames' chain of
9 rbp and the compiler's tables in places. A program run with
10 RAZ_PROFILE set is sampled every millisecond of its time, and at its
11 end Rt says which procedures and places in the source took it: each
12 procedure's samples in its own code, and in all, with those in the
13 procedures it was calling. A program built with raz -s or
14 -noprofile has no profiler: the entry point leaves profiler nil,
15 nothing reaches startProfile, and the linker leaves it out with all
16 it uses. Built with -s it has no places either, and no teller or
17 placer: a failure is told by its address, and calls and place,
18 which would need the places, are left out the same way.
19 The handlers are Linux's on x86-64, set by system calls: what the
20 kernel hands them is laid out as it is there. A program built with
21 raz -bare, for the bare machine, runs no body of Rt, so has no
22 handlers and no profiler. *)
23module Rt;
24import Sys;
25import SYSTEM;
26
27const
28 Full*: ERROR = "too many procedures to run at exit"; (* atExit's *)
29 MaxAtExit = 32;
30 SigFpe = 8;
31 SigSegv = 11;
32 Low = 10000H; (* no address below this is ever mapped *)
33 Digits = "0123456789abcdef";
34 SigProf = 27;
35 (* SA_SIGINFO, SA_ONSTACK, SA_RESTORER and SA_RESTART, so that a
36 system call a sample interrupts goes on *)
37 ProfFlags = 4H + 8000000H + 4000000H + 10000000H;
38 MaxSamples = 100000;
39 MaxProcs = 8192;
40 MaxPlaces = 65536;
41 (* the line table's special opcodes, as the compiler makes them *)
42 LineBase = -5;
43 LineRange = 14;
44 OpcodeBase = 13;
45 Depth = 24; (* the callers noted with each sample, at most *)
46 (* SA_SIGINFO, SA_ONSTACK, SA_RESTORER and SA_RESETHAND *)
47 Flags = 4H + 8000000H + 4000000H + 80000000H;
48
49type
50 (* A row of the line table: the code from address at on comes from
51 line and column col of file, numbered from 1 *)
52 Row = record at: UINT; file, line, col: INT; end;
53 (* A procedure, from address start to stop, called name, and its
54 count variables from first on; it saves the registers of its
55 variables, bits of regs, a quadword each from saveAt in its frame *)
56 Proc = record start, stop, name, first, count, saves: U32; saveAt: I32; end;
57 (* A variable of a procedure, at off from its frame, shown by kind:
58 1 a signed integer, 2 an unsigned one, 3 a BOOL, 4 an address,
59 5 a real; plus its size times 16, and 256 if the frame holds its
60 address, or 512 times 1 + i if it is in register i of regs *)
61 Local = record name: U32; off: I32; kind: U32; end;
62 (* What rt_sigaction and sigaltstack take *)
63 Action = record
64 handler: proc(sig: INT; info, ctx: ^U8);
65 flags: U64;
66 restorer: proc;
67 mask: U64;
68 end;
69 Stack = record sp: ^U8; flags, size: INT; end;
70
71var
72 atExits: [MaxAtExit]proc;
73 numAtExit: INT;
74 ending: INT; (* the status exit was given, once it has been *)
75 cExit: proc(status: I32); (* C's exit, set first thing in a program that uses C *)
76 (* Set first thing too: where the line table is in them, where the
77 program's code starts and stops, the numbers of procedures and
78 variables; the procedures and variables, and their names; and
79 the line table, DWARF's line program, which gdb reads as
80 .debug_line. The linker makes them. *)
81 places: ^INT;
82 line: [256]U8; (* the message being made *)
83 (* rbx, r12, r13, r14 and r15 in the frame being told of, where the
84 compiler keeps a procedure's busiest variables; then rdi and rsi
85 where the program stopped, where a procedure that calls nothing
86 keeps the parameters that arrive in them *)
87 regs: [7]UINT;
88 lineLen: INT;
89 act: Action;
90 alt: Stack;
91 altStack: [16384]U8; (* where the handlers run, even when the stack is full *)
92 (* the profile: where the program was at each sample, and how many
93 samples fell in each procedure and at each place *)
94 samples: [MaxSamples]UINT;
95 (* the callers at each sample, by their return addresses: a row of
96 Depth for each, a short one ended by 0; mapped when profiling *)
97 chains: ^UINT;
98 numSamples: INT;
99 profiler: proc; (* startProfile, put here by the entry point, or nil *)
100 (* calls, put here by the entry point, or nil: a failure in a program
101 built with raz -s, which has no places, tells no calls *)
102 teller: proc(ip, bp: UINT; vars: BOOL);
103 (* place, put here by the entry point, or nil, as teller *)
104 placer: proc(a: UINT);
105 procCount: [MaxProcs]INT;
106 procTotal: [MaxProcs]INT; (* the samples each procedure was on the chain of *)
107 placeCount: [MaxPlaces]INT;
108 timerv: [4]INT; (* setitimer's interval and value *)
109
110(* Registers p to run when the program ends by exit. *)
111proc atExit*(p: proc): ERROR;
112begin
113 if numAtExit = MaxAtExit then return Full; end;
114 atExits[numAtExit] := p;
115 INC(numAtExit);
116 return nil;
117end;
118
119proc profile; forward;
120
121(* The status exit was given, while the procedures atExit registered
122 run; 0 before. A failed check and stop both end with 2. *)
123proc exitStatus*: INT;
124begin
125 return ending;
126end;
127
128(* Runs the procedures registered with atExit, the last first, then
129 ends the program with status: through C's exit in a program that
130 uses C, so that C flushes its buffers too. Each procedure is taken
131 off the list before it runs, so it runs once even if it fails or
132 calls exit itself. *)
133proc exit*(status: INT);
134var p: proc;
135begin
136 ending := status;
137 while numAtExit > 0 do
138 DEC(numAtExit);
139 p := atExits[numAtExit];
140 p();
141 end;
142 if cExit # nil then cExit(I32(status)); end;
143 Sys.exit(status);
144end;
145
146(* Stops the program: says msg, and then a line feed, on standard
147 error, then ends it by exit with status 2, as a failed check does. *)
148proc stop*(msg: []const U8);
149begin
150 _ := Sys.write(Sys.stderr, msg);
151 _ := Sys.write(Sys.stderr, "\n");
152 exit(2);
153end;
154
155(* Messages, made in line, one byte kept for the line feed, and
156 written by say in one piece *)
157proc put(s: []const U8);
158var i: INT;
159begin
160 for i := 0 to LEN(s) - 1 do
161 if lineLen < LEN(line) - 1 then
162 line[lineLen] := s[i];
163 INC(lineLen);
164 end;
165 end;
166end;
167
168(* The digits are made from the last, those of a negative n from its
169 negative remainders, so that the lowest INT comes out too. *)
170proc putInt(n: INT);
171var buf: [20]U8; i: INT; neg: BOOL;
172begin
173 neg := n < 0;
174 i := 20;
175 repeat
176 DEC(i);
177 if neg then buf[i] := U8(-(n mod 10)) + '0'; else buf[i] := U8(n mod 10) + '0'; end;
178 n := n div 10;
179 until n = 0;
180 if neg then put("-"); end;
181 put(buf[i..20]);
182end;
183
184proc putStr(s: ^U8);
185var n: INT;
186begin
187 n := 0;
188 while s[n] # 0 do INC(n); end;
189 put(s[0..n]);
190end;
191
192proc say;
193begin
194 line[lineLen] := '\n';
195 _ := Sys.write(Sys.stderr, line[0..lineLen + 1]);
196 lineLen := 0;
197end;
198
199(* The names, after the procedures and variables *)
200proc names: ^U8;
201begin
202 return ^U8(places + 5) + 28 * places[3] + 12 * places[4];
203end;
204
205(* The line table *)
206proc lines: ^U8;
207begin
208 return ^U8(places) + places[0];
209end;
210
211(* The number p points at, in LEB128, unsigned, and where the next
212 thing starts *)
213proc uleb(p: ^U8): (INT, ^U8);
214var n, shift: INT;
215begin
216 n := 0;
217 shift := 0;
218 while p^ >= 80H do
219 n := n | INT(p^ & 7FH) shl shift;
220 INC(shift, 7);
221 p := p + 1;
222 end;
223 return n | INT(p^) shl shift, p + 1;
224end;
225
226(* The same, signed *)
227proc sleb(p: ^U8): (INT, ^U8);
228var n, shift, b: INT;
229begin
230 n := 0;
231 shift := 0;
232 repeat
233 b := INT(p^);
234 p := p + 1;
235 n := n | (b & 7FH) shl shift;
236 INC(shift, 7);
237 until b < 80H;
238 if (shift < 64) and (b & 40H # 0) then n := n | (-1 shl shift); end; (* its sign *)
239 return n, p;
240end;
241
242(* The path of the line table's file f, as a C string: the files'
243 names follow the table's header of 29 bytes, each ending in a zero
244 and followed by three numbers *)
245proc path(f: INT): ^U8;
246var p: ^U8; i, k: INT;
247begin
248 p := lines() + 29;
249 for i := 2 to f do
250 while p^ # 0 do p := p + 1; end;
251 p := p + 1;
252 for k := 1 to 3 do _, p := uleb(p); end;
253 end;
254 return p;
255end;
256
257(* The row of the line table that the code at address a comes from,
258 the one with the highest address up to a, and its number; or, if
259 k >= 0, row number k. The number is -1 if there is none. The table
260 is run as DWARF says, each opcode changing the row being made; the
261 compiler uses only those below, a row made by copy or by a special
262 opcode, which adds to the address and the line at once. *)
263proc row(a: UINT; k: INT): (Row, INT);
264var p, stop: ^U8; q: ^U32; at: ^UINT; r, best: Row; n, found, op, v: INT;
265begin
266 p := lines();
267 q := ^U32(p);
268 stop := p + 4 + INT(q^);
269 q := ^U32(p + 6);
270 p := p + 10 + INT(q^); (* the program, past the header *)
271 r := {file: 1, line: 1};
272 n := 0;
273 found := -1;
274 while p < stop do
275 op := INT(p^);
276 p := p + 1;
277 if op >= OpcodeBase then
278 op := op - OpcodeBase;
279 r.at := r.at + UINT(op div LineRange);
280 r.line := r.line + LineBase + op mod LineRange;
281 op := 1;
282 elsif op = 0 then (* extended: its length, then which *)
283 v, p := uleb(p);
284 if p^ = 1 then r := {file: 1, line: 1}; (* end_sequence *)
285 elsif p^ = 2 then at := ^UINT(p + 1); r.at := at^; (* set_address *)
286 end;
287 p := p + v;
288 elsif op = 2 then v, p := uleb(p); r.at := r.at + UINT(v); (* advance_pc *)
289 elsif op = 3 then v, p := sleb(p); r.line := r.line + v; (* advance_line *)
290 elsif op = 4 then r.file, p := uleb(p); (* set_file *)
291 elsif op = 5 then r.col, p := uleb(p); (* set_column *)
292 end;
293 if op = 1 then (* copy, or a special opcode: the row r *)
294 if n = k then return r, n; end;
295 if (k < 0) and (r.at <= a) and ((found < 0) or (r.at >= best.at)) then
296 best := r;
297 found := n;
298 end;
299 INC(n);
300 end;
301 end;
302 return best, found;
303end;
304
305(* Puts where row r comes from, as file:line:col *)
306proc putRow(r: Row);
307begin
308 putStr(path(r.file));
309 put(":");
310 putInt(r.line);
311 put(":");
312 putInt(r.col);
313end;
314
315proc putHex(u: UINT);
316var buf: [16]U8; i: INT;
317begin
318 i := 16;
319 repeat
320 DEC(i);
321 buf[i] := Digits[INT(u & 15)];
322 u := u shr 4;
323 until u = 0;
324 put("0x");
325 put(buf[i..16]);
326end;
327
328(* The compiler's, as fail is: puts where the code at address a comes
329 from, as file:line:col: and a space, if a is in the program's code:
330 the row of the line table with the highest address up to a. *)
331proc place*(a: UINT);
332var r: Row; n: INT;
333begin
334 if (a < UINT(places[1])) or (a >= UINT(places[2])) then return; end;
335 r, n := row(a, -1);
336 if n < 0 then return; end;
337 putRow(r);
338 put(": ");
339end;
340
341(* Puts where the code at address a is: place, or, in a program built
342 with raz -s, which keeps no places, the address *)
343proc where(a: UINT);
344begin
345 if placer # nil then placer(a);
346 else
347 put("at ");
348 putHex(a);
349 put(": ");
350 end;
351end;
352
353(* The frame pointer of the procedure that calls it, which a code
354 procedure leaves as it is *)
355proc framePtr: UINT;
356code
357 mov rax, rbp;
358 ret;
359end framePtr;
360
361(* The frame of the procedure that called the one calling this *)
362proc callerFrame: UINT;
363var q: ^UINT;
364begin
365 q := ^UINT(framePtr()); (* callerFrame's own: its caller's frame is in it *)
366 q := ^UINT(q^);
367 return q^;
368end;
369
370(* The procedure whose code holds address a, or nil. A procedure's
371 start and stop are the low 32 bits of its addresses, which are all
372 the compiler keeps; the program's code lies in the low or the top
373 2 GB (raz -base), and in either the low 32 bits of a, which is in
374 the code, are in the same order as a itself. *)
375proc procAt(a: UINT): ^Proc;
376var p: ^Proc; i: INT;
377begin
378 if (places = nil) or (a < UINT(places[1])) or (a >= UINT(places[2])) then return nil; end;
379 p := ^Proc(places + 5);
380 a := a & 0FFFFFFFFH;
381 for i := 0 to places[3] - 1 do
382 if (UINT(p[i].start) <= a) and (a < UINT(p[i].stop)) then return p + i; end;
383 end;
384 return nil;
385end;
386
387(* x with six figures after the point, or as m e n beyond them *)
388proc putReal(x: F64);
389var e, i: INT; f: U64;
390begin
391 if x # x then put("nan"); return; end;
392 if x < 0.0 then put("-"); x := -x; end;
393 if (x > 1.0) and (x * 2.0 = x) then put("inf"); return; end;
394 e := 0;
395 while x >= 1.0E15 do x := x / 10.0; INC(e); end;
396 while (x # 0.0) and (x < 0.001) do x := x * 10.0; DEC(e); end;
397 f := U64(x * 1000000.0 + 0.5);
398 putInt(INT(f div 1000000));
399 put(".");
400 for i := 1 to 6 do
401 f := f mod 1000000 * 10;
402 put(Digits[INT(f div 1000000)..INT(f div 1000000) + 1]);
403 end;
404 if e # 0 then put("e"); putInt(e); end;
405end;
406
407(* The value of variable l of the frame at bp *)
408proc putValue(bp: UINT; l: ^Local);
409var a: ^U8; w: ^UINT; h: ^U16; s: ^U32; f: ^F32; d: ^F64; v: UINT; bits: INT;
410begin
411 a := ^U8(bp) + INT(l^.off);
412 if l^.kind shr 9 # 0 then a := ^U8(SYSTEM.ADR(regs[INT(l^.kind shr 9) - 1])); end;
413 w := ^UINT(a);
414 if l^.kind & 256 # 0 then a := ^U8(w^); w := ^UINT(a); end;
415 h := ^U16(a); s := ^U32(a); f := ^F32(a); d := ^F64(a);
416 bits := INT(l^.kind shr 4 & 15) * 8;
417 match bits of
418 | 8: v := UINT(a^);
419 | 16: v := UINT(h^);
420 | 32: v := UINT(s^);
421 | else: v := w^;
422 end;
423 match l^.kind & 15 of
424 | 1:
425 if (bits < 64) and (v shr (bits - 1) # 0) then putInt(INT(v) - INT(1) shl bits);
426 else putInt(INT(v));
427 end;
428 | 2: putInt(INT(v));
429 | 3: if v # 0 then put("true"); else put("false"); end;
430 | 4: if v = 0 then put("nil"); else putHex(v); end;
431 | else: if bits = 32 then putReal(F64(f^)); else putReal(d^); end;
432 end;
433end;
434
435(* Says that n more calls are as the one before, if there are any;
436 the lines it takes *)
437proc more(n: INT): INT;
438begin
439 if n = 0 then return 0; end;
440 put(" and ");
441 putInt(n);
442 put(" more the same");
443 say;
444 return 1;
445end;
446
447(* rbx, r12, r13, r14 and r15, into p[0] to p[4] *)
448proc liveRegs(p: ^UINT);
449code
450 mov [rdi], rbx;
451 mov [rdi + 8], r12;
452 mov [rdi + 16], r13;
453 mov [rdi + 24], r14;
454 mov [rdi + 32], r15;
455 ret;
456end liveRegs;
457
458(* An address in the code of the procedure that calls it *)
459proc here: UINT;
460code
461 mov rax, [rsp];
462 ret;
463end here;
464
465(* regs as the caller of p's frame at bp left them, where p saved them *)
466proc restore(p: ^Proc; bp: UINT);
467var i, j: INT; q: ^UINT;
468begin
469 if p = nil then return; end;
470 j := 0;
471 for i := 0 to 4 do
472 if p^.saves shr i & 1 # 0 then
473 q := ^UINT(^U8(bp) + INT(p^.saveAt) + 8 * j);
474 regs[i] := q^;
475 INC(j);
476 end;
477 end;
478end;
479
480(* Says the calls under way, a line each, from the one at address ip
481 whose frame is at bp: where each is, and its variables, unless vars
482 is false for the first. At most 20 lines; a frame that isn't the
483 program's ends them. Calls of one procedure from one place, as in a
484 recursion that overflowed the stack, are told once, and counted. *)
485proc calls(ip, bp: UINT; vars: BOOL);
486var p, last: ^Proc; l: ^Local; i, n, same: INT; q: ^UINT; lastIp, x, xip: UINT; saved: BOOL;
487begin
488 (* the registers as they are, then as each frame from this one out
489 to bp's found them *)
490 liveRegs(SYSTEM.ADR(regs[0]));
491 x := framePtr();
492 xip := here();
493 while (x # bp) and (x & 7 = 0) and (x # 0) do
494 restore(procAt(xip), x);
495 q := ^UINT(x);
496 if q[0] <= x then break; end;
497 xip := q[1] - 1;
498 x := q[0];
499 end;
500 saved := vars; (* not in a prologue: the frame has saved them *)
501 n := 0;
502 same := 0;
503 last := nil;
504 lastIp := 0;
505 while n < 20 do
506 p := procAt(ip);
507 if p = nil then break; end;
508 if (p = last) and (ip = lastIp) then
509 INC(same);
510 else
511 n := n + more(same);
512 same := 0;
513 last := p;
514 lastIp := ip;
515 put(" in ");
516 putStr(names() + INT(p^.name));
517 put(" at ");
518 where(ip);
519 l := ^Local(^U8(places + 5) + 28 * places[3]) + INT(p^.first);
520 if not vars or (p^.count = 0) then DEC(lineLen, 2); end; (* where's ": " *)
521 for i := 0 to INT(p^.count) - 1 do
522 if vars then
523 if i > 0 then put(", "); end;
524 putStr(names() + INT(l[i].name));
525 put(" = ");
526 putValue(bp, l + i);
527 end;
528 end;
529 say;
530 INC(n);
531 vars := true;
532 end;
533 if saved then restore(p, bp); end;
534 saved := true;
535 q := ^UINT(bp);
536 if (bp & 7 # 0) or (q[0] <= bp) then break; end;
537 ip := q[1] - 1; (* the call, by its return address *)
538 bp := q[0];
539 end;
540 _ := more(same);
541end;
542
543(* Says on standard error the calls under way, from the one that calls
544 it, each with its variables, as after a failed check. *)
545proc trace*;
546var q: ^UINT;
547begin
548 q := ^UINT(framePtr());
549 calls(q[1] - 1, q[0], true);
550end;
551
552(* A check failed in the code at address at: says where, and what
553 failed, on standard error, then ends the program by exit with
554 status 2. what is 0 for an index a and 1 for a slice a..b, of
555 something whose length is len; 2 for a, which is no position of
556 the enumeration called name; 3 for a slice a..b of a pointer, which
557 runs backwards; 7 for a view at index a that runs past the end of
558 something whose length is len. What a target's machine doesn't catch the code
559 tests for, and stops at with what 4, a nil pointer; 5, a division
560 by zero; 6, a stack overflow; these end the program by exit with
561 status 2 too, as the signal handler does. rdi and rsi are the
562 registers as the failing code had them. *)
563proc fail*(what, a, b, len: INT; at: UINT; name: ^U8; rdi, rsi: UINT);
564begin
565 regs[5] := rdi;
566 regs[6] := rsi;
567 where(at);
568 if (what >= 4) and (what <= 6) then
569 put("stopped by ");
570 if what = 4 then put("a nil pointer");
571 elsif what = 5 then put("a division fault");
572 else put("a stack overflow");
573 end;
574 say;
575 if teller # nil then teller(at, callerFrame(), true); end;
576 exit(2);
577 end;
578 if what = 0 then
579 put("index ");
580 putInt(a);
581 elsif what = 7 then
582 put("a view at index ");
583 putInt(a);
584 put(" runs past a length of ");
585 putInt(len);
586 elsif (what = 1) or (what = 3) then
587 put("slice ");
588 putInt(a);
589 put("..");
590 putInt(b);
591 if what = 3 then put(" runs backwards"); end;
592 else
593 putInt(a);
594 put(" isn't a position of ");
595 putStr(name);
596 end;
597 if what < 2 then
598 put(" is out of range for a length of ");
599 putInt(len);
600 end;
601 say;
602 if teller # nil then teller(at, callerFrame(), true); end;
603 exit(2);
604end;
605
606(* Returns from a signal handler: rt_sigreturn *)
607proc sigReturn;
608code
609 mov eax, 15;
610 syscall;
611end sigReturn;
612
613(* A signal stops the program: says where it was and why on standard
614 error, then ends the program by exit with status 2, as a failed
615 check does. info and ctx are the kernel's siginfo and ucontext. *)
616proc onSignal(sig: INT; info, ctx: ^U8);
617var adr, sp, ip, bp: UINT; q: ^UINT; why: []const U8;
618begin
619 q := ^UINT(ctx + 104); (* uc_mcontext's rdi, then rsi, then rbp *)
620 regs[5] := q[0];
621 regs[6] := q[1];
622 bp := q[2];
623 q := ^UINT(info + 16); (* si_addr *)
624 adr := q^;
625 q := ^UINT(ctx + 160); (* uc_mcontext's rsp, then rip *)
626 sp := q[0];
627 ip := q[1];
628 if sig = SigFpe then why := "a division fault";
629 elsif ip < Low then
630 why := "a nil procedure";
631 q := ^UINT(sp);
632 ip := q^ - 1; (* the call, by its return address *)
633 elsif adr < Low then why := "a nil pointer";
634 elsif adr - sp + 100000H < 200000H then why := "a stack overflow"; (* within a megabyte of rsp *)
635 else why := "a bad address";
636 end;
637 where(ip);
638 put("stopped by ");
639 put(why);
640 say;
641 (* the variables of a frame the stack overflowed in may be past it *)
642 if teller # nil then teller(ip, bp, why # "a stack overflow"); end;
643 exit(2);
644end;
645
646(* Whether a is in the program's own code, not C's *)
647proc inCode(a: UINT): BOOL;
648begin
649 return (a >= UINT(places[1])) and (a < UINT(places[2]));
650end;
651
652(* SIGPROF, every millisecond the program runs, in any of its threads:
653 notes where it was, and the calls under way, up the chain of frames.
654 The chain is followed only through the program's own code, whose
655 frames all keep it in rbp: C's code may use rbp for anything. *)
656proc onProf(_sig: INT; _info, ctx: ^U8);
657var n, k: INT; q, f, row: ^UINT; ip, bp: UINT;
658begin
659 n := XADD(numSamples, 1);
660 if n >= MaxSamples then return; end;
661 q := ^UINT(ctx + 120); (* uc_mcontext's rbp *)
662 bp := q^;
663 q := ^UINT(ctx + 168); (* uc_mcontext's rip *)
664 ip := q^;
665 samples[n] := ip;
666 row := chains + n * Depth;
667 k := 0;
668 if (places # nil) and inCode(ip) then
669 while (k < Depth) and (bp # 0) and (bp & 7 = 0) do
670 f := ^UINT(bp);
671 if not inCode(f[1]) then break; end;
672 row[k] := f[1] - 1; (* the call, by its return address *)
673 INC(k);
674 if f[0] <= bp then break; end;
675 bp := f[0];
676 end;
677 end;
678 if k < Depth then row[k] := 0; end;
679end;
680
681(* The number of the procedure the code at address a is in, or -1 *)
682proc procNum(a: UINT): INT;
683var p: ^Proc;
684begin
685 p := procAt(a);
686 if p = nil then return -1; end;
687 return p - ^Proc(places + 5);
688end;
689
690(* The number of the line table's row the code at address a comes
691 from, or -1 *)
692proc placeAt(a: UINT): INT;
693var n: INT;
694begin
695 _, n := row(a, -1);
696 return n;
697end;
698
699(* Puts the share of n that k is, as a percentage four wide *)
700proc putShare(k, n: INT);
701var i: INT;
702begin
703 i := k * 100 div n;
704 if i < 10 then put(" "); elsif i < 100 then put(" "); else put(" "); end;
705 putInt(i);
706 put("%");
707end;
708
709(* Says the ten that took most of count's n samples, by name, with
710 their totals beside them if total isn't empty *)
711proc top(count: []INT; total: []const INT; n: INT; byPlace: BOOL);
712var i, k, best: INT; p: ^Proc; r: Row;
713begin
714 p := ^Proc(places + 5);
715 for k := 1 to 10 do
716 best := 0;
717 for i := 1 to LEN(count) - 1 do
718 if count[i] > count[best] then best := i; end;
719 end;
720 if count[best] = 0 then return; end;
721 putShare(count[best], n);
722 if LEN(total) > 0 then put(" "); putShare(total[best], n); end;
723 put(" ");
724 if byPlace then
725 r, _ := row(0, best);
726 putRow(r);
727 else putStr(names() + INT(p[best].name));
728 end;
729 say;
730 count[best] := 0;
731 end;
732end;
733
734(* The compiler's, as fail is: if RAZ_PROFILE is set, samples the
735 program every millisecond of its time, and says at its end what took
736 it (profile) *)
737proc startProfile*;
738begin
739 if LEN(Sys.env("RAZ_PROFILE")) = 0 then return; end;
740 chains := ^UINT(Sys.mmap(MaxSamples * Depth * SIZE(UINT)));
741 if chains = nil then return; end;
742 act := {handler: onProf, flags: ProfFlags, restorer: sigReturn};
743 _ := SYSTEM.SYSCALL(13, SigProf, SYSTEM.ADR(act), 0, 8);
744 timerv := [0, 1000, 0, 1000]; (* every millisecond, from one on *)
745 _ := SYSTEM.SYSCALL(38, 2, SYSTEM.ADR(timerv), 0); (* setitimer(ITIMER_PROF) *)
746 _ := atExit(profile);
747end;
748
749(* At the end of a profiled run: which procedures, and which places in
750 the source, took the time, as shares of the samples *)
751proc profile;
752var t: [4]INT; i, n, k, j, m, s: INT; seen: [Depth + 1]INT; row: ^UINT;
753begin
754 t := [0, 0, 0, 0];
755 _ := SYSTEM.SYSCALL(38, 2, SYSTEM.ADR(t), 0); (* setitimer(ITIMER_PROF): no more *)
756 n := numSamples;
757 if n > MaxSamples then n := MaxSamples; end;
758 if (places = nil) or (n = 0) then return; end;
759 for i := 0 to n - 1 do
760 k := procNum(samples[i]);
761 if (k >= 0) and (k < MaxProcs) then INC(procCount[k]); end;
762 (* each procedure on the sample's chain counts once in its
763 total, however often it is there *)
764 row := chains + i * Depth;
765 m := 0;
766 for j := -1 to Depth - 1 do
767 if j < 0 then k := procNum(samples[i]);
768 elsif row[j] = 0 then break;
769 else k := procNum(row[j]);
770 end;
771 if (k >= 0) and (k < MaxProcs) then
772 s := 0;
773 while (s < m) and (seen[s] # k) do INC(s); end;
774 if s = m then seen[m] := k; INC(m); INC(procTotal[k]); end;
775 end;
776 end;
777 k := placeAt(samples[i]);
778 if (k >= 0) and (k < MaxPlaces) then INC(placeCount[k]); end;
779 end;
780 put("profile: ");
781 putInt(n);
782 put(" samples of a millisecond; each procedure's own, then with its calls'");
783 say;
784 top(procCount[0..places[3]], procTotal[0..places[3]], n, false);
785 put("by place:");
786 say;
787 top(placeCount, placeCount[0..0], n, true);
788end;
789
790begin
791 alt := {sp: SYSTEM.ADR(altStack[0]), size: LEN(altStack)};
792 _ := SYSTEM.SYSCALL(131, SYSTEM.ADR(alt), 0); (* sigaltstack *)
793 act := {handler: onSignal, flags: Flags, restorer: sigReturn};
794 _ := SYSTEM.SYSCALL(13, SigSegv, SYSTEM.ADR(act), 0, 8); (* rt_sigaction *)
795 _ := SYSTEM.SYSCALL(13, SigFpe, SYSTEM.ADR(act), 0, 8);
796 if profiler # nil then profiler(); end;
797end Rt.