@typesol/cli 0.50.0 → 0.51.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/CHANGELOG.md +144 -0
  2. package/README.md +12 -10
  3. package/SECURITY.md +5 -3
  4. package/dist/cli.js +36 -5
  5. package/dist/compiler/analyze.d.ts +8 -1
  6. package/dist/compiler/analyze.js +227 -19
  7. package/dist/compiler/diagnostics.d.ts +4 -0
  8. package/dist/compiler/diagnostics.js +5 -1
  9. package/dist/compiler/emit/base.d.ts +31 -1
  10. package/dist/compiler/emit/base.js +37 -1
  11. package/dist/compiler/emit/calls.js +27 -6
  12. package/dist/compiler/emit/cpi-core.d.ts +3 -0
  13. package/dist/compiler/emit/cpi-core.js +8 -2
  14. package/dist/compiler/emit/cpi.js +4 -2
  15. package/dist/compiler/emit/create.js +9 -9
  16. package/dist/compiler/emit/expressions.d.ts +8 -1
  17. package/dist/compiler/emit/expressions.js +65 -0
  18. package/dist/compiler/emit/function.d.ts +2 -0
  19. package/dist/compiler/emit/function.js +59 -7
  20. package/dist/compiler/emit/outline.d.ts +35 -0
  21. package/dist/compiler/emit/outline.js +547 -0
  22. package/dist/compiler/emit/program.js +11 -2
  23. package/dist/compiler/emit/shared.d.ts +57 -2
  24. package/dist/compiler/emit/shared.js +18 -3
  25. package/dist/compiler/emit/statements.d.ts +28 -1
  26. package/dist/compiler/emit/statements.js +279 -24
  27. package/dist/compiler/emit/storage.d.ts +16 -0
  28. package/dist/compiler/emit/storage.js +122 -3
  29. package/dist/compiler/hints.d.ts +1 -1
  30. package/dist/compiler/hints.js +9 -1
  31. package/dist/compiler/idl.js +1 -1
  32. package/dist/compiler/index.d.ts +15 -1
  33. package/dist/compiler/index.js +47 -10
  34. package/dist/compiler/model.d.ts +13 -1
  35. package/dist/compiler/stack.d.ts +71 -0
  36. package/dist/compiler/stack.js +309 -0
  37. package/dist/compiler/toolchain.d.ts +87 -5
  38. package/dist/compiler/toolchain.js +384 -19
  39. package/dist/workspace.d.ts +1 -0
  40. package/dist/workspace.js +1 -1
  41. package/docker/deps/0.51.0.lock.json +1206 -0
  42. package/docs/architecture.md +1 -1
  43. package/docs/audit.md +13 -11
  44. package/docs/case-study-escrow.md +1 -1
  45. package/docs/cli.md +2 -2
  46. package/docs/glossary.md +2 -1
  47. package/docs/language-basics.md +25 -1
  48. package/docs/language-pdas.md +6 -2
  49. package/docs/language-statements.md +101 -11
  50. package/docs/language-types.md +80 -5
  51. package/docs/runtime.md +1 -1
  52. package/docs/security-model.md +5 -3
  53. package/docs/stability.md +5 -1
  54. package/docs/troubleshooting.md +45 -1
  55. package/llms-full.txt +271 -27
  56. package/package.json +1 -1
  57. package/releases/0.50.0.json +874 -0
  58. package/runtime/typesol_rt.h +125 -51
@@ -1,5 +1,5 @@
1
1
  import { execFileSync, spawnSync } from "node:child_process";
2
- import { existsSync, readFileSync, readdirSync, realpathSync, rmSync } from "node:fs";
2
+ import { existsSync, mkdtempSync, readFileSync, readdirSync, realpathSync, rmSync } from "node:fs";
3
3
  import os from "node:os";
4
4
  import path from "node:path";
5
5
  import { fileURLToPath } from "node:url";
@@ -73,9 +73,16 @@ export function findToolchain(sbpf = "v0", host = process) {
73
73
  compilerBuiltins: path.join(rustlib, builtins),
74
74
  };
75
75
  }
76
- /** Compile generated C to an SBF shared object (same flags as the SDK's sbf.mk for the chosen SBPF version). */
77
- /** The SBF stack frame of one function. */
76
+ /** SBPF v0: the fixed stack frame of every function. */
78
77
  export const STACK_FRAME = 4096;
78
+ /**
79
+ * SBPF v1 and v2: the largest frame of one function. Frames are sized per function there, but a load or store
80
+ * addresses its slot with a signed 16-bit offset from the frame pointer, and the backend encodes a larger offset
81
+ * wrapped (+34,284 becomes -31,252) without a message: a bigger frame reads and writes the wrong memory.
82
+ */
83
+ export const STACK_FRAME_V1 = 32767;
84
+ /** SBPF v1 and v2: the stack every frame on a call path shares (64 frames of 4 KiB); past it the program fails. */
85
+ export const STACK_TOTAL_V1 = 262144;
79
86
  /** clang's flags for SBF objects (the SDK's sbf.mk for the chosen SBPF version, plus TypeSOL's warnings). */
80
87
  export function sbfCflags(sbpf = "v0") {
81
88
  return [
@@ -84,8 +91,9 @@ export function sbfCflags(sbpf = "v0") {
84
91
  // Generated checks may be always true/false (`a === a`, `enumByte >= 256` for a 256-variant enum); that is not an error.
85
92
  "-Wno-tautological-compare",
86
93
  // SBPF v0 gives every function a fixed 4 KiB stack frame; past it the program corrupts memory instead of failing.
87
- // v1 and v2 grow frames dynamically, so the limit does not apply there.
88
- ...(sbpf === "v0" ? [`-Wframe-larger-than=${STACK_FRAME}`] : []),
94
+ // v1 and v2 size each function's frame, but no frame may pass 32,767 bytes (STACK_FRAME_V1), and all the frames
95
+ // of a call path share 256 KiB (STACK_TOTAL_V1, checked on the linked program by buildSharedObject).
96
+ `-Wframe-larger-than=${sbpf === "v0" ? STACK_FRAME : STACK_FRAME_V1}`,
89
97
  "-O2",
90
98
  "-fno-builtin",
91
99
  // One section per function and constant, so the linker's --gc-sections can drop what nothing reaches.
@@ -102,18 +110,36 @@ export function sbfCflags(sbpf = "v0") {
102
110
  export function builtinsCflags(sbpf = "v0") {
103
111
  return [...sbfCflags(sbpf), `-DTS_SBPF_${sbpf.toUpperCase()}`];
104
112
  }
105
- export function buildSharedObject(cFile, outSo, sbpf = "v0", tc = findToolchain(sbpf)) {
113
+ /**
114
+ * Compile generated C to an SBF shared object (the SDK's sbf.mk flags for the chosen SBPF version), refusing any
115
+ * program whose stack does not fit: a frame over the limit (clang's -Wframe-larger-than), a frame the SBF backend
116
+ * reports it cannot lay out (its own messages, printed while clang still succeeds), and on SBPF v1 and v2 a call path
117
+ * whose frames together pass 256 KiB (from the linked program's calls and frame-pointer adjustments).
118
+ */
119
+ export function buildSharedObject(cFile, outSo, sbpf = "v0", tc = findToolchain(sbpf), opts = {}) {
106
120
  const obj = outSo.replace(/\.so$/, ".o");
107
121
  const builtinsObj = outSo.replace(/\.so$/, ".builtins.o");
108
122
  const cflags = sbfCflags(sbpf);
109
123
  const incs = tc.includes.flatMap((i, n) => (n < 2 ? ["-isystem", i] : ["-I", i]));
110
124
  try {
111
- run(tc.clang, [...cflags, ...incs, "-o", obj, "-c", cFile]);
125
+ const stderr = run(tc.clang, [...cflags, ...incs, "-o", obj, "-c", cFile]);
126
+ // The SBF backend reports a frame it cannot lay out on stderr and lets clang exit 0: the program would compute
127
+ // wrong results, so the build stops here.
128
+ const backend = backendStackError(stderr, sbpf, readFileSync(cFile, "utf8"));
129
+ if (backend) {
130
+ rmSync(obj, { force: true });
131
+ throw backend;
132
+ }
112
133
  }
113
134
  catch (e) {
135
+ if (e instanceof StackLimitError)
136
+ throw e;
114
137
  const message = e.message;
115
138
  if (!STACK_OVER.test(message))
116
139
  throw e;
140
+ // `brief` (a build trying another layout): the functions and sizes only, without the second compile.
141
+ if (opts.brief)
142
+ throw stackError(message, new Map(), "", sbpf);
117
143
  // Compiled again with debug info for clang's frame layout: which locals take the room.
118
144
  const layoutFlags = cflags.filter((f) => f !== "-Werror" && !f.startsWith("-Wframe-larger-than"));
119
145
  const res = spawnSync(tc.clang, [...layoutFlags, ...incs, "-g", "-w", "-Rpass-analysis=stack-frame-layout", "-o", obj, "-c", cFile], {
@@ -122,7 +148,7 @@ export function buildSharedObject(cFile, outSo, sbpf = "v0", tc = findToolchain(
122
148
  maxBuffer: 256 * 1024 * 1024,
123
149
  });
124
150
  rmSync(obj, { force: true });
125
- throw stackError(message, frameLayouts(res.stderr ?? ""), readFileSync(cFile, "utf8"));
151
+ throw stackError(message, frameLayouts(res.stderr ?? ""), readFileSync(cFile, "utf8"), sbpf);
126
152
  }
127
153
  try {
128
154
  // The builtins (128-bit multiplication, division and shifts, signed 64-bit division) from the runtime's C, after
@@ -130,6 +156,32 @@ export function buildSharedObject(cFile, outSo, sbpf = "v0", tc = findToolchain(
130
156
  // but split into other archive members, so the linker laid them out in another order on each host; this does not.
131
157
  run(tc.clang, [...builtinsCflags(sbpf), "-o", builtinsObj, "-c", BUILTINS_SOURCE]);
132
158
  linkSharedObject([obj, builtinsObj], outSo, tc);
159
+ if (sbpf !== "v0") {
160
+ const deepest = deepestCallPath(readFileSync(outSo));
161
+ if (deepest.indirect) {
162
+ // The path through an indirect call cannot be measured, so the stack is not known to fit.
163
+ rmSync(outSo, { force: true });
164
+ throw new Error(`the program makes ${deepest.indirect} indirect call${deepest.indirect === 1 ? "" : "s"} (callx), whose targets the SBPF ${sbpf} stack check cannot follow, so it cannot show that the program's frames fit in ${STACK_TOTAL_V1} bytes. ` +
165
+ "TypeSOL generates no indirect calls with the tested toolchain: please report this with the program.");
166
+ }
167
+ if (deepest.bytes > STACK_TOTAL_V1) {
168
+ // The program is stripped: a second link that keeps the symbols names the functions on the path.
169
+ const named = outSo.replace(/\.so$/, ".symbols.so");
170
+ let names = new Map();
171
+ try {
172
+ linkSharedObject([obj, builtinsObj], named, tc, [], { keepSymbols: true });
173
+ names = functionSymbols(readFileSync(named), readFileSync(outSo));
174
+ }
175
+ catch {
176
+ /* no names: the path is given by address */
177
+ }
178
+ finally {
179
+ rmSync(named, { force: true });
180
+ }
181
+ rmSync(outSo, { force: true });
182
+ throw callPathError(deepest, names, sbpf);
183
+ }
184
+ }
133
185
  }
134
186
  finally {
135
187
  rmSync(obj, { force: true }); // the object files are only intermediates
@@ -137,7 +189,7 @@ export function buildSharedObject(cFile, outSo, sbpf = "v0", tc = findToolchain(
137
189
  }
138
190
  }
139
191
  /** Link SBF objects into a program: libc from platform-tools, nothing from its Rust libraries. */
140
- export function linkSharedObject(objects, outSo, tc, extra = []) {
192
+ export function linkSharedObject(objects, outSo, tc, extra = [], opts = {}) {
141
193
  run(tc.lld, [
142
194
  "-z",
143
195
  "notext",
@@ -153,7 +205,7 @@ export function linkSharedObject(objects, outSo, tc, extra = []) {
153
205
  // Drop unreachable code (the builtins a program does not call) and the symbol tables, which the loader never
154
206
  // reads: smaller programs cost less rent and upload time.
155
207
  "--gc-sections",
156
- "--strip-all",
208
+ ...(opts.keepSymbols ? [] : ["--strip-all"]),
157
209
  "-lc",
158
210
  "-o",
159
211
  outSo,
@@ -426,6 +478,38 @@ export function checkToolchain(info = toolchainInfo(), warn = (m) => console.err
426
478
  return info;
427
479
  }
428
480
  const STACK_OVER = /stack frame size \((\d+)\) exceeds limit \((\d+)\) in '(\w+)'/;
481
+ /** A build refused because the program's stack does not fit: the message, and what did not fit. */
482
+ export class StackLimitError extends Error {
483
+ failures;
484
+ constructor(failures, message) {
485
+ super(message);
486
+ this.failures = failures;
487
+ this.name = "StackLimitError";
488
+ }
489
+ }
490
+ /**
491
+ * The stack frame of every function clang keeps in the object (helpers it inlined everywhere have none), from a
492
+ * compile of `cFile` with the build's flags but no frame limit, and -fstack-usage. Nothing is kept of that compile.
493
+ */
494
+ export function measureFrames(cFile, sbpf = "v0", tc = findToolchain(sbpf)) {
495
+ const dir = mkdtempSync(path.join(os.tmpdir(), "typesol-frames-"));
496
+ try {
497
+ const obj = path.join(dir, "m.o");
498
+ const flags = sbfCflags(sbpf).filter((f) => f !== "-Werror" && !f.startsWith("-Wframe-larger-than"));
499
+ const incs = tc.includes.flatMap((i, n) => (n < 2 ? ["-isystem", i] : ["-I", i]));
500
+ run(tc.clang, [...flags, ...incs, "-w", "-fstack-usage", "-o", obj, "-c", cFile]);
501
+ const out = new Map();
502
+ for (const l of readFileSync(path.join(dir, "m.su"), "utf8").split("\n")) {
503
+ const m = /:([A-Za-z_]\w*)\t(\d+)\t/.exec(l);
504
+ if (m)
505
+ out.set(m[1], Number(m[2]));
506
+ }
507
+ return out;
508
+ }
509
+ finally {
510
+ rmSync(dir, { recursive: true, force: true });
511
+ }
512
+ }
429
513
  /** clang's `-Rpass-analysis=stack-frame-layout` remarks: each function's variable slots. */
430
514
  export function frameLayouts(remarks) {
431
515
  const out = new Map();
@@ -456,7 +540,7 @@ export function frameLayouts(remarks) {
456
540
  * clang's frame-size errors in the program's terms: which instruction or helper, how much, the locals that take the
457
541
  * room (from `layouts`, clang's frame layout of the generated C `c`) and what to do.
458
542
  */
459
- export function stackError(message, layouts = new Map(), c = "") {
543
+ export function stackError(message, layouts = new Map(), c = "", sbpf = "v0") {
460
544
  const over = [...message.matchAll(new RegExp(STACK_OVER.source, "g"))];
461
545
  // clang inlines helpers into their callers, so an instruction's frame includes theirs.
462
546
  const what = (fn) => fn.startsWith("ix_") ? `instruction ${fn.slice(3)} (with the helpers inlined into it)` : fn.startsWith("fn_") ? `helper ${fn.slice(3)}()` : fn;
@@ -561,16 +645,297 @@ export function stackError(message, layouts = new Map(), c = "") {
561
645
  : "\n (unnamed: copies clang made)"
562
646
  : ""));
563
647
  };
564
- return new Error(over.map((m) => `${what(m[3])} needs ${m[1]} bytes of stack; SBPF v0 gives each function ${m[2]}${locals(m[3])}`).join("\n") +
565
- "\nKeep large structs and arrays in account data (bind them with const: a reference, not a copy), give a large local list or struct its own room with /** @heap */ (in an instruction), or move work that needs large locals of its own into a /** @noinline */ helper, which gets its own 4 KiB frame." +
648
+ const limit = sbpf === "v0"
649
+ ? (m) => `SBPF v0 gives each function ${m[2]}`
650
+ : (m) => `SBPF ${sbpf} allows one function at most ${m[2]} (a load or store reaches its slot with a 16-bit offset, so a larger frame would read and write the wrong memory)`;
651
+ return new StackLimitError(over.map((m) => ({ kind: "frame", fn: m[3], bytes: Number(m[1]), limit: Number(m[2]) })), over.map((m) => `${what(m[3])} needs ${m[1]} bytes of stack; ${limit(m)}${locals(m[3])}`).join("\n") +
652
+ (sbpf === "v0"
653
+ ? "\nKeep large structs and arrays in account data (bind them with const: a reference, not a copy), give a large local list or struct its own room with /** @heap */ (in an instruction), or move work that needs large locals of its own into a /** @noinline */ helper, which gets its own 4 KiB frame."
654
+ : `\nKeep large structs and arrays in account data (bind them with const: a reference, not a copy), give a large local list or struct its own room with /** @heap */ (in an instruction), or move work that needs large locals of its own into a /** @noinline */ helper, which gets a frame of its own (all the frames of a call path share ${STACK_TOTAL_V1} bytes).`) +
566
655
  (rest ? `\n${rest}` : ""));
567
656
  }
568
- function run(cmd, args) {
569
- try {
570
- execFileSync(cmd, args, { stdio: ["ignore", "pipe", "pipe"], maxBuffer: 256 * 1024 * 1024 });
657
+ /** C functions' bodies in the generated C, by name (`fn_*`, `ix_*`), and the ones declared noinline. */
658
+ function cFunctions(c) {
659
+ const bodies = new Map();
660
+ const noinline = new Set();
661
+ let current;
662
+ for (const l of c.split("\n")) {
663
+ const m = /^(__attribute__\(\(noinline\)\) )?static uint64_t ((?:fn|ix)_\w+)\(.*\) \{$/.exec(l);
664
+ if (m) {
665
+ bodies.set(m[2], (current = []));
666
+ if (m[1])
667
+ noinline.add(m[2]);
668
+ }
669
+ else if (l === "}")
670
+ current = undefined;
671
+ else
672
+ current?.push(l);
571
673
  }
572
- catch (e) {
573
- const err = e;
574
- throw new Error(`${path.basename(cmd)} failed:\n${err.stderr?.toString() ?? ""}${err.stdout?.toString() ?? ""}`);
674
+ return { bodies, noinline };
675
+ }
676
+ /** The number of arguments of the call whose `(` is at `open` in `text`, or undefined if it does not close there. */
677
+ function callArity(text, open) {
678
+ let depth = 0;
679
+ let args = 0;
680
+ let any = false;
681
+ for (let i = open; i < text.length; i++) {
682
+ const ch = text[i];
683
+ if (ch === "(" || ch === "[" || ch === "{")
684
+ depth++;
685
+ else if (ch === ")" || ch === "]" || ch === "}") {
686
+ if (--depth === 0)
687
+ return any ? args + 1 : 0;
688
+ }
689
+ else if (depth === 1 && ch === ",")
690
+ args++;
691
+ else if (depth === 1 && !/\s/.test(ch))
692
+ any = true;
575
693
  }
694
+ return undefined;
695
+ }
696
+ const BACKEND_CALL = /^Error: A function call in method (\w+) overwrites values in the frame/;
697
+ const BACKEND_OFFSET = /^Error: Function (\w+) Stack offset of (\d+) exceeded max offset of (\d+)/;
698
+ /**
699
+ * The SBF backend's own stack messages in clang's stderr, in the program's terms, or undefined when there are none.
700
+ * The backend prints them and clang still exits 0: "A function call in method F overwrites values in the frame" (a
701
+ * call that passes arguments on the stack, past a frame at the limit) and "Function F Stack offset of N exceeded max
702
+ * offset of M". Either way the program it builds may compute wrong results.
703
+ */
704
+ export function backendStackError(stderr, sbpf = "v0", c = "") {
705
+ const lines = stderr.split("\n");
706
+ const calls = [...new Set(lines.flatMap((l) => BACKEND_CALL.exec(l)?.[1] ?? []))];
707
+ const offsets = new Map();
708
+ for (const l of lines) {
709
+ const m = BACKEND_OFFSET.exec(l);
710
+ if (m && !offsets.has(m[1]))
711
+ offsets.set(m[1], m);
712
+ }
713
+ if (!calls.length && !offsets.size)
714
+ return undefined;
715
+ const what = (fn) => fn.startsWith("ix_") ? `instruction ${fn.slice(3)} (with the helpers inlined into it)` : fn.startsWith("fn_") ? `helper ${fn.slice(3)}()` : fn;
716
+ const { bodies, noinline } = cFunctions(c);
717
+ // The helpers `fn` calls with more than 5 C arguments (the rest go on the stack), in it or in the helpers clang
718
+ // may inline into it.
719
+ const stackArgCalls = (fn) => {
720
+ const out = new Set();
721
+ const seen = new Set([fn]);
722
+ const visit = (f) => {
723
+ const body = (bodies.get(f) ?? []).join("\n");
724
+ for (const call of body.matchAll(/\b(fn_\w+)\(/g)) {
725
+ const callee = call[1];
726
+ const n = callArity(body, call.index + callee.length);
727
+ if (n !== undefined && n > 5)
728
+ out.add(`${callee.slice(3)}()`);
729
+ if (!seen.has(callee) && !noinline.has(callee)) {
730
+ seen.add(callee);
731
+ visit(callee);
732
+ }
733
+ }
734
+ };
735
+ visit(fn);
736
+ return [...out];
737
+ };
738
+ const frame = sbpf === "v0" ? `the ${STACK_FRAME}-byte frame of SBPF v0` : "its frame";
739
+ const parts = [
740
+ ...calls.map((fn) => {
741
+ const callees = stackArgCalls(fn);
742
+ return (`${what(fn)}: a call passes arguments on the stack past the end of ${frame}, which overwrites the frame's own values (clang's SBF backend reports this and builds anyway; the program would compute wrong results)` +
743
+ (callees.length
744
+ ? `\n helpers it calls with more than 5 arguments in C (its parameters, plus one for the program's context and one for a returned value): ${callees.join(", ")}`
745
+ : "") +
746
+ "\nGive the called helper fewer parameters (a struct parameter is passed as one pointer), or make room in the caller: keep large structs and arrays in account data (bind them with const: a reference, not a copy), give a large local list or struct its own room with /** @heap */ (in an instruction), or move work that needs large locals into a /** @noinline */ helper.");
747
+ }),
748
+ ...[...offsets.values()].map((m) => `${what(m[1])} needs a stack offset of ${m[2]} bytes; its frame allows ${m[3]} (clang's SBF backend reports this and builds anyway; the program would compute wrong results)` +
749
+ "\nKeep large structs and arrays in account data (bind them with const: a reference, not a copy), give a large local list or struct its own room with /** @heap */ (in an instruction), or move work that needs large locals of its own into a /** @noinline */ helper."),
750
+ ];
751
+ return new StackLimitError([
752
+ ...calls.map((fn) => ({ kind: "call", fn })),
753
+ ...[...offsets.values()].map((m) => ({ kind: "offset", fn: m[1], bytes: Number(m[2]), limit: Number(m[3]) })),
754
+ ], parts.join("\n"));
755
+ }
756
+ function elfSections(elf) {
757
+ if (elf.length < 0x40 || elf.readUInt32BE(0) !== 0x7f454c46)
758
+ throw new Error("not an ELF file");
759
+ const shoff = Number(elf.readBigUInt64LE(0x28));
760
+ const shentsize = elf.readUInt16LE(0x3a);
761
+ const shnum = elf.readUInt16LE(0x3c);
762
+ const shstrndx = elf.readUInt16LE(0x3e);
763
+ const raw = Array.from({ length: shnum }, (_, i) => {
764
+ const at = shoff + i * shentsize;
765
+ return {
766
+ nameOff: elf.readUInt32LE(at),
767
+ type: elf.readUInt32LE(at + 4),
768
+ addr: Number(elf.readBigUInt64LE(at + 0x10)),
769
+ offset: Number(elf.readBigUInt64LE(at + 0x18)),
770
+ size: Number(elf.readBigUInt64LE(at + 0x20)),
771
+ link: elf.readUInt32LE(at + 0x28),
772
+ };
773
+ });
774
+ const strtab = raw[shstrndx]?.offset ?? 0;
775
+ return raw.map(({ nameOff, ...r }) => ({ ...r, name: elf.toString("latin1", strtab + nameOff, elf.indexOf(0, strtab + nameOff)) }));
776
+ }
777
+ /**
778
+ * The deepest call path of a linked SBPF v1/v2 program, from its own instructions: functions start at the
779
+ * entrypoint and at every target of an internal call (`call` with a pc-relative target; a call the loader resolves
780
+ * through a relocation is a syscall, which runs outside the program's stack), and a function's frame is what it
781
+ * subtracts from the frame pointer r10 (`add64 r10, -N`). Since this is the code clang produced, a helper it inlined
782
+ * adds its locals to its caller's frame and its calls to the caller's calls.
783
+ *
784
+ * Not followed: indirect calls (`callx`), counted in `indirect`; TypeSOL emits none (closures are expanded where
785
+ * they are called). A cycle (recursion) throws: TypeSOL refuses recursion, so it would be a compiler bug.
786
+ */
787
+ export function deepestCallPath(elf) {
788
+ const sections = elfSections(elf);
789
+ const text = sections.find((s) => s.name === ".text");
790
+ if (!text)
791
+ throw new Error("the program has no .text section");
792
+ const entry = Number(elf.readBigUInt64LE(0x18));
793
+ // Call sites the loader patches: R_SBF_64_32 (10) relocations, the syscalls of a program without static syscalls.
794
+ const relocated = new Set();
795
+ for (const s of sections) {
796
+ if (s.type !== 9)
797
+ continue; // SHT_REL
798
+ for (let at = s.offset; at + 16 <= s.offset + s.size; at += 16)
799
+ if ((Number(elf.readBigUInt64LE(at + 8)) & 0xffffffff) === 10)
800
+ relocated.add(Number(elf.readBigUInt64LE(at)));
801
+ }
802
+ const count = Math.floor(text.size / 8);
803
+ const op = (i) => elf[text.offset + i * 8];
804
+ const regs = (i) => elf[text.offset + i * 8 + 1];
805
+ const imm = (i) => elf.readInt32LE(text.offset + i * 8 + 4);
806
+ const at = (address) => (address - text.addr) / 8;
807
+ const starts = new Set([at(entry)]);
808
+ const calls = [];
809
+ for (let i = 0; i < count; i++) {
810
+ if (op(i) === 0x85 && !relocated.has(text.addr + i * 8)) {
811
+ const target = i + 1 + imm(i);
812
+ if (target < 0 || target >= count)
813
+ throw new Error(`a call at .text+0x${(i * 8).toString(16)} leaves the program's code`);
814
+ starts.add(target);
815
+ calls.push([i, target]);
816
+ }
817
+ // lddw takes two instruction slots (SBPF v1; v2 has no lddw, and its 0x18 is not an instruction either).
818
+ if (op(i) === 0x18 && i + 1 < count && op(i + 1) === 0)
819
+ i++;
820
+ }
821
+ const sorted = [...starts].sort((a, b) => a - b);
822
+ const owner = (i) => {
823
+ let lo = 0;
824
+ let hi = sorted.length - 1;
825
+ if (i < sorted[0])
826
+ return undefined;
827
+ while (lo < hi) {
828
+ const mid = (lo + hi + 1) >> 1;
829
+ if (sorted[mid] <= i)
830
+ lo = mid;
831
+ else
832
+ hi = mid - 1;
833
+ }
834
+ return sorted[lo];
835
+ };
836
+ const fns = new Map(sorted.map((s) => [s, { frame: 0, callees: new Set(), indirect: 0 }]));
837
+ for (let i = 0; i < count; i++) {
838
+ const f = owner(i);
839
+ if (f !== undefined) {
840
+ const fn = fns.get(f);
841
+ if (op(i) === 0x07 && (regs(i) & 0x0f) === 10 && imm(i) < 0)
842
+ fn.frame += -imm(i);
843
+ else if (op(i) === 0x8d)
844
+ fn.indirect++;
845
+ }
846
+ if (op(i) === 0x18 && i + 1 < count && op(i + 1) === 0)
847
+ i++;
848
+ }
849
+ for (const [site, target] of calls) {
850
+ const f = owner(site);
851
+ if (f !== undefined)
852
+ fns.get(f).callees.add(target);
853
+ }
854
+ const memo = new Map();
855
+ const visiting = new Set();
856
+ let indirect = 0;
857
+ const deepest = (f) => {
858
+ const known = memo.get(f);
859
+ if (known)
860
+ return known.bytes;
861
+ if (visiting.has(f))
862
+ throw new Error(`the program's calls form a cycle through .text+0x${(f * 8).toString(16)}: its stack cannot be bounded`);
863
+ visiting.add(f);
864
+ const fn = fns.get(f);
865
+ indirect += fn.indirect;
866
+ let best = { bytes: fn.frame };
867
+ for (const c of [...fn.callees].sort((a, b) => a - b)) {
868
+ const b = fn.frame + deepest(c);
869
+ if (b > best.bytes)
870
+ best = { bytes: b, next: c };
871
+ }
872
+ visiting.delete(f);
873
+ memo.set(f, best);
874
+ return best.bytes;
875
+ };
876
+ const root = at(entry);
877
+ const bytes = deepest(root);
878
+ const path = [];
879
+ for (let f = root; f !== undefined; f = memo.get(f).next)
880
+ path.push({ address: f * 8, frame: fns.get(f).frame });
881
+ return { bytes, path, indirect };
882
+ }
883
+ /**
884
+ * Function names by .text offset, from `named` (the same program linked with its symbols), when its code is the code
885
+ * of `stripped`; empty otherwise.
886
+ */
887
+ export function functionSymbols(named, stripped) {
888
+ const out = new Map();
889
+ const ns = elfSections(named);
890
+ const text = ns.find((s) => s.name === ".text");
891
+ const other = elfSections(stripped).find((s) => s.name === ".text");
892
+ if (!text ||
893
+ !other ||
894
+ text.addr !== other.addr ||
895
+ !named.subarray(text.offset, text.offset + text.size).equals(stripped.subarray(other.offset, other.offset + other.size)))
896
+ return out;
897
+ for (const s of ns) {
898
+ if (s.type !== 2)
899
+ continue; // SHT_SYMTAB
900
+ const strtab = ns[s.link];
901
+ for (let at = s.offset; at + 24 <= s.offset + s.size; at += 24) {
902
+ if ((named[at + 4] & 0xf) !== 2)
903
+ continue; // STT_FUNC
904
+ const value = Number(named.readBigUInt64LE(at + 8));
905
+ const nameAt = strtab.offset + named.readUInt32LE(at);
906
+ const name = named.toString("latin1", nameAt, named.indexOf(0, nameAt));
907
+ if (name && value >= text.addr && value < text.addr + text.size)
908
+ out.set(value - text.addr, name);
909
+ }
910
+ }
911
+ return out;
912
+ }
913
+ /** The error for a call path whose frames pass SBPF v1/v2's 256 KiB of stack. */
914
+ export function callPathError(deepest, names, sbpf) {
915
+ const what = (fn) => (fn.startsWith("ix_") ? `instruction ${fn.slice(3)}` : fn.startsWith("fn_") ? `${fn.slice(3)}()` : fn);
916
+ const steps = deepest.path.map((p) => `${(() => {
917
+ const n = names.get(p.address);
918
+ return n ? what(n) : `.text+0x${p.address.toString(16)}`;
919
+ })()} ${p.frame}`);
920
+ const named = deepest.path.map((p) => names.get(p.address));
921
+ return new StackLimitError([
922
+ {
923
+ kind: "path",
924
+ fn: named.find((n) => n?.startsWith("ix_")) ?? "entrypoint",
925
+ bytes: deepest.bytes,
926
+ limit: STACK_TOTAL_V1,
927
+ path: named.every((n) => n !== undefined) ? deepest.path.map((p, i) => ({ fn: named[i], frame: p.frame })) : undefined,
928
+ },
929
+ ], `the deepest call path needs ${deepest.bytes} bytes of stack; SBPF ${sbpf} gives all the frames of a call path together ${STACK_TOTAL_V1} (256 KiB), and past that the program fails with an access violation\n` +
930
+ ` path (function and frame bytes): ${steps.join(" -> ")}\n` +
931
+ "Keep large structs and arrays in account data (bind them with const: a reference, not a copy), give a large local list or struct of an instruction its own room with /** @heap */, or call the helpers with large frames one after another instead of from each other.");
932
+ }
933
+ /** Run a tool; its stderr when it succeeds (clang's SBF backend reports some errors there and exits 0). */
934
+ function run(cmd, args) {
935
+ const res = spawnSync(cmd, args, { stdio: ["ignore", "pipe", "pipe"], maxBuffer: 256 * 1024 * 1024 });
936
+ if (res.error)
937
+ throw new Error(`${path.basename(cmd)} failed:\n${res.error.message}`);
938
+ if (res.status !== 0)
939
+ throw new Error(`${path.basename(cmd)} failed:\n${res.stderr?.toString() ?? ""}${res.stdout?.toString() ?? ""}${res.signal ? `(killed by ${res.signal})` : ""}`);
940
+ return res.stderr?.toString() ?? "";
576
941
  }
@@ -53,6 +53,7 @@ export declare function buildWorkspace(ws: Workspace, names?: string[], opts?: {
53
53
  sbpf?: Sbpf;
54
54
  profile?: boolean;
55
55
  needKeypair?: boolean;
56
+ stackAuto?: boolean;
56
57
  }): {
57
58
  paths: ProgramPaths;
58
59
  address: string;
package/dist/workspace.js CHANGED
@@ -144,7 +144,7 @@ export function buildWorkspace(ws, names = Object.keys(ws.programs), opts = {})
144
144
  // another process building it at the same time (vitest runs test files in parallel workers) would overwrite them.
145
145
  return withBuildLock(paths.outDir, () => {
146
146
  const { address, created, keyless } = programAddress(ws, name, { needKeypair: opts.needKeypair });
147
- const result = build(paths.entry, paths.outDir, address, { sbpf: opts.sbpf ?? ws.sbpf, profile: opts.profile });
147
+ const result = build(paths.entry, paths.outDir, address, { sbpf: opts.sbpf ?? ws.sbpf, profile: opts.profile, stackAuto: opts.stackAuto });
148
148
  // The TypeScript client (docs/client.md) is written with the build, from the same IDL.
149
149
  const clientPath = writeClient(result.idl, path.join(paths.outDir, `${result.model.name}.client.ts`)).path;
150
150
  return { paths, address, created, keyless, result, clientPath };