raz / lib / Rt.darwin-arm64.raz

809 lines · 27.2 KiB · raw · history · last change 89524972

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