@typesol/cli 0.44.1 → 0.45.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.
@@ -7,6 +7,8 @@ export const RUNTIME_DIR = fileURLToPath(new URL("../../runtime/", import.meta.u
7
7
  /** Executable names: platform-tools ship .exe files on Windows. */
8
8
  const EXE = (name) => (process.platform === "win32" ? `${name}.exe` : name);
9
9
  export const SBPF_VERSIONS = ["v0", "v1", "v2"];
10
+ /** The runtime's compiler builtins, compiled with each program and linked in place of compiler-builtins. */
11
+ export const BUILTINS_SOURCE = path.join(RUNTIME_DIR, "typesol_builtins.c");
10
12
  /** Locate the Solana C SDK that ships with the Agave CLI's platform-tools. */
11
13
  export function findToolchain(sbpf = "v0") {
12
14
  // Where the Agave installer puts it, or next to `cargo-build-sbf` on PATH (custom --data-dir, Homebrew, Docker…).
@@ -53,9 +55,9 @@ export function findToolchain(sbpf = "v0") {
53
55
  /** Compile generated C to an SBF shared object (same flags as the SDK's sbf.mk for the chosen SBPF version). */
54
56
  /** The SBF stack frame of one function. */
55
57
  export const STACK_FRAME = 4096;
56
- export function buildSharedObject(cFile, outSo, sbpf = "v0", tc = findToolchain(sbpf)) {
57
- const obj = outSo.replace(/\.so$/, ".o");
58
- const cflags = [
58
+ /** clang's flags for SBF objects (the SDK's sbf.mk for the chosen SBPF version, plus TypeSOL's warnings). */
59
+ export function sbfCflags(sbpf = "v0") {
60
+ return [
59
61
  "-Werror",
60
62
  "-Wno-parentheses-equality",
61
63
  // Generated checks may be always true/false (`a === a`, `enumByte >= 256` for a 256-variant enum); that is not an error.
@@ -74,6 +76,15 @@ export function buildSharedObject(cFile, outSo, sbpf = "v0", tc = findToolchain(
74
76
  "-fPIC",
75
77
  ...(sbpf === "v0" ? [] : [`-mcpu=${sbpf}`]),
76
78
  ];
79
+ }
80
+ /** The flags runtime/typesol_builtins.c is compiled with: the program's, and the SBPF version (its assembly differs). */
81
+ export function builtinsCflags(sbpf = "v0") {
82
+ return [...sbfCflags(sbpf), `-DTS_SBPF_${sbpf.toUpperCase()}`];
83
+ }
84
+ export function buildSharedObject(cFile, outSo, sbpf = "v0", tc = findToolchain(sbpf)) {
85
+ const obj = outSo.replace(/\.so$/, ".o");
86
+ const builtinsObj = outSo.replace(/\.so$/, ".builtins.o");
87
+ const cflags = sbfCflags(sbpf);
77
88
  const incs = tc.includes.flatMap((i, n) => (n < 2 ? ["-isystem", i] : ["-I", i]));
78
89
  try {
79
90
  run(tc.clang, [...cflags, ...incs, "-o", obj, "-c", cFile]);
@@ -92,6 +103,20 @@ export function buildSharedObject(cFile, outSo, sbpf = "v0", tc = findToolchain(
92
103
  rmSync(obj, { force: true });
93
104
  throw stackError(message, frameLayouts(res.stderr ?? ""), readFileSync(cFile, "utf8"));
94
105
  }
106
+ try {
107
+ // The builtins (128-bit multiplication, division and shifts, signed 64-bit division) from the runtime's C, after
108
+ // the program's object. platform-tools' compiler-builtins library has the same instructions in each host package
109
+ // but split into other archive members, so the linker laid them out in another order on each host; this does not.
110
+ run(tc.clang, [...builtinsCflags(sbpf), "-o", builtinsObj, "-c", BUILTINS_SOURCE]);
111
+ linkSharedObject([obj, builtinsObj], outSo, tc);
112
+ }
113
+ finally {
114
+ rmSync(obj, { force: true }); // the object files are only intermediates
115
+ rmSync(builtinsObj, { force: true });
116
+ }
117
+ }
118
+ /** Link SBF objects into a program: libc from platform-tools, nothing from its Rust libraries. */
119
+ export function linkSharedObject(objects, outSo, tc, extra = []) {
95
120
  run(tc.lld, [
96
121
  "-z",
97
122
  "notext",
@@ -104,17 +129,112 @@ export function buildSharedObject(cFile, outSo, sbpf = "v0", tc = findToolchain(
104
129
  tc.libDir,
105
130
  "-z",
106
131
  "max-page-size=4096",
107
- // Drop unreachable code (e.g. the parts of compiler-builtins' soft-float objects nothing calls) and the symbol
108
- // tables, which the loader never reads: smaller programs cost less rent and upload time.
132
+ // Drop unreachable code (the builtins a program does not call) and the symbol tables, which the loader never
133
+ // reads: smaller programs cost less rent and upload time.
109
134
  "--gc-sections",
110
135
  "--strip-all",
111
136
  "-lc",
112
137
  "-o",
113
138
  outSo,
114
- obj,
115
- tc.compilerBuiltins,
139
+ ...objects,
140
+ ...extra,
116
141
  ]);
117
- rmSync(obj, { force: true }); // the object file is only an intermediate
142
+ const missing = unresolvedSymbols(readFileSync(outSo)).filter((s) => !isSyscall(s));
143
+ if (missing.length) {
144
+ rmSync(outSo, { force: true });
145
+ // Another clang may call a builtin the tested one never does: say that first, as it is then the likely cause.
146
+ let info;
147
+ try {
148
+ info = toolchainInfo(tc);
149
+ }
150
+ catch {
151
+ /* the version cannot be read: no claim about it */
152
+ }
153
+ const t = TESTED_TOOLCHAIN;
154
+ throw new Error((info && !info.tested
155
+ ? `this toolchain is not the tested one (${shortClang(info.clang)}${info.platformTools ? `, platform-tools ${info.platformTools}` : ""}; ` +
156
+ `TESTED_TOOLCHAIN is ${shortClang(t.clang)}, platform-tools ${t.platformTools}), and its clang may call compiler builtins the tested one ` +
157
+ `does not, which runtime/typesol_builtins.c does not define: build with the tested toolchain (${INSTALL_TESTED_TOOLCHAIN[1]}). `
158
+ : "") +
159
+ `the program calls ${missing.join(", ")}, which neither the runtime nor libc defines and the SBF loader cannot resolve as a syscall ` +
160
+ `(with the tested toolchain, a compiler builtin missing from runtime/typesol_builtins.c is a TypeSOL bug: please report it with the program)`);
161
+ }
162
+ }
163
+ /**
164
+ * The syscalls a TypeSOL program may leave to the SBF loader: every one the SDK's headers declare (`@SYSCALL` in
165
+ * platform-tools-sdk/sbf/c/inc/sol/inc/*.inc) and every one runtime/typesol_rt.h declares itself, with `abort`.
166
+ * test/cli/toolchain.test.ts checks that this is exactly that set.
167
+ */
168
+ export const SYSCALLS = [
169
+ "abort",
170
+ "sol_alt_bn128_compression",
171
+ "sol_alt_bn128_group_op",
172
+ "sol_big_mod_exp",
173
+ "sol_blake3",
174
+ "sol_create_program_address",
175
+ "sol_curve_validate_point",
176
+ "sol_get_clock_sysvar",
177
+ "sol_get_epoch_rewards_sysvar",
178
+ "sol_get_epoch_schedule_sysvar",
179
+ "sol_get_last_restart_slot",
180
+ "sol_get_rent_sysvar",
181
+ "sol_get_return_data",
182
+ "sol_get_stack_height",
183
+ "sol_invoke_signed_c",
184
+ "sol_keccak256",
185
+ "sol_log_",
186
+ "sol_log_64_",
187
+ "sol_log_compute_units_",
188
+ "sol_log_data",
189
+ "sol_log_pubkey",
190
+ "sol_memcpy_",
191
+ "sol_memmove_",
192
+ "sol_memset_",
193
+ "sol_panic_",
194
+ "sol_poseidon",
195
+ "sol_remaining_compute_units",
196
+ "sol_secp256k1_recover",
197
+ "sol_set_return_data",
198
+ "sol_sha256",
199
+ "sol_try_find_program_address",
200
+ ];
201
+ /** Whether the SBF loader resolves `name` as a syscall for a TypeSOL program (one of SYSCALLS). */
202
+ export function isSyscall(name) {
203
+ return SYSCALLS.includes(name);
204
+ }
205
+ /** The undefined symbols of an SBF shared object's dynamic symbol table (what the loader resolves as syscalls). */
206
+ export function unresolvedSymbols(elf) {
207
+ if (elf.length < 0x40 || elf.readUInt32BE(0) !== 0x7f454c46)
208
+ throw new Error("not an ELF file");
209
+ const shoff = Number(elf.readBigUInt64LE(0x28));
210
+ const shentsize = elf.readUInt16LE(0x3a);
211
+ const shnum = elf.readUInt16LE(0x3c);
212
+ const section = (i) => {
213
+ const at = shoff + i * shentsize;
214
+ return {
215
+ type: elf.readUInt32LE(at + 4),
216
+ offset: Number(elf.readBigUInt64LE(at + 0x18)),
217
+ size: Number(elf.readBigUInt64LE(at + 0x20)),
218
+ link: elf.readUInt32LE(at + 0x28),
219
+ };
220
+ };
221
+ const out = [];
222
+ for (let i = 0; i < shnum; i++) {
223
+ const s = section(i);
224
+ if (s.type !== 11)
225
+ continue; // SHT_DYNSYM
226
+ const strtab = section(s.link);
227
+ for (let at = s.offset + 24; at + 24 <= s.offset + s.size; at += 24) {
228
+ if (elf.readUInt16LE(at + 6) !== 0)
229
+ continue; // st_shndx: defined
230
+ const nameAt = strtab.offset + elf.readUInt32LE(at);
231
+ const end = elf.indexOf(0, nameAt);
232
+ const name = elf.toString("latin1", nameAt, end);
233
+ if (name)
234
+ out.push(name);
235
+ }
236
+ }
237
+ return out;
118
238
  }
119
239
  /**
120
240
  * The toolchain this release is tested with: CI installs exactly this Agave CLI and platform-tools, and every
@@ -0,0 +1,183 @@
1
+ import type { BuildManifest, ContainerIdentity, Sbpf } from "../compiler/index.js";
2
+ export declare const DOCKER_PLATFORM = "linux/amd64";
3
+ export declare const DOCKERFILE: string;
4
+ /** The release records the package ships (releases/<version>.json): the TypeSOL versions an image can install. */
5
+ export declare const RELEASES_DIR: string;
6
+ /**
7
+ * The dependency locks the package ships (docker/deps/<version>.lock.json): for each TypeSOL version, the npm lockfile
8
+ * of its runtime dependencies, which the image installs with `npm ci` (every package checked against its integrity).
9
+ * The lock of version N ships in package N (it does not contain N's own tarball); a version newer than the package
10
+ * carries its own, checked with the rest of its tarball against the release record.
11
+ */
12
+ export declare const DEPS_DIR: string;
13
+ /** Docker is missing or failed: the message says what to do. Never answered by building locally instead. */
14
+ export declare class DockerError extends Error {
15
+ }
16
+ export type DockerStatus = {
17
+ ok: true;
18
+ version: string;
19
+ platform: string;
20
+ } | {
21
+ ok: false;
22
+ reason: string;
23
+ fix: string;
24
+ };
25
+ /** Whether `docker` is there and its daemon answers. */
26
+ export declare function dockerStatus(): DockerStatus;
27
+ /** Throws a DockerError with the fix when Docker cannot run builds. */
28
+ export declare function needDocker(): void;
29
+ /** The pinned inputs a Dockerfile names: its base images (FROM …@sha256:…) and its checksummed downloads (ADD --checksum). */
30
+ export declare function dockerfileInputs(text: string): {
31
+ base: string[];
32
+ downloads: {
33
+ url: string;
34
+ sha256: string;
35
+ }[];
36
+ };
37
+ /** What `--docker` needs of a release record: the tarball's hashes and every file's sha256. */
38
+ export interface ReleaseRecord {
39
+ version: string;
40
+ commit: string;
41
+ tarball: {
42
+ shasum: string;
43
+ integrity: string;
44
+ };
45
+ files: {
46
+ path: string;
47
+ sha256: string;
48
+ }[];
49
+ }
50
+ /** The versions whose records ship with this package, oldest first. */
51
+ export declare function recordedVersions(dir?: string): string[];
52
+ /** Where a release record came from: this package, a file given with --release-record, or the repository's main branch. */
53
+ export interface RecordSource {
54
+ kind: "package" | "file" | "repository";
55
+ /** `releases/<version>.json` (in the package), the file as given, or the URL it was fetched from. */
56
+ location: string;
57
+ /** sha256 of the record's bytes, as read or served (what `sha256sum` of the file gives). */
58
+ sha256: string;
59
+ }
60
+ /** A release record, its bytes (what the image build checks the tarball against), and where it came from. */
61
+ export interface FoundRecord {
62
+ record: ReleaseRecord;
63
+ bytes: Buffer;
64
+ source: RecordSource;
65
+ }
66
+ /**
67
+ * Where a release's record is fetched from when this package does not ship it: the repository's main branch, where it
68
+ * is committed after the release is published (the package of version N cannot contain releases/N.json).
69
+ */
70
+ export declare const RELEASES_URL = "https://raw.githubusercontent.com/typesol-lang/typesol/main/releases";
71
+ /** The fetch a record lookup uses (tests pass their own: no network). */
72
+ export type FetchText = (url: string, init: {
73
+ signal: AbortSignal;
74
+ }) => Promise<{
75
+ ok: boolean;
76
+ status: number;
77
+ arrayBuffer(): Promise<ArrayBuffer>;
78
+ }>;
79
+ /**
80
+ * The release record of `version`: `file` (`--release-record`, e.g. releases/<version>.json from the repository), or
81
+ * the one this package ships. A version without one is refused: its tarball could not be checked. (findReleaseRecord
82
+ * also fetches a newer release's record from the repository.)
83
+ */
84
+ export declare function releaseRecord(version: string, file?: string, dir?: string): FoundRecord;
85
+ /**
86
+ * The release record of `version` for a container build: `file` when given, else the package's, else (a release newer
87
+ * than this package, whose record was committed after the package was published) releases/<version>.json fetched from
88
+ * the repository's main branch over HTTPS. The check then rests on two independent sources agreeing: the tarball npm
89
+ * serves and the record the repository holds. Offline, or when the repository has no record for the version, it is an
90
+ * error that names --release-record. Where the record came from goes to `log` and into the build's manifest.
91
+ */
92
+ export declare function findReleaseRecord(version: string, opts?: {
93
+ file?: string;
94
+ dir?: string;
95
+ fetch?: FetchText;
96
+ log?: (s: string) => void;
97
+ timeoutMs?: number;
98
+ }): Promise<FoundRecord>;
99
+ /**
100
+ * The TypeSOL version a container build uses: `--typesol-version`, else the version of the deployed build's manifest
101
+ * (verify), else this CLI's. A project that installs another typesol than the CLI that runs is an error rather than a
102
+ * guess: the project's own (`npx --no-install typesol`) is the one its builds were made with.
103
+ */
104
+ export declare function chooseTypesolVersion(opts: {
105
+ given?: string;
106
+ deployed?: {
107
+ version: string;
108
+ from: string;
109
+ };
110
+ projectRoot?: string;
111
+ cliVersion: string;
112
+ }): {
113
+ version: string;
114
+ why: string;
115
+ };
116
+ /** The image a container build runs in, and what to record about it. */
117
+ export interface BuildImage {
118
+ tag: string;
119
+ identity: ContainerIdentity;
120
+ }
121
+ /**
122
+ * The dependency lock of `version`'s image: this package's docker/deps/<version>.lock.json, else the one in that
123
+ * version's own tarball, whose sha256 the release record lists (the image takes it from the checked tarball). Neither:
124
+ * a DockerError, as the image would have to resolve the dependencies unpinned.
125
+ */
126
+ export declare function dependencyLock(record: ReleaseRecord, dir?: string): {
127
+ bytes?: Buffer;
128
+ lock: NonNullable<ContainerIdentity["deps"]>;
129
+ };
130
+ /** The versions whose dependency locks ship with this package. */
131
+ export declare function lockedVersions(dir?: string): string[];
132
+ /** sha256 of a record's file list (path and sha256 of each, in order): one label for "every file as recorded". */
133
+ export declare function filesDigest(record: ReleaseRecord): string;
134
+ /**
135
+ * The labels an image is built with: everything the image build checked. A cached image is used only when all of
136
+ * them are this record's and this lock's.
137
+ */
138
+ export declare function imageLabels(dockerfileSha: string, record: ReleaseRecord, lockSha: string): Record<string, string>;
139
+ /**
140
+ * The image for `version`, built first when this machine has none (`typesol-build:<version>-<Dockerfile sha256>`).
141
+ * Progress goes to stderr. Building needs the network (base images, release files, npm); running it does not.
142
+ */
143
+ export declare function ensureImage(version: string, found?: FoundRecord, log?: (s: string) => void): BuildImage;
144
+ /** One program to build in the container. Paths are the host's. */
145
+ export interface ContainerJob {
146
+ entry: string;
147
+ outDir: string;
148
+ address: string;
149
+ sbpf: Sbpf;
150
+ profile?: boolean;
151
+ }
152
+ export interface ContainerResult {
153
+ name: string;
154
+ soPath: string;
155
+ manifestPath: string;
156
+ manifest: BuildManifest;
157
+ }
158
+ /**
159
+ * Build `jobs` in the image: `root` mounted read-only (the only sources the container sees), each output directory
160
+ * writable, no network, a read-only root file system, no capabilities, the caller's uid and gid (containerUser). The files are
161
+ * the ones `build` writes; each manifest gets the container's identity.
162
+ */
163
+ export declare function containerBuild(image: BuildImage, root: string, jobs: ContainerJob[]): ContainerResult[];
164
+ /**
165
+ * The user the container runs as: the caller's uid:gid, so that it can write the output directories the caller made
166
+ * and the outputs are the caller's. That is root (0:0) for a root caller, still without capabilities, with
167
+ * no-new-privileges and a read-only root file system. Where there is no uid (Windows), the image's `node` user.
168
+ */
169
+ export declare function containerUser(ids?: {
170
+ uid?: number;
171
+ gid?: number;
172
+ }): string;
173
+ /** TYPESOL_DOCKER_CPUS / TYPESOL_DOCKER_MEMORY: limits for the build container on a shared machine. */
174
+ export declare function limits(): string[];
175
+ /** The git commit of a source directory and whether its files differ from it, when it is in a checkout. */
176
+ export declare function sourceRevision(dir: string): {
177
+ commit: string;
178
+ clean: boolean;
179
+ } | undefined;
180
+ /** The `typesol verify` command that repeats a container verify: the arguments and every option that changes the result. */
181
+ export declare function repeatCommand(args: string[], v: Record<string, unknown>, version: string): string;
182
+ /** Quote a command-line word for a POSIX shell when it needs it. */
183
+ export declare function shellQuote(s: string): string;