• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

nickg / nvc / 6709062420

31 Oct 2023 04:04PM UTC coverage: 91.262% (+0.01%) from 91.249%
6709062420

push

github

nickg
Add specialised exit handler for 'last_event

33 of 33 new or added lines in 3 files covered. (100.0%)

49769 of 54534 relevant lines covered (91.26%)

598003.15 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

72.14
/src/jit/jit-code.c
1
//
2
//  Copyright (C) 2022-2023  Nick Gasson
3
//
4
//  This program is free software: you can redistribute it and/or modify
5
//  it under the terms of the GNU General Public License as published by
6
//  the Free Software Foundation, either version 3 of the License, or
7
//  (at your option) any later version.
8
//
9
//  This program is distributed in the hope that it will be useful,
10
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
11
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
//  GNU General Public License for more details.
13
//
14
//  You should have received a copy of the GNU General Public License
15
//  along with this program.  If not, see <http://www.gnu.org/licenses/>.
16
//
17

18
#include "util.h"
19
#include "cpustate.h"
20
#include "debug.h"
21
#include "hash.h"
22
#include "ident.h"
23
#include "jit/jit-priv.h"
24
#include "option.h"
25
#include "thread.h"
26

27
#include <assert.h>
28
#include <stdlib.h>
29
#include <string.h>
30
#include <stdio.h>
31
#include <unistd.h>
32
#include <inttypes.h>
33

34
#if defined __MINGW32__
35
#include <winnt.h>
36
#elif defined __APPLE__
37
#include <mach-o/loader.h>
38
#include <mach-o/reloc.h>
39
#include <mach-o/nlist.h>
40
#include <mach-o/stab.h>
41
#include <mach-o/arm64/reloc.h>
42
#include <mach-o/x86_64/reloc.h>
43
#else
44
#include <elf.h>
45
#endif
46

47
#ifdef HAVE_CAPSTONE
48
#include <capstone.h>
49
#endif
50

51
#ifndef R_AARCH64_MOVW_UABS_G0_NC
52
#define R_AARCH64_MOVW_UABS_G0_NC 264
53
#endif
54

55
#ifndef R_AARCH64_MOVW_UABS_G1_NC
56
#define R_AARCH64_MOVW_UABS_G1_NC 266
57
#endif
58

59
#ifndef R_AARCH64_MOVW_UABS_G2_NC
60
#define R_AARCH64_MOVW_UABS_G2_NC 268
61
#endif
62

63
#ifndef R_AARCH64_MOVW_UABS_G3
64
#define R_AARCH64_MOVW_UABS_G3 269
65
#endif
66

67
#ifndef SHT_X86_64_UNWIND
68
#define SHT_X86_64_UNWIND 0x70000001
69
#endif
70

71
#define CODE_PAGE_ALIGN   4096
72
#define CODE_PAGE_SIZE    0x400000
73
#define THREAD_CACHE_SIZE 0x10000
74
#define CODE_BLOB_ALIGN   256
75
#define MIN_BLOB_SIZE     0x4000
76

77
#define __IMM64(x) __IMM32(x), __IMM32((x) >> 32)
78
#define __IMM32(x) __IMM16(x), __IMM16((x) >> 16)
79
#define __IMM16(x) (x) & 0xff, ((x) >> 8) & 0xff
80

81
STATIC_ASSERT(MIN_BLOB_SIZE <= THREAD_CACHE_SIZE);
82
STATIC_ASSERT(MIN_BLOB_SIZE % CODE_BLOB_ALIGN == 0);
83
STATIC_ASSERT(CODE_PAGE_SIZE % THREAD_CACHE_SIZE == 0);
84

85
typedef struct _code_page code_page_t;
86

87
typedef struct {
88
   uintptr_t  addr;
89
   char      *text;
90
} code_comment_t;
91

92
typedef struct {
93
   unsigned        count;
94
   unsigned        max;
95
   code_comment_t *comments;
96
} code_debug_t;
97

98
typedef struct _code_span {
99
   code_cache_t *owner;
100
   code_span_t  *next;
101
   ident_t       name;
102
   uint8_t      *base;
103
   size_t        size;
104
#ifdef DEBUG
105
   code_debug_t  debug;
106
#endif
107
} code_span_t;
108

109
typedef struct _patch_list {
110
   patch_list_t    *next;
111
   uint8_t         *wptr;
112
   jit_label_t      label;
113
   code_patch_fn_t  fn;
114
} patch_list_t;
115

116
typedef struct _code_page {
117
   code_cache_t *owner;
118
   code_page_t  *next;
119
   uint8_t      *mem;
120
} code_page_t;
121

122
typedef struct _code_cache {
123
   nvc_lock_t   lock;
124
   code_page_t *pages;
125
   code_span_t *spans;
126
   code_span_t *freelist[MAX_THREADS];
127
   code_span_t *globalfree;
128
   FILE        *perfmap;
129
#ifdef HAVE_CAPSTONE
130
   csh          capstone;
131
#endif
132
#ifdef DEBUG
133
   size_t       used;
134
#endif
135
} code_cache_t;
136

137
static void code_disassemble(code_span_t *span, uintptr_t mark,
138
                             struct cpu_state *cpu);
139

140
static void code_cache_unwinder(uintptr_t addr, debug_frame_t *frame,
×
141
                                void *context)
142
{
143
   code_cache_t *code = context;
×
144

145
   const uint8_t *pc = (uint8_t *)addr;
×
146
   for (code_span_t *span = code->spans; span; span = span->next) {
×
147
      if (pc >= span->base && pc < span->base + span->size) {
×
148
         frame->kind = FRAME_VHDL;
×
149
         frame->disp = pc - span->base;
×
150
         frame->symbol = istr(span->name);
×
151
      }
152
   }
153
}
×
154

155
static void code_fault_handler(int sig, void *addr, struct cpu_state *cpu,
×
156
                               void *context)
157
{
158
   code_page_t *page = context;
×
159

160
   const uint8_t *pc = (uint8_t *)cpu->pc;
×
161
   if (pc < page->mem || pc > page->mem + CODE_PAGE_SIZE)
×
162
      return;
163

164
   uintptr_t mark = cpu->pc;
×
165
#ifndef __MINGW32__
166
   if (sig == SIGTRAP)
×
167
      mark--;   // Point to faulting instruction
168
#endif
169

170
   for (code_span_t *span = page->owner->spans; span; span = span->next) {
×
171
      if (pc >= span->base && pc < span->base + span->size && span->name)
×
172
         code_disassemble(span, mark, cpu);
173
   }
174
}
175

176
#ifdef DEBUG
177
static bool code_cache_contains(code_cache_t *code, uint8_t *base, size_t size)
6,894✔
178
{
179
   assert_lock_held(&code->lock);
6,894✔
180

181
   for (code_page_t *p = code->pages; p; p = p->next) {
6,894✔
182
      if (base >= p->mem && base + size <= p->mem + CODE_PAGE_SIZE)
6,894✔
183
         return true;
184
   }
185

186
   return false;
187
}
188
#endif
189

190
static code_span_t *code_span_new(code_cache_t *code, ident_t name,
6,894✔
191
                                  uint8_t *base, size_t size)
192
{
193
   SCOPED_LOCK(code->lock);
6,894✔
194

195
   assert(code_cache_contains(code, base, size));
6,894✔
196

197
   code_span_t *span = xcalloc(sizeof(code_span_t));
6,894✔
198
   span->name  = name;
6,894✔
199
   span->next  = code->spans;
6,894✔
200
   span->base  = base;
6,894✔
201
   span->size  = size;
6,894✔
202
   span->owner = code;
6,894✔
203

204
   code->spans = span;
6,894✔
205
   return span;
6,894✔
206
}
207

208
static void code_page_new(code_cache_t *code)
2,875✔
209
{
210
   assert_lock_held(&code->lock);
2,875✔
211

212
   code_page_t *page = xcalloc(sizeof(code_page_t));
2,875✔
213
   page->owner = code;
2,875✔
214
   page->next  = code->pages;
2,875✔
215
   page->mem   = map_jit_pages(CODE_PAGE_ALIGN, CODE_PAGE_SIZE);
2,875✔
216

217
   add_fault_handler(code_fault_handler, page);
2,875✔
218
   debug_add_unwinder(page->mem, CODE_PAGE_SIZE, code_cache_unwinder, code);
2,875✔
219

220
   code->pages = page;
2,875✔
221

222
   code_span_t *span = xcalloc(sizeof(code_span_t));
2,875✔
223
   span->next  = code->spans;
2,875✔
224
   span->base  = page->mem;
2,875✔
225
   span->size  = CODE_PAGE_SIZE;
2,875✔
226
   span->owner = code;
2,875✔
227

228
   code->globalfree = code->spans = span;
2,875✔
229
}
2,875✔
230

231
code_cache_t *code_cache_new(void)
2,868✔
232
{
233
   code_cache_t *code = xcalloc(sizeof(code_cache_t));
2,868✔
234

235
   {
236
      SCOPED_LOCK(code->lock);
5,736✔
237
      code_page_new(code);
2,868✔
238
   }
239

240
#ifdef HAVE_CAPSTONE
241
#if defined ARCH_X86_64
242
   if (cs_open(CS_ARCH_X86, CS_MODE_64, &(code->capstone)) != CS_ERR_OK)
243
      fatal_trace("failed to init capstone for x86_64");
244
#elif defined ARCH_ARM64
245
   if (cs_open(CS_ARCH_ARM64, CS_MODE_ARM, &(code->capstone)) != CS_ERR_OK)
246
      fatal_trace("failed to init capstone for Arm64");
247
#else
248
#error Cannot configure capstone for this architecture
249
#endif
250

251
   if (cs_option(code->capstone, CS_OPT_DETAIL, 1) != CS_ERR_OK)
252
      fatal_trace("failed to set capstone detailed mode");
253
#endif
254

255
   return code;
2,868✔
256
}
257

258
void code_cache_free(code_cache_t *code)
2,866✔
259
{
260
   for (code_page_t *it = code->pages, *tmp; it; it = tmp) {
5,739✔
261
      debug_remove_unwinder(it->mem);
2,873✔
262
      remove_fault_handler(code_fault_handler, it);
2,873✔
263

264
      nvc_munmap(it->mem, CODE_PAGE_SIZE);
2,873✔
265

266
      tmp = it->next;
2,873✔
267
      free(it);
2,873✔
268
   }
269

270
   for (code_span_t *it = code->spans, *tmp; it; it = tmp) {
12,633✔
271
      tmp = it->next;
9,767✔
272
      free(it);
9,767✔
273
   }
274

275
#ifdef HAVE_CAPSTONE
276
   cs_close(&(code->capstone));
277
#endif
278

279
#ifdef DEBUG
280
   debugf("JIT code footprint: %zu bytes", code->used);
2,866✔
281
#endif
282

283
   free(code);
2,866✔
284
}
2,866✔
285

286
#ifdef HAVE_CAPSTONE
287
static int code_print_spaces(int col, int tab)
288
{
289
   for (; col < tab; col++)
290
      fputc(' ', stdout);
291
   return col;
292
}
293
#endif
294

295
static void code_disassemble(code_span_t *span, uintptr_t mark,
296
                             struct cpu_state *cpu)
297
{
298
#ifdef HAVE_CAPSTONE
299
   SCOPED_LOCK(span->owner->lock);
300

301
   printf("--");
302

303
   const int namelen = ident_len(span->name);
304
   for (int i = 0; i < 72 - namelen; i++)
305
      fputc('-', stdout);
306

307
   printf(" %s ----\n", istr(span->name));
308

309
   cs_insn *insn = cs_malloc(span->owner->capstone);
310

311
#ifdef DEBUG
312
   code_comment_t *comment = span->debug.comments;
313
#endif
314

315
   const uint8_t *const eptr = span->base + span->size;
316
   for (const uint8_t *ptr = span->base; ptr < eptr; ) {
317
      uint64_t address = (uint64_t)ptr;
318

319
#ifdef DEBUG
320
      for (; comment < span->debug.comments + span->debug.count
321
              && comment->addr <= address; comment++)
322
         printf("%30s;; %s\n", "", comment->text);
323
#endif
324

325
      size_t size = eptr - ptr;
326
      int col = 0;
327
      if (cs_disasm_iter(span->owner->capstone, &ptr, &size, &address, insn)) {
328
         char hex1[33], *p = hex1;
329
         for (size_t k = 0; k < insn->size; k++)
330
            p += checked_sprintf(p, hex1 + sizeof(hex1) - p, "%02x",
331
                                 insn->bytes[k]);
332

333
         col = printf("%-12" PRIx64 " %-16.16s %s %s", insn->address,
334
                          hex1, insn->mnemonic, insn->op_str);
335

336
#ifdef ARCH_X86_64
337
         if (strcmp(insn->mnemonic, "movabs") == 0) {
338
            const cs_x86_op *src = &(insn->detail->x86.operands[1]);
339
            if (src->type == X86_OP_IMM) {
340
               const char *sym = debug_symbol_name((void *)src->imm);
341
               if (sym != NULL) {
342
                  col = code_print_spaces(col, 60);
343
                  col += printf(" ; %s", sym);
344
               }
345
            }
346
         }
347
#endif
348

349
         if (strlen(hex1) > 16)
350
            col = printf("\n%15s -%-16s", "", hex1 + 16) - 1;
351
      }
352
      else {
353
#ifdef ARCH_ARM64
354
         col = printf("%-12" PRIx64 " %-16.08x %s 0x%08x", (uint64_t)ptr,
355
                      *(uint32_t *)ptr, ".word", *(uint32_t *)ptr);
356
         ptr += 4;
357
#else
358
         col = printf("%-12" PRIx64 " %-16.02x %s 0x%02x", (uint64_t)ptr,
359
                      *ptr, ".byte", *ptr);
360
         ptr++;
361
#endif
362
      }
363

364
      if (mark != 0 && (ptr >= eptr || address > mark)) {
365
         col = code_print_spaces(col, 66);
366
         printf("<=============\n");
367
         if (cpu != NULL) {
368
#ifdef ARCH_X86_64
369
            const char *names[] = {
370
               "RAX", "RCX", "RDX", "RBX", "RSP", "RBP", "RSI", "RDI",
371
               "R8", "R9", "R10", "R11", "R12", "R13", "R14", "R15"
372
            };
373
            for (int i = 0; i < ARRAY_LEN(names); i++)
374
               printf("\t%s\t%"PRIxPTR"\n", names[i], cpu->regs[i]);
375
#else
376
            for (int i = 0; i < 32; i++)
377
               printf("\tR%d\t%"PRIxPTR"\n", i, cpu->regs[i]);
378
#endif
379
         }
380
         mark = 0;
381
      }
382
      else
383
         printf("\n");
384
   }
385

386
   cs_free(insn, 1);
387

388
   for (int i = 0; i < 80; i++)
389
      fputc('-', stdout);
390
   printf("\n");
391
   fflush(stdout);
392
#endif
393
}
394

395
static void code_write_perf_map(code_span_t *span)
×
396
{
397
   SCOPED_LOCK(span->owner->lock);
×
398

399
   if (span->owner->perfmap == NULL) {
×
400
      char *fname LOCAL = xasprintf("/tmp/perf-%d.map", getpid());
×
401
      if ((span->owner->perfmap = fopen(fname, "w")) == NULL) {
×
402
         warnf("cannot create %s: %s", fname, last_os_error());
×
403
         opt_set_int(OPT_PERF_MAP, 0);
×
404
         return;
×
405
      }
406
      else
407
         debugf("writing perf map to %s", fname);
×
408
   }
409

410
   fprintf(span->owner->perfmap, "%p 0x%zx %s\n", span->base, span->size,
×
411
           istr(span->name));
412
   fflush(span->owner->perfmap);
×
413
}
414

415
code_blob_t *code_blob_new(code_cache_t *code, ident_t name, size_t hint)
5,971✔
416
{
417
   code_span_t **freeptr = &(code->freelist[thread_id()]);
5,971✔
418

419
   code_span_t *free = relaxed_load(freeptr);
5,971✔
420
   if (free == NULL) {
5,971✔
421
      free = code_span_new(code, NULL, code->pages->mem, 0);
923✔
422
      relaxed_store(freeptr, free);
923✔
423
   }
424

425
   const size_t reqsz = hint ?: MIN_BLOB_SIZE;
5,971✔
426

427
   if (free->size < reqsz) {
5,971✔
428
      SCOPED_LOCK(code->lock);
984✔
429

430
#ifdef DEBUG
431
      if (free->size > 0)
984✔
432
         debugf("thread %d needs new code cache from global free list "
12✔
433
                "(requested %zu bytes, wasted %zu bytes)",
434
                thread_id(), reqsz, free->size);
435
#endif
436

437
      const size_t chunksz = MAX(reqsz, THREAD_CACHE_SIZE);
984✔
438
      const size_t alignedsz = ALIGN_UP(chunksz, CODE_BLOB_ALIGN);
984✔
439

440
      if (alignedsz > code->globalfree->size) {
984✔
441
         DEBUG_ONLY(debugf("requesting new %d byte code page", CODE_PAGE_SIZE));
7✔
442
         code_page_new(code);
7✔
443
         assert(code->globalfree->size == CODE_PAGE_SIZE);
7✔
444
      }
445

446
      const size_t take = MIN(code->globalfree->size, alignedsz);
984✔
447

448
      free->size = take;
984✔
449
      free->base = code->globalfree->base;
984✔
450

451
      code->globalfree->base += take;
984✔
452
      code->globalfree->size -= take;
984✔
453
   }
454

455
   assert(reqsz <= free->size);
5,971✔
456
   assert(((uintptr_t)free->base & (CODE_BLOB_ALIGN - 1)) == 0);
5,971✔
457

458
   code_span_t *span = code_span_new(code, name, free->base, free->size);
5,971✔
459

460
   free->base += span->size;
5,971✔
461
   free->size -= span->size;
5,971✔
462

463
   code_blob_t *blob = xcalloc(sizeof(code_blob_t));
5,971✔
464
   blob->span = span;
5,971✔
465
   blob->wptr = span->base;
5,971✔
466

467
   thread_wx_mode(WX_WRITE);
5,971✔
468

469
   return blob;
5,971✔
470
}
471

472
void code_blob_finalise(code_blob_t *blob, jit_entry_fn_t *entry)
5,971✔
473
{
474
   code_span_t *span = blob->span;
5,971✔
475
   span->size = blob->wptr - span->base;
5,971✔
476

477
   code_span_t *freespan = relaxed_load(&(span->owner->freelist[thread_id()]));
5,971✔
478
   assert(freespan->size == 0);
5,971✔
479

480
   ihash_free(blob->labels);
5,971✔
481
   blob->labels = NULL;
5,971✔
482

483
   if (unlikely(blob->patches != NULL))
5,971✔
484
      fatal_trace("not all labels in %s were patched", istr(span->name));
×
485
   else if (unlikely(blob->overflow)) {
5,971✔
486
      // Return all the memory
487
      freespan->size = freespan->base - span->base;
1✔
488
      freespan->base = span->base;
1✔
489
      free(blob);
1✔
490
      return;
1✔
491
   }
492
   else if (span->size == 0)
5,970✔
493
      fatal_trace("code span %s is empty", istr(span->name));
×
494

495
   uint8_t *aligned = ALIGN_UP(blob->wptr, CODE_BLOB_ALIGN);
5,970✔
496
   freespan->size = freespan->base - aligned;
5,970✔
497
   freespan->base = aligned;
5,970✔
498

499
   if (opt_get_verbose(OPT_ASM_VERBOSE, istr(span->name))) {
5,970✔
500
      color_printf("\n$bold$$blue$");
×
501
      code_disassemble(span, 0, NULL);
×
502
      color_printf("$$\n");
×
503
   }
504

505
   __builtin___clear_cache((char *)span->base, (char *)blob->wptr);
5,970✔
506

507
   thread_wx_mode(WX_EXECUTE);
5,970✔
508

509
   store_release(entry, (jit_entry_fn_t)span->base);
5,970✔
510

511
   DEBUG_ONLY(relaxed_add(&span->owner->used, span->size));
5,970✔
512
   free(blob);
5,970✔
513

514
   if (opt_get_int(OPT_PERF_MAP))
5,970✔
515
      code_write_perf_map(span);
×
516
}
517

518
void code_blob_emit(code_blob_t *blob, const uint8_t *bytes, size_t len)
15,829✔
519
{
520
   if (unlikely(blob->overflow))
15,829✔
521
      return;
522
   else if (unlikely(blob->wptr + len > blob->span->base + blob->span->size)) {
15,829✔
523
      warnf("JIT code buffer for %s too small", istr(blob->span->name));
1✔
524
      for (patch_list_t *it = blob->patches, *tmp; it; it = tmp) {
1✔
525
         tmp = it->next;
×
526
         free(it);
×
527
      }
528
      blob->patches = NULL;
1✔
529
      blob->overflow = true;
1✔
530
      return;
1✔
531
   }
532

533
   for (size_t i = 0; i < len; i++)
30,909,300✔
534
      *(blob->wptr++) = bytes[i];
30,893,500✔
535
}
536

537
void code_blob_align(code_blob_t *blob, unsigned align)
6,158✔
538
{
539
#ifdef ARCH_X86_64
540
   const uint8_t pad[] = { 0x90 };
6,158✔
541
#else
542
   const uint8_t pad[] = { 0x00 };
543
#endif
544

545
   assert(is_power_of_2(align));
6,158✔
546
   assert(align % ARRAY_LEN(pad) == 0);
547

548
   while (((uintptr_t)blob->wptr & (align - 1)) && !blob->overflow)
6,475✔
549
      code_blob_emit(blob, pad, ARRAY_LEN(pad));
317✔
550
}
6,158✔
551

552
void code_blob_mark(code_blob_t *blob, jit_label_t label)
60✔
553
{
554
   if (unlikely(blob->overflow))
60✔
555
      return;
556
   else if (blob->labels == NULL)
60✔
557
      blob->labels = ihash_new(256);
55✔
558

559
   ihash_put(blob->labels, label, blob->wptr);
60✔
560

561
   for (patch_list_t **p = &(blob->patches); *p; ) {
77✔
562
      if ((*p)->label == label) {
17✔
563
         patch_list_t *next = (*p)->next;
7✔
564
         (*(*p)->fn)(blob, label, (*p)->wptr, blob->wptr);
7✔
565
         free(*p);
7✔
566
         *p = next;
7✔
567
      }
568
      else
569
         p = &((*p)->next);
10✔
570
   }
571
}
572

573
void code_blob_patch(code_blob_t *blob, jit_label_t label, code_patch_fn_t fn)
8✔
574
{
575
   void *ptr = NULL;
8✔
576
   if (unlikely(blob->overflow))
8✔
577
      return;
578
   else if (blob->labels != NULL && (ptr = ihash_get(blob->labels, label)))
8✔
579
      (*fn)(blob, label, blob->wptr, ptr);
1✔
580
   else {
581
      patch_list_t *new = xmalloc(sizeof(patch_list_t));
7✔
582
      new->next  = blob->patches;
7✔
583
      new->fn    = fn;
7✔
584
      new->label = label;
7✔
585
      new->wptr  = blob->wptr;
7✔
586

587
      blob->patches = new;
7✔
588
   }
589
}
590

591
#ifdef DEBUG
592
static void code_blob_print_value(text_buf_t *tb, jit_value_t value)
332✔
593
{
594
   switch (value.kind) {
332✔
595
   case JIT_VALUE_REG:
135✔
596
      tb_printf(tb, "R%d", value.reg);
135✔
597
      break;
135✔
598
   case JIT_VALUE_INT64:
170✔
599
      if (value.int64 < 4096)
170✔
600
         tb_printf(tb, "#%"PRIi64, value.int64);
167✔
601
      else
602
         tb_printf(tb, "#0x%"PRIx64, value.int64);
3✔
603
      break;
604
   case JIT_VALUE_DOUBLE:
1✔
605
      tb_printf(tb, "%%%g", value.dval);
1✔
606
      break;
1✔
607
   case JIT_ADDR_CPOOL:
×
608
      tb_printf(tb, "[CP+%"PRIi64"]", value.int64);
×
609
      break;
×
610
   case JIT_ADDR_REG:
19✔
611
      tb_printf(tb, "[R%d", value.reg);
19✔
612
      if (value.disp != 0)
19✔
613
         tb_printf(tb, "+%d", value.disp);
1✔
614
      tb_cat(tb, "]");
19✔
615
      break;
19✔
616
   case JIT_ADDR_ABS:
×
617
      tb_printf(tb, "[#%016"PRIx64"]", value.int64);
×
618
      break;
×
619
   case JIT_ADDR_COVER:
×
620
      tb_printf(tb, "@%"PRIi64, value.int64);
×
621
      break;
×
622
   case JIT_VALUE_LABEL:
5✔
623
      tb_printf(tb, "%d", value.label);
5✔
624
      break;
5✔
625
   case JIT_VALUE_HANDLE:
2✔
626
      tb_printf(tb, "<%d>", value.handle);
2✔
627
      break;
2✔
628
   case JIT_VALUE_EXIT:
×
629
      tb_printf(tb, "%s", jit_exit_name(value.exit));
×
630
      break;
×
631
   case JIT_VALUE_LOC:
×
632
      tb_printf(tb, "<%s:%d>", loc_file_str(&value.loc), value.loc.first_line);
×
633
      break;
×
634
   case JIT_VALUE_FOREIGN:
×
635
      tb_printf(tb, "$%s", istr(ffi_get_sym(value.foreign)));
×
636
      break;
×
637
   case JIT_VALUE_LOCUS:
×
638
      tb_printf(tb, "%s%+d", istr(value.ident), value.disp);
×
639
      break;
×
640
   case JIT_VALUE_VPOS:
×
641
      tb_printf(tb, "%u:%u", value.vpos.block, value.vpos.op);
×
642
      break;
×
643
   default:
×
644
      tb_cat(tb, "???");
×
645
   }
646
}
332✔
647

648
static void code_blob_add_comment(code_blob_t *blob, char *text)
649
{
650
   code_debug_t *dbg = &(blob->span->debug);
651

652
   if (dbg->count == dbg->max) {
653
      dbg->max = MAX(128, dbg->max * 2);
654
      dbg->comments = xrealloc_array(dbg->comments, dbg->max,
655
                                     sizeof(code_comment_t));
656
   }
657

658
   dbg->comments[dbg->count].addr = (uintptr_t)blob->wptr;
659
   dbg->comments[dbg->count].text = text;
660
   dbg->count++;
661
}
662

663
void code_blob_print_ir(code_blob_t *blob, jit_ir_t *ir)
291✔
664
{
665
   LOCAL_TEXT_BUF tb = tb_new();
582✔
666
   tb_printf(tb, "%s%s", jit_op_name(ir->op), jit_cc_name(ir->cc));
291✔
667

668
   if (ir->size != JIT_SZ_UNSPEC)
291✔
669
      tb_printf(tb, ".%d", 1 << (3 + ir->size));
26✔
670

671
   tb_printf(tb, "%*.s", (int)MAX(0, 10 - tb_len(tb)), "");
291✔
672

673
   if (ir->result != JIT_REG_INVALID)
291✔
674
      tb_printf(tb, "R%d", ir->result);
168✔
675

676
   if (ir->arg1.kind != JIT_VALUE_INVALID) {
291✔
677
      if (ir->result != JIT_REG_INVALID)
225✔
678
         tb_cat(tb, ", ");
160✔
679
      code_blob_print_value(tb, ir->arg1);
225✔
680
   }
681

682
   if (ir->arg2.kind != JIT_VALUE_INVALID) {
291✔
683
      tb_cat(tb, ", ");
107✔
684
      code_blob_print_value(tb, ir->arg2);
107✔
685
   }
686

687
   code_blob_add_comment(blob, tb_claim(tb));
291✔
688
}
291✔
689

690
void code_blob_printf(code_blob_t *blob, const char *fmt, ...)
×
691
{
692
   code_debug_t *dbg = &(blob->span->debug);
×
693

694
   if (dbg->count == dbg->max) {
×
695
      dbg->max = MAX(128, dbg->max * 2);
×
696
      dbg->comments = xrealloc_array(dbg->comments, dbg->max,
×
697
                                     sizeof(code_comment_t));
698
   }
699

700
   va_list ap;
×
701
   va_start(ap, fmt);
×
702

703
   char *text = xvasprintf(fmt, ap);
×
704
   code_blob_add_comment(blob, text);
×
705

706
   va_end(ap);
×
707
}
×
708
#endif   // DEBUG
709

710
#ifdef ARCH_ARM64
711
static void *arm64_emit_trampoline(code_blob_t *blob, uintptr_t dest)
712
{
713
   const uint8_t veneer[] = {
714
      0x50, 0x00, 0x00, 0x58,   // LDR X16, [PC+8]
715
      0x00, 0x02, 0x1f, 0xd6,   // BR X16
716
      __IMM64(dest)
717
   };
718

719
   void *prev = memmem(blob->span->base, blob->span->size,
720
                       veneer, ARRAY_LEN(veneer));
721
   if (prev != NULL)
722
      return prev;
723
   else {
724
      void *addr = blob->wptr;
725
      code_blob_emit(blob, veneer, ARRAY_LEN(veneer));
726
      return addr;
727
   }
728
}
729
#else
730
#define arm64_emit_trampoline(blob, dest) NULL
731
#endif
732

733
#if defined __MINGW32__
734
static void code_load_pe(code_blob_t *blob, const void *data, size_t size)
735
{
736
   const IMAGE_FILE_HEADER *imghdr = data;
737

738
   if (imghdr->Machine != IMAGE_FILE_MACHINE_AMD64)
739
      fatal_trace("unknown target machine %x", imghdr->Machine);
740

741
   const IMAGE_SYMBOL *symtab = data + imghdr->PointerToSymbolTable;
742
   const char *strtab = data + imghdr->PointerToSymbolTable
743
      + imghdr->NumberOfSymbols * sizeof(IMAGE_SYMBOL);
744

745
   const IMAGE_SECTION_HEADER *sections =
746
      data + IMAGE_SIZEOF_FILE_HEADER + imghdr->SizeOfOptionalHeader;
747

748
   void **load_addr LOCAL =
749
      xmalloc_array(imghdr->NumberOfSections, sizeof(void *));
750

751
   for (int i = 0; i < imghdr->NumberOfSections; i++) {
752
      if ((sections[i].Characteristics & IMAGE_SCN_CNT_CODE)
753
          || (sections[i].Characteristics & IMAGE_SCN_CNT_INITIALIZED_DATA)) {
754
         const int align = sections[i].Characteristics & IMAGE_SCN_ALIGN_MASK;
755
         code_blob_align(blob, 1 << ((align >> 20) - 1));
756
         load_addr[i] = blob->wptr;
757
         code_blob_emit(blob, data + sections[i].PointerToRawData,
758
                        sections[i].SizeOfRawData);
759
      }
760
      else if ((sections[i].Characteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA)
761
               && sections[i].Misc.VirtualSize > 0)
762
         fatal_trace("non-empty BSS not supported");
763
   }
764

765
   if (blob->overflow)
766
      return;   // Relocations might point outside of code span
767

768
   for (int i = 0; i < imghdr->NumberOfSections; i++) {
769
      const IMAGE_RELOCATION *relocs = data + sections[i].PointerToRelocations;
770
      for (int j = 0; j < sections[i].NumberOfRelocations; j++) {
771
         const char *name = NULL;
772
         char tmp[9];
773

774
         assert(relocs[j].SymbolTableIndex < imghdr->NumberOfSymbols);
775
         const IMAGE_SYMBOL *sym = symtab + relocs[j].SymbolTableIndex;
776

777
         if (sym->N.Name.Short) {
778
            memcpy(tmp, sym->N.ShortName, 8);
779
            tmp[8] = '\0';
780
            name = tmp;
781
         }
782
         else
783
            name = strtab + sym->N.Name.Long;
784

785
         void *ptr = NULL;
786
         if (sym->SectionNumber > 0) {
787
            assert(sym->SectionNumber - 1 < imghdr->NumberOfSections);
788
            ptr = load_addr[sym->SectionNumber - 1];
789
         }
790
         else if (strcmp(name, "___chkstk_ms") == 0) {
791
            extern void ___chkstk_ms(void);
792
            ptr = &___chkstk_ms;
793
         }
794
         else
795
            ptr = ffi_find_symbol(NULL, name);
796

797
         if (ptr == NULL)
798
            fatal_trace("failed to resolve symbol %s", name);
799

800
         void *patch = load_addr[i] + relocs[j].VirtualAddress;
801
         assert((uint8_t *)patch >= blob->span->base);
802
         assert((uint8_t *)patch < blob->span->base + blob->span->size);
803

804
         switch (relocs[j].Type) {
805
         case IMAGE_REL_AMD64_ADDR64:
806
            *(uint64_t *)patch += (uint64_t)ptr;
807
            break;
808
         case IMAGE_REL_AMD64_ADDR32NB:
809
            *(uint32_t *)patch += (uint32_t)(ptr - (void *)blob->span->base);
810
            break;
811
         default:
812
            blob->span->size = blob->wptr - blob->span->base;
813
            code_disassemble(blob->span, (uintptr_t)patch, NULL);
814
            fatal_trace("cannot handle relocation type %d for symbol %s",
815
                        relocs[j].Type, name);
816
         }
817
      }
818

819
      if (strncmp((const char *)sections[i].Name, ".pdata",
820
                  IMAGE_SIZEOF_SHORT_NAME) == 0) {
821
         assert(sections[i].SizeOfRawData % sizeof(RUNTIME_FUNCTION) == 0);
822
         const int count = sections[i].SizeOfRawData / sizeof(RUNTIME_FUNCTION);
823
         const DWORD64 base = (DWORD64)blob->span->base;
824

825
         // TODO: we should also call RtlDeleteFunctionTable at some point
826
         if (!RtlAddFunctionTable(load_addr[i], count, base))
827
            fatal_trace("RtlAddFunctionTable failed: %s", last_os_error());
828
      }
829
   }
830
}
831
#elif defined __APPLE__
832
static void code_load_macho(code_blob_t *blob, const void *data, size_t size)
833
{
834
   const void *rptr = data;
835

836
   const struct mach_header_64 *fhdr = rptr;
837
   rptr += sizeof(struct mach_header_64);
838

839
   if (fhdr->magic != MH_MAGIC_64)
840
      fatal_trace("bad Mach-O magic %x", fhdr->magic);
841

842
   const struct segment_command_64 *seg = NULL;
843
   const struct symtab_command *symtab = NULL;
844

845
   void **load_addr LOCAL = NULL;
846

847
   for (int i = 0; i < fhdr->ncmds; i++) {
848
      const struct load_command *load = rptr;
849
      switch (load->cmd) {
850
      case LC_SEGMENT_64:
851
         {
852
            seg = rptr;
853
            load_addr = xmalloc_array(seg->nsects, sizeof(void *));
854

855
            for (int j = 0; j < seg->nsects; j++) {
856
               const struct section_64 *sec =
857
                  (void *)seg + sizeof(struct segment_command_64)
858
                  + j * sizeof(struct section_64);
859
               code_blob_align(blob, 1 << sec->align);
860
               load_addr[j] = blob->wptr;
861
               code_blob_emit(blob, data + sec->offset, sec->size);
862
            }
863
         }
864
         break;
865
      case LC_SYMTAB:
866
         symtab = rptr;
867
         assert(symtab->cmdsize == sizeof(struct symtab_command));
868
         break;
869
      case LC_DATA_IN_CODE:
870
      case LC_LINKER_OPTIMIZATION_HINT:
871
      case LC_BUILD_VERSION:
872
      case LC_DYSYMTAB:
873
         break;
874
      default:
875
         warnf("unrecognised load command 0x%0x", load->cmd);
876
      }
877

878
      rptr += load->cmdsize;
879
   }
880
   assert(rptr == data + sizeof(struct mach_header_64) + fhdr->sizeofcmds);
881

882
   if (blob->overflow)
883
      return;   // Relocations might point outside of code span
884

885
   assert(seg != NULL);
886
   assert(symtab != NULL);
887

888
   for (int i = 0; i < seg->nsects; i++) {
889
      const struct section_64 *sec =
890
         (void *)seg + sizeof(struct segment_command_64)
891
         + i * sizeof(struct section_64);
892

893
      uint32_t addend = 0;
894
      for (int j = 0; j < sec->nreloc; j++) {
895
         const struct relocation_info *rel =
896
            data + sec->reloff + j * sizeof(struct relocation_info);
897
         const char *name = NULL;
898
         void *ptr = NULL;
899
         if (rel->r_extern) {
900
            assert(rel->r_symbolnum < symtab->nsyms);
901
            const struct nlist_64 *nl = data + symtab->symoff
902
               + rel->r_symbolnum * sizeof(struct nlist_64);
903
            name = data + symtab->stroff + nl->n_un.n_strx;
904

905
            if (nl->n_type & N_EXT) {
906
               if (icmp(blob->span->name, name + 1))
907
                  ptr = blob->span->base;
908
               else if ((ptr = ffi_find_symbol(NULL, name + 1)) == NULL)
909
                  fatal_trace("failed to resolve symbol %s", name + 1);
910
            }
911
            else if (nl->n_sect != NO_SECT)
912
               ptr = blob->span->base + nl->n_value;
913
         }
914
         else
915
            ptr = blob->span->base;
916

917
         ptr += addend;
918
         addend = 0;
919

920
         void *patch = load_addr[i] + rel->r_address;
921
         assert((uint8_t *)patch >= blob->span->base);
922
         assert((uint8_t *)patch < blob->span->base + blob->span->size);
923

924
         switch (rel->r_type) {
925
#ifdef ARCH_ARM64
926
         case ARM64_RELOC_UNSIGNED:
927
            assert(rel->r_length == 3);
928
            *(void **)patch = ptr;
929
            break;
930
         case ARM64_RELOC_SUBTRACTOR:
931
            break;   // What is this?
932
         case ARM64_RELOC_GOT_LOAD_PAGEOFF12:
933
         case ARM64_RELOC_PAGEOFF12:
934
            switch ((*(uint32_t *)patch >> 23) & 0x7f) {
935
            case 0b1111010:   // LDR (immediate, SIMD&FP)
936
            case 0b1110010:   // LDR (immediate)
937
               assert(*(uint32_t *)patch & (1 << 30));  // Quadword
938
               assert(((uintptr_t)ptr & 7) == 0);
939
               *(uint32_t *)patch |= (((uintptr_t)ptr & 0xfff) >> 3) << 10;
940
               break;
941
            case 0b0100010:   // ADD (immediate)
942
               *(uint32_t *)patch |= ((uintptr_t)ptr & 0xfff) << 10;
943
               break;
944
            default:
945
               blob->span->size = blob->wptr - blob->span->base;
946
               code_disassemble(blob->span, (uintptr_t)patch, NULL);
947
               fatal_trace("cannot patch instruction");
948
            }
949
            break;
950
         case ARM64_RELOC_GOT_LOAD_PAGE21:
951
         case ARM64_RELOC_PAGE21:
952
            {
953
               const intptr_t dst_page = (intptr_t)ptr & ~UINT64_C(0xfff);
954
               const intptr_t src_page = (intptr_t)patch & ~UINT64_C(0xfff);
955
               const intptr_t upper21 = (dst_page - src_page) >> 12;
956
               *(uint32_t *)patch |= (upper21 & 3) << 29;
957
               *(uint32_t *)patch |= ((upper21 >> 2) & 0x7ffff) << 5;
958
            }
959
            break;
960
         case ARM64_RELOC_BRANCH26:
961
            {
962
               void *veneer = arm64_emit_trampoline(blob, (uintptr_t)ptr);
963
               const ptrdiff_t pcrel = (veneer - patch) >> 2;
964
               *(uint32_t *)patch &= ~0x3ffffff;
965
               *(uint32_t *)patch |= pcrel & 0x3ffffff;
966
            }
967
            break;
968
         case ARM64_RELOC_ADDEND:
969
            addend = rel->r_symbolnum;
970
            break;
971
#elif defined ARCH_X86_64
972
         case X86_64_RELOC_UNSIGNED:
973
            *(uint64_t *)patch += (uint64_t)ptr;
974
            break;
975
         case X86_64_RELOC_BRANCH:
976
            *(uint32_t *)patch += (uint32_t)(ptr - patch - 4);
977
            break;
978
#endif
979
         default:
980
            blob->span->size = blob->wptr - blob->span->base;
981
            code_disassemble(blob->span, (uintptr_t)patch, NULL);
982
            fatal_trace("cannot handle relocation type %d for symbol %s",
983
                        rel->r_type, name);
984
         }
985
      }
986
   }
987
}
988
#elif !defined __MINGW32__
989
static void code_load_elf(code_blob_t *blob, const void *data, size_t size)
990
{
991
   const Elf64_Ehdr *ehdr = data;
992

993
   if (ehdr->e_ident[EI_MAG0] != ELFMAG0
994
       || ehdr->e_ident[EI_MAG1] != ELFMAG1
995
       || ehdr->e_ident[EI_MAG2] != ELFMAG2
996
       || ehdr->e_ident[EI_MAG3] != ELFMAG3)
997
      fatal_trace("bad ELF magic");
998
   else if (ehdr->e_shentsize != sizeof(Elf64_Shdr))
999
      fatal_trace("bad section header size %d != %zu", ehdr->e_shentsize,
1000
                  sizeof(Elf64_Shdr));
1001

1002
   const Elf64_Shdr *strtab_hdr =
1003
      data + ehdr->e_shoff + ehdr->e_shstrndx * ehdr->e_shentsize;
1004
   const char *strtab = data + strtab_hdr->sh_offset;
1005

1006
   void **load_addr LOCAL = xcalloc_array(ehdr->e_shnum, sizeof(void *));
1007

1008
   for (int i = 0; i < ehdr->e_shnum; i++) {
1009
      const Elf64_Shdr *shdr = data + ehdr->e_shoff + i * ehdr->e_shentsize;
1010

1011
      switch (shdr->sh_type) {
1012
      case SHT_PROGBITS:
1013
         if (shdr->sh_flags & SHF_ALLOC) {
1014
            code_blob_align(blob, shdr->sh_addralign);
1015
            load_addr[i] = blob->wptr;
1016
            code_blob_emit(blob, data + shdr->sh_offset, shdr->sh_size);
1017
         }
1018
         break;
1019

1020
      case SHT_RELA:
1021
         // Handled in second pass
1022
         break;
1023

1024
      case SHT_NULL:
1025
      case SHT_STRTAB:
1026
      case SHT_X86_64_UNWIND:
1027
      case SHT_SYMTAB:
1028
         break;
1029

1030
      default:
1031
         warnf("ignoring ELF section %s with type %x", strtab + shdr->sh_name,
1032
               shdr->sh_type);
1033
      }
1034
   }
1035

1036
   if (blob->overflow)
1037
      return;   // Relocations might point outside of code span
1038

1039
   for (int i = 0; i < ehdr->e_shnum; i++) {
1040
      const Elf64_Shdr *shdr = data + ehdr->e_shoff + i * ehdr->e_shentsize;
1041
      if (shdr->sh_type != SHT_RELA)
1042
         continue;
1043

1044
      const Elf64_Shdr *mod =
1045
         data + ehdr->e_shoff + shdr->sh_info * ehdr->e_shentsize;
1046
      if (mod->sh_type != SHT_PROGBITS || !(mod->sh_flags & SHF_ALLOC))
1047
         continue;
1048
      else if (load_addr[shdr->sh_info] == NULL)
1049
         fatal_trace("section %s not loaded", strtab + mod->sh_name);
1050

1051
      const Elf64_Shdr *symtab =
1052
         data + ehdr->e_shoff + shdr->sh_link * ehdr->e_shentsize;
1053
      if (symtab->sh_type != SHT_SYMTAB)
1054
         fatal_trace("section %s is not a symbol table",
1055
                     strtab + symtab->sh_name);
1056

1057
      const Elf64_Rela *endp = data + shdr->sh_offset + shdr->sh_size;
1058
      for (const Elf64_Rela *r = data + shdr->sh_offset; r < endp; r++) {
1059
         const Elf64_Sym *sym = data + symtab->sh_offset
1060
            + ELF64_R_SYM(r->r_info) * symtab->sh_entsize;
1061

1062
         char *ptr = NULL;
1063
         switch (ELF64_ST_TYPE(sym->st_info)) {
1064
         case STT_NOTYPE:
1065
         case STT_FUNC:
1066
            ptr = ffi_find_symbol(NULL, strtab + sym->st_name);
1067
            break;
1068
         case STT_SECTION:
1069
            ptr = load_addr[sym->st_shndx];
1070
            break;
1071
         }
1072

1073
         if (ptr == NULL)
1074
            fatal_trace("cannot resolve symbol %s type %d",
1075
                        strtab + sym->st_name, ELF64_ST_TYPE(sym->st_info));
1076

1077
         ptr += r->r_addend;
1078

1079
         void *patch = load_addr[shdr->sh_info] + r->r_offset;
1080
         assert(r->r_offset < mod->sh_size);
1081

1082
         switch (ELF64_R_TYPE(r->r_info)) {
1083
         case R_X86_64_64:
1084
            *(uint64_t *)patch = (uint64_t)ptr;
1085
            break;
1086
         case R_AARCH64_CALL26:
1087
            {
1088
               void *veneer = arm64_emit_trampoline(blob, (uintptr_t)ptr);
1089
               const ptrdiff_t pcrel = (veneer - patch) >> 2;
1090
               *(uint32_t *)patch &= ~0x3ffffff;
1091
               *(uint32_t *)patch |= pcrel & 0x3ffffff;
1092
            }
1093
            break;
1094
         case R_AARCH64_PREL64:
1095
            *(uint64_t *)patch = ptr - (char *)patch;
1096
            break;
1097
         case R_AARCH64_MOVW_UABS_G0_NC:
1098
            *(uint32_t *)patch |= ((uintptr_t)ptr & 0xffff) << 5;
1099
            break;
1100
         case R_AARCH64_MOVW_UABS_G1_NC:
1101
            *(uint32_t *)patch |= (((uintptr_t)ptr >> 16) & 0xffff) << 5;
1102
            break;
1103
         case R_AARCH64_MOVW_UABS_G2_NC:
1104
            *(uint32_t *)patch |= (((uintptr_t)ptr >> 32) & 0xffff) << 5;
1105
            break;
1106
         case R_AARCH64_MOVW_UABS_G3:
1107
            *(uint32_t *)patch |= (((uintptr_t)ptr >> 48) & 0xffff) << 5;
1108
            break;
1109
         default:
1110
            blob->span->size = blob->wptr - blob->span->base;
1111
            code_disassemble(blob->span, (uintptr_t)patch, NULL);
1112
            fatal_trace("cannot handle relocation type %ld for symbol %s",
1113
                        ELF64_R_TYPE(r->r_info), strtab + sym->st_name);
1114
         }
1115
      }
1116
   }
1117
}
1118
#endif
1119

1120
void code_load_object(code_blob_t *blob, const void *data, size_t size)
5,711✔
1121
{
1122
#if defined __APPLE__
1123
   code_load_macho(blob, data, size);
1124
#elif defined __MINGW32__
1125
   code_load_pe(blob, data, size);
1126
#else
1127
   code_load_elf(blob, data, size);
5,711✔
1128
#endif
1129
}
5,711✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc