gmux 0.1.0
Linux on Cloudflare Workers
Loading...
Searching...
No Matches
kb.h
1#ifndef KB_H
2#define KB_H
3
4#include <stddef.h>
5#include <stdint.h>
6#include <stdio.h>
7#include <sys/uio.h>
8
9#include "f80.h"
10
11/* a mapping's host memory comes in blocks of at most 1 << KB_PIECE_BITS bytes,
12 * so no allocation is larger (mem.c); an inline cache covers one piece */
13#ifndef KB_PIECE_BITS
14 #define KB_PIECE_BITS 16
15#endif
16/* an ELF image's mappings use smaller pieces, so a guest that touches a few
17 * pages of a large binary holds fewer of them */
18#ifndef KB_IMAGE_PIECE_BITS
19 #define KB_IMAGE_PIECE_BITS (KB_PIECE_BITS < 14 ? KB_PIECE_BITS : 14)
20#endif
21#define KB_MIN_PIECE_BITS \
22 (KB_IMAGE_PIECE_BITS < KB_PIECE_BITS ? KB_IMAGE_PIECE_BITS : KB_PIECE_BITS)
23/* read-only pieces of images and file mappings as the file's own pages,
24 * shared between processes; off by default (a fork child maps each again).
25 * off, they are private pieces read from the file on first touch */
26#ifndef KB_SHARE
27 #define KB_SHARE 0
28#endif
29/* a mapping of at most this many bytes made by kb_map is one block (a single
30 * piece, bits KB_FLAT_BITS), so a lifted region can hold its bounds in locals
31 * (kb_flat_open); 0 (default): every mapping is in pieces. A flat mapping that
32 * grows past it goes back to pieces */
33#ifndef KB_FLAT
34 #define KB_FLAT 0
35#endif
36#define KB_FLAT_BITS 63
37/* the most bytes kb_buf copies for a range across pieces */
38#define KB_BUF_MAX (64u << 10)
39
40/* 0 (default): every load and store checks its cache's mapping generation,
41 * every block link its code generation, every back edge and syscall for a
42 * signal. -DKB_EPOCH=1: a block checks kb_epoch once when it starts, and what
43 * an epoch covers (mapping generation, code generation, signal state) is looked
44 * at only after one changed; a load or store checks its range alone (off until
45 * timed under V8) */
46#ifndef KB_EPOCH
47 #define KB_EPOCH 0
48#endif
49
50/* -DKB_PROFILE keeps the interpreter's hot helpers out of line, so a profile
51 * can attribute their time */
52#ifdef KB_PROFILE
53 #define KB_NOINLINE __attribute__((noinline))
54#else
55 #define KB_NOINLINE
56#endif
57
58enum kb_arch
59{
60 KB_X86 = 0,
61 KB_A64 = 1,
62 KB_WASM = 2
63};
64
65/* AArch64 handlers without SA_RESTORER return here (the kernel's vDSO
66 * sigreturn: mov x8, #139; svc #0), a page elf.c maps above the stack */
67#define KB_A64_SIGTRAMP 0x7ffffff00000ull
68
69/* registers: guest 0..31 (x86 rax..r15 at 0..15, AArch64 x0..x30 and sp at 31),
70 * temps from 32 */
71enum
72{
73 KB_T0 = 32,
74 KB_SINK = 62, /* writes to KB_ZERO land here instead */
75 KB_ZERO = 63, /* always 0: AArch64's xzr reads here */
76 KB_NREGS = 64
77};
78
79enum kb_op
80{
81 KB_MOVI, /* a = imm */
82 KB_MOV, /* a = b */
83 KB_ADD, /* a = b op c, all 64 bits; decoders truncate with ZEXT/SEXT */
84 KB_SUB,
85 KB_AND,
86 KB_OR,
87 KB_XOR,
88 KB_SHL, /* shift counts are masked by the decoder */
89 KB_SHR,
90 KB_SAR,
91 KB_ROR,
92 KB_MUL,
93 KB_UMULH,
94 KB_SMULH,
95 KB_UDIV, /* the decoder guards a zero divisor */
96 KB_SDIV,
97 KB_UREM,
98 KB_SREM,
99 KB_ZEXT, /* a = low w bytes of b */
100 KB_SEXT,
101 KB_INS, /* a's bits [imm, imm + 8w) = low bits of b */
102 KB_LD, /* a = mem[b + imm], w bytes, zero-extended */
103 KB_LDS, /* sign-extended */
104 KB_ST, /* mem[b + imm] = low w bytes of a */
105 KB_FLAGS, /* flags from (kind imm, operands b and c, result a, width w) */
106 KB_SETCC, /* a = cond imm */
107 KB_SEL, /* a = cond imm ? b : c */
108 KB_BR, /* if cond imm, leave to target; the block's end gives the other way
109 */
110 KB_JMP, /* leave to b (a register) */
111 KB_SYSCALL,
112 KB_TRAP, /* an instruction the decoder does not know: imm is its first byte
113 or word */
114 KB_CARRY, /* a = the carry flag (for adc and sbb) */
115 KB_BSWAP, /* a = byte-reversed b, w bytes */
116 KB_CLZ, /* a = leading zeros of b in w bytes */
117 KB_CTZ,
118 KB_TPIDR, /* a = the thread pointer (AArch64 mrs tpidr_el0) */
119 KB_X86MD, /* x86 mul/imul/div/idiv on rdx:rax by b; imm is the ModRM reg
120 field (4..7) */
121 KB_X86STR, /* x86 movs (imm 0) or stos (imm 1) of w bytes, repeated rcx
122 times when c is 1 */
123 KB_FSBASE, /* a = the x86 fs base (arch_prctl ARCH_SET_FS) */
124 KB_BRZ, /* leave to target if a is zero (imm 0) or nonzero (imm 1); flags
125 untouched */
126 KB_CCMP, /* AArch64 ccmp/ccmn of a and b; imm = cond | nzcv << 4 | ccmn << 8
127 */
128 KB_SETTP, /* the thread pointer = b (AArch64 msr tpidr_el0) */
129 KB_PC, /* a guest instruction starts at imm: where a fault inside it reports
130 */
131 KB_SSE, /* x86 SSE/SSE2: imm is (prefix << 8 | opcode) | ext << 16; see
132 sse.c */
133 KB_X86SHD, /* x86 shld (imm 0) or shrd (imm 1) of a by b, count c; sets
134 flags */
135 KB_X86FLAGS, /* imm 0: a = rflags; 1: rflags = a; 2 cmc, 3 clc, 4 stc, 5
136 cld, 6 std */
137 KB_X87, /* x87: imm = opcode << 8 | modrm, b = memory address, c = 0x80 for
138 memory; x87.c */
139 KB_POPCNT, /* a = the set bits of b's low w bytes */
140 KB_WTRAP, /* a wasm trap: imm indexes kb_wasm_traps */
141 KB_WEXIT, /* the wasm entry function returned */
142 KB_RESOLVE, /* the memory plan: group a resolves [b + imm, + 16w) once, and
143 lifted loads and stores with c = a + 1 skip their own check;
144 the interpreter skips these (run.c, step) */
145 KB_NZCV, /* a = the flags as AArch64 NZCV, bits 31..28 (mrs nzcv) */
146 KB_CRC32, /* a = the crc b updated by the low w bytes of c; imm 1 is crc32c
147 */
148 KB_CLOCK, /* a = the host's monotonic clock in ns (x86 rdtsc) */
149 KB_CPUID, /* x86 cpuid of leaf eax into eax ebx ecx edx */
150 KB_EXCL, /* AArch64 exclusives: imm 0 arms the monitor (ldxr); 1 stores c
151 at b, w bytes, if it holds, a = 0 then else 1 (stxr); 2 also
152 stores register imm >> 8 at b + w (stxp); 3 clears (clrex) */
153 KB_EXIT, /* a trace's side exit: leave, to the block's pc plus the int32 at
154 imm >> 16, if cond imm & 0xff holds (bit 8 clear), or if a is
155 zero (bit 8 set, bit 0 clear) or nonzero (both set) */
156 KB_A64V, /* AArch64 floating point, Advanced SIMD, FPCR/FPSR: imm is the
157 instruction word, b a load or store's address; a64v.c */
158 KB_PRIM /* first op of a block at the entry of a library function (imm 1
159 strlen, 2 memcmp, 3 strcmp, 4 memchr, 5 memcpy, 6 memmove, 7
160 memset, 8 exp, 9 log, 10 pow, 11 crc32, 12 adler32, 13
161 compress2, 14 uncompress): runs it as a host
162 kernel and returns to the caller, or falls through to the
163 function's own ops; also the head of cksum's loop, whose
164 kernel advances the loop's registers and runs on into the
165 block's own ops; prim.c */
166};
167
168/* semantic classes (run.c, kb_class): the plans read these, not opcodes */
169enum kb_class_bits
170{
171 KB_K_PURE = 1, /* no flags, memory, fault, control or host state */
172 KB_K_DEF = 2, /* writes register a and no other register */
173 KB_K_FLAGS_R = 4, /* reads flags */
174 KB_K_FLAGS_W = 8, /* writes flags */
175 KB_K_READ = 16, /* reads guest memory */
176 KB_K_WRITE = 32, /* writes guest memory */
177 KB_K_CONTROL = 64, /* may leave the block */
178 KB_K_FAULT = 128, /* may fault */
179 KB_K_HOST = 256, /* touches state beyond registers, flags and memory */
180 KB_K_VECTOR = 512, /* SSE or x87 */
181 KB_K_ADDRESS = 1024, /* resolves addresses (KB_RESOLVE) */
182 KB_K_CLOBBER = 2048 /* writes registers other than a */
183};
184extern const uint16_t kb_class[];
185
186/* flag kinds for KB_FLAGS */
187enum kb_fk
188{
189 KB_F_ADD,
190 KB_F_SUB,
191 KB_F_LOGIC,
192 KB_F_INC,
193 KB_F_DEC,
194 KB_F_ADC,
195 KB_F_SBB,
196 KB_F_SHL,
197 KB_F_SHR,
198 KB_F_SAR,
199 KB_F_MULOV, /* x86 mul/imul: c holds whether the high half was significant
200 */
201 KB_F_NEG,
202 KB_F_A_ADD, /* AArch64: C is the carry out, not a borrow */
203 KB_F_A_SUB,
204 KB_F_A_LOGIC,
205 KB_F_NZCV, /* b holds NZCV in bits 31..28 (ccmp, msr nzcv) */
206 KB_F_SETC, /* x86 bt: C = b, the rest unchanged */
207 KB_F_ZERO, /* x86 bsf, bsr: Z = (b == 0), the source */
208 KB_F_CNT, /* x86 tzcnt, lzcnt: C = (b == 0), the source; Z = (a == 0), the
209 count */
210 KB_F_ROL, /* x86 rol: a is the result, b the (nonzero) count */
211 KB_F_ROR
212};
213
214/* conditions: x86's 16 (o, no, b, ae, e, ne, be, a, s, ns, p, np, l, ge, le,
215 * g), then AArch64's */
216enum
217{
218 KB_C_O = 0,
219 KB_C_A64 = 16, /* eq ne cs cc mi pl vs vc hi ls ge lt gt le al nv */
220 KB_C_ALWAYS = 30
221};
222
223struct kb_ins {
224 uint8_t op;
225 uint8_t w; /* width in bytes */
226 uint8_t a, b, c;
227 int64_t imm;
228};
229
230/* the rights an access needs, as mprotect's bits (mem.c: kb_host and the rest)
231 */
232enum
233{
234 KB_R = 1,
235 KB_W = 2,
236 KB_X = 4
237};
238
241struct kb_ic {
242 uint64_t lo, span;
243 uint8_t* host;
244 uint32_t gen;
245};
246
247struct kb_cpu;
248struct kb_cmark;
249
252struct kb_block {
253 uint64_t pc, next, target;
254 int n;
255 struct kb_ins* ins;
256 struct kb_ic* ic; /* one per load or store, in op order */
257 int nic; /* how many */
258 uint32_t epoch, /* kb_epoch when the block last checked its assumptions */
259 mapgen; /* kb_cpu's when its caches were last known current */
260 uint32_t* pcs; /* each op's guest instruction, as an offset from pc, in
261 place of KB_PC ops (NULL in a trace, which keeps them) */
262 int flag_writes,
263 dropped; /* flag writes decoded, and those the plan took out */
264 int pruned; /* pure ops the demand plan took out */
265 uint32_t codegen; /* kb_cpu's when decoded or last found current; an older
266 one is checked again (run.c, current) */
267 uint32_t hardgen; /* kb_cpu's hardgen when decoded; an older one decodes
268 again */
269 int npv; /* the pages its code is on: pv[2i] is a page number and
270 pv[2i + 1] its version when the block was checked */
271 uint64_t* pv;
272 struct kb_block *to_target, *to_next; /* the successors last seen */
273 uint32_t taken, fall; /* runs that left to target, and to next */
274 int traced; /* decoded as a trace (or found not to be one) */
275 int nseg; /* the guest code decoded: seg[2i] to seg[2i + 1] */
276 uint64_t* seg;
277 uint64_t code; /* hash of those bytes when decoded, with a cache dir */
278 int hashed; /* code holds one */
279 int resolves; /* the memory plan's KB_RESOLVE ops, which lead the block */
280 struct kb_block* chain; /* the next block in its hash bucket */
281#if defined(KB_HOT) || defined(KB_COUNT)
282 uint64_t runs; /* times the interpreter ran it, for kb_hot_dump */
283#endif
284#ifdef KB_HOT
285 uint64_t* exits; /* runs that left at each KB_EXIT op, once one has */
286#endif
287#ifdef KB_COUNT
288 /* guest instructions, and the cpu struct words step() reads and writes */
289 int insns, rd, wr;
290#endif
291#ifdef KB_AOT
292 /* a region of lifted blocks this block's IR matched exactly; it runs from
293 the given pc and returns the next one */
294 uint64_t (*aot)(struct kb_cpu* cpu, uint64_t pc);
295#endif
296};
297
298/* a loaded ELF's file, kept open so a piece of its mapping is read on first
299 * touch (mem.c). The descriptor is katybug's own, below 1024 and close-on-exec,
300 * so a fork's exec carries it at the same number */
301#define KB_IMAGES 2
302#define KB_IMAGE_SEGS 8
303struct kb_seg {
304 uint64_t va, off, len; /* the file's [off, off + len) is at va */
305 int ro; /* the segment is not writable */
306};
307struct kb_image {
308 int fd, hdr_ok;
309 uint64_t dev, ino;
310 uint64_t start; /* where the first segment's page, and the header, sit */
311 uint8_t hdr[64];
312 int nseg;
313 struct kb_seg seg[KB_IMAGE_SEGS];
314};
315
316/* a guest's private file mapping read the same way: one entry per mapping,
317 * the descriptor shared by the entries of one file */
318#define KB_FILES 32
319struct kb_file {
320 int fd;
321 uint64_t dev, ino;
322 struct kb_seg seg;
323};
324
326 uint64_t start, end;
327 uint8_t** pieces; /* mappings never overlap; each owns its pieces (mem.c),
328 which are NULL until touched; the low bit of a
329 pointer marks a read-only piece of an image's file
330 (kb_shared), that the first write replaces by a copy */
331 int prot;
332 uint8_t image; /* 1 + the kb_cpu.images entry that fills a piece when it is
333 made, KB_IMAGES + 1 + the kb_cpu.files entry for a file
334 mapping, 0 for none; a split keeps it, a mapping that
335 replaces part of one starts at 0 */
336 uint8_t bits; /* a piece is 1 << bits bytes; a split keeps it */
337};
338
340 uint64_t handler, flags, restorer, mask;
341};
342
349struct kb_cpu {
350 uint64_t r[KB_NREGS];
351 uint64_t pc;
352 uint64_t fs, tpidr;
353 /* flags, kept as bits: N (sign), Z, C (the producing architecture's carry),
354 * V, P (x86 parity) */
355 int n, z, c, v, p;
356 /* K17: 1 + the kind of a flag write not yet made into the bits above,
357 * with its operands (run.c kb_flags_sync makes it) */
358 int lz, lz_w;
359 uint64_t lz_b, lz_c, lz_r;
360 int df; /* x86 direction flag: string ops go down when set */
361 int arch;
362 int exited, status;
363 struct kb_mapping
364 maps[1024]; /* later ones cover earlier ones where they overlap */
365 int nmaps;
366 struct kb_image images[KB_IMAGES];
367 int nimages;
368 struct kb_file files[KB_FILES];
369 int nfiles;
370 uint64_t image_total, /* pieces the image mappings had when loaded */
371 image_filled; /* pieces made from an image's file */
372 uint32_t mapgen; /* bumped by every change to maps, which makes older kb_ic
373 entries stale */
374 struct {
375 uint64_t lo, end, tab;
376 uint32_t gen;
377 } ckno; /* the cksum loop declined at lo up to end over tab while mapgen
378 was gen (prim.c) */
379 uint32_t codegen; /* bumped when executable code is unmapped, changes
380 protection or is written, which makes older blocks
381 stale until found current again */
382 uint32_t hardgen; /* the part of those that decodes every block again: an
383 unmap or a protection change (not a write) */
384 struct kb_cmark* marks; /* the code written pages hold, 16 bytes at a time
385 (mem.c) */
386 uint32_t nmarks, capmarks;
387 uint64_t wver; /* the last version a marked page was given */
388 uint64_t brk_start, brk_end, mmap_next;
389 struct kb_block* cache[4096];
390 const char* fault;
391 const char* last_fault; /* why the last fault happened, for KATYBUG_DEBUG */
392 uint64_t steps;
393 int noplan; /* KATYBUG_PLAN=0: blocks run as decoded */
394 uint64_t plan_flags,
395 plan_flags_removed; /* flag writes decoded, and dropped as unread */
396 uint64_t plan_flags_run,
397 plan_flags_ran; /* of those, as executed: dropped, and all */
398 uint64_t plan_mem,
399 plan_mem_grouped; /* accesses decoded, and those a KB_RESOLVE covers */
400 uint64_t plan_ops, plan_ops_removed; /* pure ops decoded, and dropped */
401 int tracing; /* the decoders build a trace */
402 int segments; /* a trace's most segments (KB_TRACE, KATYBUG_SEGMENTS) */
403 uint64_t decoded, loaded; /* blocks decoded, and taken from the cache */
404 uint64_t lookups; /* blocks found through the block cache */
405 void* persist; /* persist.c's records, when loaded */
406 uint64_t traces, trace_exits; /* traces built, side exits taken */
407 uint64_t plan_ops_run, plan_ops_ran; /* as executed: dropped, and all run */
408 uint64_t ipc; /* the current guest instruction */
409 uint64_t x[32][2]; /* x86 xmm0-15; AArch64 v0-31 */
410 uint32_t fpcr, fpsr; /* AArch64 */
411 uint32_t mxcsr; /* x86, kept for stmxcsr and fxsave; SSE rounds to
412 nearest whatever it holds */
413 uint64_t excl; /* AArch64's exclusive monitor: kb_switches at the
414 last ldxr, ~0 when clear */
415 f80 st[8]; /* the x87 stack, st(i) = st[(top + i) & 7] */
416 int top;
417 uint8_t ftag; /* the x87 registers holding a value */
418 uint16_t fcw,
419 fcc; /* the control word, and the status word's condition codes */
420 FILE*
421 trace; /* KATYBUG_TRACE: each guest instruction's address, as it runs */
422 struct kb_sigaction sig[65];
423 uint64_t sigmask;
424 uint64_t saved_mask; /* rt_sigsuspend's caller mask, restored by the next
425 delivery's frame */
426 int restore_mask;
427 int fault_sig, fault_code, sigreturned;
428 int segv_code; /* the si_code a pending SIGSEGV carries, 0 for the default
429 */
430 uint64_t fault_addr;
431};
432
433/* mem.c: a host pointer for guest memory comes in three kinds, and each is
434 * NULL for a byte whose mapping lacks the right (KB_R: readable, which a
435 * writable page is too; KB_W; KB_X). The plain one (kb_host, kb_span, kb_buf,
436 * kb_iov, kb_piece) is for bytes the caller may write: a read-only piece of an
437 * image is copied first, and a write to bytes that decoded blocks came from
438 * makes them decode again. The _r one is for bytes only read, and may point
439 * into the image's file. The _x one is for an instruction fetch. kb_span's *len
440 * is the most bytes the caller means to write, and comes back as the bytes left
441 * in the piece (the _r and _x ones only give the second) */
442uint8_t* kb_host(struct kb_cpu* cpu, uint64_t va, uint64_t len);
443const uint8_t* kb_host_r(struct kb_cpu* cpu, uint64_t va, uint64_t len);
444const uint8_t* kb_host_x(struct kb_cpu* cpu, uint64_t va, uint64_t len);
445uint8_t* kb_span(struct kb_cpu* cpu, uint64_t va, uint64_t* len);
446const uint8_t* kb_span_r(struct kb_cpu* cpu, uint64_t va, uint64_t* len);
447const uint8_t* kb_span_x(struct kb_cpu* cpu, uint64_t va, uint64_t* len);
448uint8_t* kb_buf(struct kb_cpu* cpu, uint64_t va, uint64_t len);
449const uint8_t* kb_buf_r(struct kb_cpu* cpu, uint64_t va, uint64_t len);
450void kb_flush(struct kb_cpu* cpu);
451int kb_read(struct kb_cpu* cpu, uint64_t va, void* dst, uint64_t len);
452int kb_write(struct kb_cpu* cpu, uint64_t va, const void* src, uint64_t len);
453/* the one write that skips the rights check, for what Linux writes whatever the
454 * page allows (the loader's stack and trampoline, a syscall's buffer written
455 * back after the call checked it); decoded code under it still goes stale */
456int kb_poke(struct kb_cpu* cpu, uint64_t va, const void* src, uint64_t len);
457/* every byte of [va, va + len) is in a mapping that gives acc */
458int kb_can(struct kb_cpu* cpu, uint64_t va, uint64_t len, int acc);
459/* the si_code of a refused access at va: 2 (SEGV_ACCERR) in a mapping, 4
460 * (SEGV_PKUERR) for data on an x86 execute-only page, 1 (SEGV_MAPERR) in a hole
461 */
462int kb_fault_code(const struct kb_cpu* cpu, uint64_t va);
463/* a block's code is marked, so a write to it is seen; the block is found
464 * current (1) or not (0) after writes to code since it was checked */
465void kb_marks_add(struct kb_cpu* cpu, struct kb_block* b);
466int kb_marks_current(struct kb_cpu* cpu, struct kb_block* b);
467int kb_iov(
468 struct kb_cpu* cpu, uint64_t va, uint64_t len, struct iovec* iov, int max
469);
470int kb_iov_r(
471 struct kb_cpu* cpu, uint64_t va, uint64_t len, struct iovec* iov, int max
472);
473uint64_t kb_pieces(uint64_t start, uint64_t end, int bits);
474uint64_t kb_piece_va(const struct kb_mapping* m, uint64_t k);
475uint8_t* kb_piece(
476 struct kb_cpu* cpu, struct kb_mapping* m, uint64_t va, uint64_t* lo,
477 uint64_t* hi
478);
479const uint8_t* kb_piece_r(
480 struct kb_cpu* cpu, struct kb_mapping* m, uint64_t va, uint64_t* lo,
481 uint64_t* hi
482);
483int kb_adopt(struct kb_cpu* cpu, struct kb_mapping* m, uint64_t k);
484int kb_file_map(
485 struct kb_cpu* cpu, struct kb_mapping* m, int fd, uint64_t off, int prot
486);
487
488static inline int kb_shared(const uint8_t* p) {
489 return (int) ((uintptr_t) p & 1);
490}
491int kb_bus(uint64_t va);
492uint8_t* kb_piece_blank(
493 struct kb_mapping* m, uint64_t va, uint64_t* lo, uint64_t* hi
494);
495int kb_image_header(
496 const struct kb_cpu* cpu, const struct kb_mapping* m, uint8_t out[64]
497);
498void kb_image_report(const struct kb_cpu* cpu);
499int kb_grow(struct kb_cpu* cpu, struct kb_mapping* m, uint64_t end);
500
501/* prim.c: string functions as host kernels (KATYBUG_PRIM=0 turns them off,
502 * KATYBUG_PRIM=memcmp,strlen keeps only those); the mask has bit i for
503 * function i */
504uint64_t kb_prim_enabled(void);
505/* hash.c: n blocks of 64 bytes (128 for sha512) into a hash's state words */
506void kb_sha256_blocks(uint32_t st[8], const uint8_t* p, size_t n);
507void kb_sha1_blocks(uint32_t st[5], const uint8_t* p, size_t n);
508void kb_md5_blocks(uint32_t st[4], const uint8_t* p, size_t n);
509void kb_sha512_blocks(uint64_t st[8], const uint8_t* p, size_t n);
510uint32_t kb_cksum_blocks(
511 uint32_t crc, const uint8_t* tab, const uint8_t* p, size_t n
512);
513int kb_cksum_canon(const uint8_t* tab);
514uint32_t kb_cksum_fast(uint32_t crc, const uint8_t* p, size_t n);
515const char* kb_cksum_path(void);
516/* digest.c: a coreutils stream's whole digest on the host's crypto; prim.c's
517 * block kernel stays the path for anything not proven private */
518enum
519{
520 KB_HD_MD5,
521 KB_HD_SHA1,
522 KB_HD_SHA256,
523 KB_HD_SHA512,
524 KB_HD_SHA224, /* the sha256 and sha512 block functions, their own init and
525 finish */
526 KB_HD_SHA384,
527 KB_HD_B2, /* blake2b of 64 bytes: no block function, its update function */
528 KB_HD_N
529};
530/* in the mode of a P_DIGEST function: an update function, not a finish */
531enum
532{
533 KB_HD_UPDATE = 32
534};
535int kb_digest_ready(void);
536int kb_digest_at(struct kb_cpu* cpu, uint64_t pc);
537int kb_digest_update_at(struct kb_cpu* cpu, uint64_t pc);
538int kb_digest_update(
539 struct kb_cpu* cpu, int alg, uint64_t ctx, uint64_t buf, uint64_t len
540);
541int kb_digest_block(
542 struct kb_cpu* cpu, int alg, uint64_t buf, uint64_t len, uint64_t ctx
543);
544int kb_digest_finish(struct kb_cpu* cpu, int alg, uint64_t ctx, uint64_t res);
545void kb_blake2b_compress(
546 uint64_t h[8], const uint8_t blk[128], const uint64_t t[2],
547 const uint64_t f[2]
548);
549/* a fork by exec hands each open digest to the child as bytes that the child's
550 * adopt claims under a ticket (the native test double sends its state in them)
551 */
552int kb_digest_save(uint8_t* out);
553void kb_digest_adopt(const uint8_t* in, int len);
554/* inflate.c: a gzip member's deflate stream on the host's zlib, found by the
555 * bytes of the static GNU gzip's inflate; kb_gzcrc is the crc loop its
556 * flush_window carries */
557int kb_inflate_ready(void);
558int kb_inflate_at(struct kb_cpu* cpu, uint64_t pc);
559int kb_inflate_admit(struct kb_cpu* cpu, int id, int mode);
560int kb_inflate(struct kb_cpu* cpu, uint64_t* next);
561int kb_gzcrc(struct kb_cpu* cpu);
562/* thunk.c: library calls found by the name a loaded object imports them under;
563 * the ids are prim.c's */
564enum
565{
566 KB_THUNK_STRLEN = 1,
567 KB_THUNK_MEMCMP,
568 KB_THUNK_STRCMP,
569 KB_THUNK_MEMCHR,
570 KB_THUNK_MEMCPY,
571 KB_THUNK_MEMMOVE,
572 KB_THUNK_MEMSET,
573 KB_THUNK_EXP,
574 KB_THUNK_LOG,
575 KB_THUNK_POW,
576 KB_THUNK_CRC32,
577 KB_THUNK_ADLER32,
578 KB_THUNK_COMPRESS2,
579 KB_THUNK_UNCOMPRESS,
580 KB_THUNK_ZS, /* KB_ZS_N stream entries from here (zstream.c's order) */
581 KB_THUNK_ZPOISON = 0x7f /* an import of one that cannot be served */
582};
583#define KB_ZS_N 31
584extern const char* const kb_zs_name[KB_ZS_N];
585int kb_thunk_at(struct kb_cpu* cpu, uint64_t pc);
586/* a stream init called from caller may be taken: that object imports the
587 * life cycle (deflate and deflateEnd, or inflate and inflateEnd) and no object
588 * imports an entry the stream mirror cannot serve */
589int kb_thunk_zok(struct kb_cpu* cpu, uint64_t caller, int inflate);
590/* zstream.c: entry e (0..KB_ZS_N-1) of a guest z_stream whose libz is version
591 * ver of prim.c's list of stock zlib versions: 0 gives up with nothing changed,
592 * 1 ran (*v is the return value), 2 raised a guest fault. KB_ZV_RESET_CLEARS
593 * is the index of the first version whose inflateReset clears data_type */
594#define KB_ZV_RESET_CLEARS 4
595int kb_zs(struct kb_cpu* cpu, int e, int ver, uint64_t* v);
596void kb_zs_report(FILE* f);
597/* the loaded ELF object that holds pc, as the span it maps, or 0 */
598int kb_thunk_object(
599 struct kb_cpu* cpu, uint64_t pc, uint64_t* lo, uint64_t* hi
600);
601/* prim.c's table: one row for each recognizer, whatever kind it is. identify
602 * says whether the code at pc is this row's (its id in the low byte, its mode
603 * above), by the bytes of the code, the name a loaded object imports it under
604 * or both; admit is the proof a row that keeps state needs before its run
605 * (none for a stateless row); run returns the one convention below. fx is where
606 * a row's state lives, and fork what a guest fork by exec does with it: save
607 * and adopt carry it to the child (KB_FORK_COPY), the child's guest meets the
608 * library's own error (KB_FORK_LOST) or the child ends at its next call
609 * (KB_FORK_ENDS) */
610enum
611{
612 KB_GAVE_UP, /* nothing changed: the guest's own code runs */
613 KB_SKIPPED, /* the same, a decline remembered from an earlier call */
614 KB_RAN, /* the call is done: *next is where it returns */
615 KB_RAN_ON, /* registers advanced: the block's own ops run on */
616 KB_RESUMED /* a call that came back from the guest's own code: *next is set
617 */
618};
619enum
620{
621 KB_FX_NONE, /* no state: guest memory only, every range checked first */
622 KB_FX_PROCESS, /* state in this process's memory: a checkpoint keeps it */
623 KB_FX_HOST /* state in the host: the machine refuses a checkpoint */
624};
625enum
626{
627 KB_FORK_NONE,
628 KB_FORK_COPY,
629 KB_FORK_LOST,
630 KB_FORK_ENDS
631};
632#define KB_ANY_ARCH (-1)
634 const char* name; /* the name KATYBUG_PRIM takes */
635 int8_t arch; /* KB_X86, KB_A64 or KB_ANY_ARCH */
636 uint8_t fx, fork;
637 int (*identify)(struct kb_cpu* cpu, uint64_t pc, int id);
638 int (*admit)(struct kb_cpu* cpu, int id, int mode);
639 int (*run)(struct kb_cpu* cpu, int id, int mode, uint64_t* next);
640 int (*save)(uint8_t* out);
641 void (*adopt)(const uint8_t* in, int len);
642};
643const struct kb_prim_row* kb_prim_row(int id);
644int kb_prim_rows(void);
645const char* kb_prim_name(int id);
646/* the id of the library entry a loaded object imports under name, or 0 */
647int kb_prim_thunk_id(const char* name);
648/* the most bytes every row's save writes in all, and the child's claim */
649#define KB_PRIM_STATE_MAX 4096
650int kb_prim_save(uint8_t* out);
651void kb_prim_adopt(const uint8_t* in, int len);
652int kb_prim_at(struct kb_cpu* cpu, uint64_t pc);
653/* 1: the call was done and *next is where it returns, 0: the block's own ops
654 * run */
655int kb_prim(struct kb_cpu* cpu, int id, uint64_t* next);
656void kb_prim_report(void);
657/* the identity helpers the recognizers share: FNV-1a over bytes, whether the
658 * len bytes at pc hash to hash, an end that no guest code can catch, and the
659 * mark a stream puts in its state so a copy of it is told from the state it
660 * began as */
661#define KB_FNV0 0xcbf29ce484222325ull
662uint64_t kb_fnv(uint64_t h, const uint8_t* p, size_t n);
663int kb_fnv_at(struct kb_cpu* cpu, uint64_t pc, uint32_t len, uint64_t* h);
664int kb_code_is(struct kb_cpu* cpu, uint64_t pc, uint32_t len, uint64_t hash);
665void kb_die(const char* what);
666uint64_t kb_mark(void);
667int kb_marked(uint64_t m);
668void kb_decode_report(const struct kb_cpu* cpu);
669/* a window for a KB_RESOLVE group: kb_host_ic checks no rights and always
670 * keeps its cache (a lifted region's, which is never attached to code on a page
671 * that is writable too); kb_host_ic_at checks the rights acc names, and keeps
672 * no cache for a write to a page that is both writable and executable */
673uint8_t* kb_host_ic(
674 struct kb_cpu* cpu, struct kb_ic* ic, uint64_t va, uint64_t len
675);
676uint8_t* kb_host_ic_at(
677 struct kb_cpu* cpu, struct kb_ic* ic, uint64_t va, uint64_t len, int acc
678);
679struct kb_mapping* kb_map(
680 struct kb_cpu* cpu, uint64_t start, uint64_t len, int prot
681);
682struct kb_mapping* kb_map_bits(
683 struct kb_cpu* cpu, uint64_t start, uint64_t len, int prot, int bits
684);
685/* the flat mapping holding hint, as a lifted region's fast path wants it: its
686 * first address in *lo, in *lim how many bytes from it an access of up to 16
687 * may start (0 for none), and its block in *host. lim is 0 when hint is in no
688 * mapping, in one that is not flat, or in one without the rights acc needs
689 * (KB_W: also not when it is executable) */
690void kb_flat_open(
691 struct kb_cpu* cpu, uint64_t hint, int acc, uint64_t* lo, uint64_t* lim,
692 uint8_t** host
693);
694int kb_unmap(struct kb_cpu* cpu, uint64_t start, uint64_t len);
695int kb_protect(struct kb_cpu* cpu, uint64_t start, uint64_t len, int prot);
696uint64_t kb_free_at(struct kb_cpu* cpu, uint64_t at, uint64_t len);
697uint64_t kb_load(struct kb_cpu* cpu, uint64_t va, int w);
698void kb_store(struct kb_cpu* cpu, uint64_t va, uint64_t v, int w);
699uint64_t kb_load_ic(struct kb_cpu* cpu, struct kb_ic* ic, uint64_t va, int w);
700void kb_store_ic(
701 struct kb_cpu* cpu, struct kb_ic* ic, uint64_t va, uint64_t v, int w
702);
703/* kb_store_ic for the interpreter: a store to bytes a decoded block came from
704 * leaves kb_smc in cpu->fault (not a fault: the instruction ends and the code
705 * after it is looked up again) */
706extern const char kb_smc[];
707void kb_store_smc(
708 struct kb_cpu* cpu, struct kb_ic* ic, uint64_t va, uint64_t v, int w
709);
710
711/* x86.c, a64.c: decode the block at pc; 0 on success */
712int kb_x86_block(struct kb_cpu* cpu, struct kb_block* b);
713int kb_a64_block(struct kb_cpu* cpu, struct kb_block* b);
714
715/* wasm.c: a wasm module's functions, decoded to the IR; kb_wasm_main runs
716 * --wasm */
717int kb_wasm_block(struct kb_cpu* cpu, struct kb_block* b);
718int kb_wasm_load(struct kb_cpu* cpu, const char* path);
719int kb_wasm_main(struct kb_cpu* cpu, int argc, char** argv);
720extern const char* kb_wasm_traps[];
721
722/* run.c: moves on whenever a mapping, executable code or the signal state
723 * changes, from a signal handler too, so the bump is one atomic add */
724extern volatile uint32_t kb_epoch;
725#define KB_BUMP() ((void) __atomic_fetch_add(&kb_epoch, 1, __ATOMIC_RELAXED))
726
727/* run.c */
728int kb_cond(struct kb_cpu* cpu, int cond);
729/* the flag bits made current before anything reads or writes them directly */
730void kb_flags_sync(struct kb_cpu* cpu);
731#define KB_SYNC(cpu) \
732 do { \
733 if ((cpu)->lz) kb_flags_sync(cpu); \
734 } while (0)
735/* -DKB_LAZY: 0 eager flags, 1 recorded and made when read, 2 conditions from
736 * the record */
737#ifndef KB_LAZY
738 #define KB_LAZY 2
739#endif
740int kb_run(struct kb_cpu* cpu);
741/* -DKB_POLL picks where pending signals are looked for: 2 (default) back-edges
742 * and after a syscall; 0 every block, 1 back-edges only, 3 every KB_POLL_FUEL
743 * blocks (lifted: block transitions); 1 and 3 miss signals, arms only. The
744 * interpreter ignores it under KB_EPOCH, where the epoch guard polls */
745#ifndef KB_POLL
746 #define KB_POLL 2
747#endif
748#ifndef KB_POLL_FUEL
749 #define KB_POLL_FUEL 64
750#endif
751#if KB_POLL == 2
752extern int kb_syscalled;
753#endif
754#ifdef KB_HOT
755/* KATYBUG_HOT=<dir>: every block the interpreter ran, with its IR and run
756 * count, to <dir>/<pid>.hot */
757void kb_hot_dump(struct kb_cpu* cpu);
758#endif
759#ifdef KB_COUNT
760/* -DKB_COUNT with KATYBUG_COUNT=<file>: guest-state traffic and mapping checks,
761 * appended to the file at exit (lifted regions add theirs through aot.h) */
762struct kb_count {
763 uint64_t rd, wr, refills, entries;
764 uint64_t lat_n, lat_sum,
765 lat_max; /* host signal to the poll that sees it, ns */
766 uint64_t sys[512]; /* syscalls by the guest's own number */
767 uint64_t cat[10][2]; /* lifted code's cpu words read and written, by aot.h's
768 AOT_C_ category */
769 /* the interpreter's checks, as run: a load or store's generation and range
770 * compares, a block link's code generation, the signal poll's tests, the
771 * thread and fault tests, the link and exit tests, the epoch compare and
772 * what it found changed (deopts), signal polls made */
773 uint64_t ck_gen, ck_range, ck_code, ck_poll, ck_thread, ck_fault, ck_link,
774 ck_exit, ck_epoch, deopt_map, deopt_code, polls;
775 /* state the guest reads that a later epoch would cover: fs base reads,
776 cpuid, indirect jumps and trace side exits taken or not */
777 uint64_t rd_fs, rd_cpuid, ijmp, exits;
778 uint64_t bump_map, bump_sig;
779};
780extern struct kb_count kb_count;
781void kb_count_report(struct kb_cpu* cpu);
782 #define KB_BUMP_AS(kind) (kb_count.bump_##kind++, KB_BUMP())
783#else
784 #define KB_BUMP_AS(kind) KB_BUMP()
785#endif
786#ifdef KB_AOT
787/* the lifted blocks (generated, see experiments/aot-oracle): attaches a region
788 * to a block whose IR matches one exactly */
789void kb_aot_attach(struct kb_cpu* cpu, struct kb_block* b);
790void kb_aot_detach(struct kb_block* b);
791void kb_aot_stale(struct kb_cpu* cpu);
792int kb_block_wx(struct kb_cpu* cpu, const struct kb_block* b);
793void kb_aot_string(struct kb_cpu* cpu, int stos, int w, int rep);
794extern volatile int* kb_pending_flag;
795#endif
796
797/* elf.c */
798int kb_load_elf(
799 struct kb_cpu* cpu, const char* path, int argc, char** argv, char** envp
800);
801
802/* main.c: the path this katybug was started from, for a guest's execve of a
803 * foreign ELF */
804extern const char* kb_self;
805
806/* sys.c: the guest's syscall, with its number and arguments in guest registers
807 */
808void kb_syscall(struct kb_cpu* cpu);
809int64_t kb_err(int e);
810char* kb_str(struct kb_cpu* cpu, uint64_t va);
811
812/* sys.c: guest descriptors are the host's, so katybug's own live at the top of
813 * the table where the guest does not look; kb_log is where its diagnostics go
814 * (a private copy of stderr, so a guest that closes fd 2 does not silence it),
815 * and kb_own_fd copies a descriptor up there. A descriptor the host just made
816 * for the guest goes through kb_newfd (EMFILE at the guest's soft limit), and
817 * one at or past the base is kb_past_limit (EBADF) */
818extern FILE* kb_log;
819void kb_log_init(int resumed);
820int kb_own_fd(int fd);
821int kb_keep_fd(int fd);
822FILE* kb_own_fopen(const char* path, const char* mode);
823int kb_past_limit(int fd);
824int64_t kb_newfd(int fd);
825int64_t kb_newfd2(int* fds);
826void kb_nofile_get(uint64_t out[2]);
827void kb_nofile_set(const uint64_t in[2]);
828
829/* fork.c: fork by exec of katybug and a state transfer, where the host cannot
830 * fork (wasm) */
831int kb_fork_by_exec(void);
832int64_t kb_fork(struct kb_cpu* cpu);
833int kb_resume(struct kb_cpu* cpu, int fd);
834
835/* net.c: the socket, poll and select syscalls (generic numbers); -38 for others
836 */
837int64_t kb_net(struct kb_cpu* cpu, int64_t nr, const uint64_t* a);
838
839/* sse.c: one SSE instruction; a = the ModRM reg field, c = the r/m register
840 (0x80 when memory at TA), b = the GPR/temp holding a memory operand's
841 address, w = REX.W, imm as in KB_SSE */
842int kb_sse(struct kb_cpu* cpu, const struct kb_ins* x);
843int kb_x87(struct kb_cpu* cpu, const struct kb_ins* x);
844/* a64v.c: one AArch64 FP/SIMD instruction, as KB_A64V; nonzero when unknown */
845int kb_a64v(struct kb_cpu* cpu, const struct kb_ins* x);
846
847/* sig.c */
848int64_t kb_sigaction(struct kb_cpu* cpu, int s, uint64_t act, uint64_t old);
849int64_t kb_sigprocmask(struct kb_cpu* cpu, int how, uint64_t set, uint64_t old);
850void kb_raise(struct kb_cpu* cpu, int s, int code);
851void kb_sigreturn(struct kb_cpu* cpu);
852int kb_restart(struct kb_cpu* cpu, int restartable);
853void kb_fxsave(struct kb_cpu* cpu, uint64_t at);
854void kb_fxrstor(struct kb_cpu* cpu, uint64_t at);
855void kb_signals(struct kb_cpu* cpu);
856int kb_fault(struct kb_cpu* cpu, int s, int code, uint64_t addr);
857int kb_host_sig(int s);
858int64_t kb_sigsuspend(struct kb_cpu* cpu, uint64_t mask);
859void kb_sig_reinstall(struct kb_cpu* cpu);
860void kb_sig_inherit(struct kb_cpu* cpu);
861int64_t kb_sigpending(struct kb_cpu* cpu, uint64_t set);
862int64_t kb_timer(struct kb_cpu* cpu, int64_t nr, const uint64_t* a);
863
864/* thread.c: guest threads, green, inside this one process; kb_cpu holds the
865 * running one's state */
866extern int kb_nthreads;
867extern uint64_t kb_switches;
868extern volatile int* kb_pending_flag; /* sig.c: a signal waits */
869/* a call's result when another thread now runs */
870#define KB_SWITCHED INT64_MIN
871#define KB_SLICE 16384 /* back edges one thread runs before the next's turn */
872int64_t kb_thread_clone(struct kb_cpu* cpu, const uint64_t* a);
873int kb_thread_exit(struct kb_cpu* cpu);
874int64_t kb_gettid(void);
875int64_t kb_futex(struct kb_cpu* cpu, const uint64_t* a);
876void kb_yield(struct kb_cpu* cpu);
877int kb_thread_gate(
878 struct kb_cpu* cpu, int64_t nr, const uint64_t* a, int64_t* v
879);
880void kb_thread_forked(void);
881void kb_thread_called(void);
882
883/* a growing op list for decoders */
884struct kb_emit {
885 struct kb_ins* ins;
886 int n, cap;
887};
888void kb_put(struct kb_emit* e, int op, int w, int a, int b, int c, int64_t imm);
889
890/* block fusion (run.c): a block runs on through up to KB_FUSE_MAX direct
891 * jumps; -DKB_FUSE=0 ends every block at its first */
892#ifndef KB_FUSE
893 #define KB_FUSE 1
894#endif
895#define KB_FUSE_MAX 4
896/* -DKB_CHAIN=0: every block looked up in the cache instead of through its
897 * predecessor's link (run.c next_block) */
898#ifndef KB_CHAIN
899 #define KB_CHAIN 1
900#endif
901/* traces: a block run KB_TRACE_AT times is decoded again on through the hot
902 * side of its biased branches, up to KB_TRACE segments by default
903 * (KATYBUG_SEGMENTS=n sets 1 to KB_SEGS - 1); -DKB_TRACE=1 compiles them out */
904#ifndef KB_TRACE
905 #define KB_TRACE 32
906#endif
907#define KB_TRACE_AT 64
908#define KB_SEGS 65
909struct kb_fuse {
910 struct kb_cpu* cpu;
911 int trace; /* decoding a trace */
912 int n, jumps; /* segments after the first; jumps fused */
913 uint64_t head; /* where the block ending here alone starts */
914 uint64_t lo[KB_SEGS], hi[KB_SEGS]; /* code the block holds */
915};
916int kb_fuse(
917 struct kb_emit* e, const struct kb_block* b, struct kb_fuse* f,
918 uint64_t end, uint64_t* at
919);
920/* the block keeps the code ranges f saw, the last ending at end */
921void kb_fuse_done(struct kb_block* b, struct kb_fuse* f, uint64_t end);
922
923/* persist.c: decoded blocks kept across processes under KATYBUG_CACHE */
924void kb_persist_load(struct kb_cpu* cpu, const char* elf);
925int kb_persist_take(struct kb_cpu* cpu, struct kb_block* b);
926void kb_persist_save(struct kb_cpu* cpu);
927uint8_t* kb_persist_pack(
928 struct kb_cpu* cpu, size_t* n, int (*want)(uint64_t pc)
929);
930void kb_persist_adopt(struct kb_cpu* cpu, uint8_t* blob, size_t n);
931uint64_t kb_code_hash(struct kb_cpu* cpu, const struct kb_block* b, int* ok);
932int kb_block_ready(struct kb_cpu* cpu, struct kb_block* b);
933
934#endif
Definition f80.h:8
Definition persist.c:91
Definition kb.h:252
Definition mem.c:149
Definition kb.h:349
Definition kb.h:884
Definition kb.h:319
Definition kb.h:909
Definition kb.h:241
Definition kb.h:307
Definition kb.h:223
Definition kb.h:325
Definition kb.h:633
Definition kb.h:303
Definition kb.h:339