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

nickg / nvc / 14575037276

21 Apr 2025 02:17PM UTC coverage: 92.329% (+0.01%) from 92.316%
14575037276

push

github

nickg
Use medium code model for JIT on X86_64

38 of 50 new or added lines in 1 file covered. (76.0%)

1 existing line in 1 file now uncovered.

69219 of 74970 relevant lines covered (92.33%)

418899.96 hits per line

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

73.61
/src/jit/jit-code.c
1
//
2
//  Copyright (C) 2022-2024  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
#ifndef IMAGE_REL_ARM64_BRANCH26
72
#define IMAGE_REL_ARM64_BRANCH26 0x03
73
#endif
74

75
#ifndef IMAGE_REL_ARM64_ADDR32NB
76
#define IMAGE_REL_ARM64_ADDR32NB 0x02
77
#endif
78

79
#ifndef IMAGE_REL_ARM64_PAGEBASE_REL21
80
#define IMAGE_REL_ARM64_PAGEBASE_REL21 0x04
81
#endif
82

83
#ifndef IMAGE_REL_ARM64_PAGEOFFSET_12A
84
#define IMAGE_REL_ARM64_PAGEOFFSET_12A 0x06
85
#endif
86

87
#ifndef IMAGE_REL_ARM64_PAGEOFFSET_12L
88
#define IMAGE_REL_ARM64_PAGEOFFSET_12L 0x07
89
#endif
90

91
#define CODE_PAGE_ALIGN   4096
92
#define CODE_PAGE_SIZE    0x400000
93
#define THREAD_CACHE_SIZE 0x10000
94
#define CODE_BLOB_ALIGN   256
95
#define MIN_BLOB_SIZE     0x4000
96

97
#define __IMM64(x) __IMM32(x), __IMM32((x) >> 32)
98
#define __IMM32(x) __IMM16(x), __IMM16((x) >> 16)
99
#define __IMM16(x) (x) & 0xff, ((x) >> 8) & 0xff
100

101
STATIC_ASSERT(MIN_BLOB_SIZE <= THREAD_CACHE_SIZE);
102
STATIC_ASSERT(MIN_BLOB_SIZE % CODE_BLOB_ALIGN == 0);
103
STATIC_ASSERT(CODE_PAGE_SIZE % THREAD_CACHE_SIZE == 0);
104

105
typedef struct _code_page code_page_t;
106

107
typedef struct {
108
   uintptr_t  addr;
109
   char      *text;
110
} code_comment_t;
111

112
typedef struct {
113
   unsigned        count;
114
   unsigned        max;
115
   code_comment_t *comments;
116
} code_debug_t;
117

118
typedef struct _code_span {
119
   code_cache_t *owner;
120
   code_span_t  *next;
121
   ident_t       name;
122
   uint8_t      *base;
123
   void         *entry;
124
   size_t        size;
125
#ifdef DEBUG
126
   code_debug_t  debug;
127
#endif
128
} code_span_t;
129

130
typedef struct _patch_list {
131
   patch_list_t    *next;
132
   uint8_t         *wptr;
133
   jit_label_t      label;
134
   code_patch_fn_t  fn;
135
} patch_list_t;
136

137
typedef struct _code_page {
138
   code_cache_t *owner;
139
   code_page_t  *next;
140
   uint8_t      *mem;
141
} code_page_t;
142

143
typedef struct _code_cache {
144
   nvc_lock_t   lock;
145
   code_page_t *pages;
146
   code_span_t *spans;
147
   code_span_t *freelist[MAX_THREADS];
148
   code_span_t *globalfree;
149
   FILE        *perfmap;
150
#ifdef HAVE_CAPSTONE
151
   csh          capstone;
152
#endif
153
#ifdef DEBUG
154
   size_t       used;
155
#endif
156
} code_cache_t;
157

158
static void code_disassemble(code_span_t *span, uintptr_t mark,
159
                             struct cpu_state *cpu);
160

161
static void code_cache_unwinder(uintptr_t addr, debug_frame_t *frame,
×
162
                                void *context)
163
{
164
   code_cache_t *code = context;
×
165

166
   const uint8_t *pc = (uint8_t *)addr;
×
167
   for (code_span_t *span = code->spans; span; span = span->next) {
×
168
      if (pc >= span->base && pc < span->base + span->size) {
×
169
         frame->kind = FRAME_VHDL;
×
170
         frame->disp = pc - span->base;
×
171
         frame->symbol = istr(span->name);
×
172
      }
173
   }
174
}
×
175

176
static void code_fault_handler(int sig, void *addr, struct cpu_state *cpu,
×
177
                               void *context)
178
{
179
   code_page_t *page = context;
×
180

181
   const uint8_t *pc = (uint8_t *)cpu->pc;
×
182
   if (pc < page->mem || pc > page->mem + CODE_PAGE_SIZE)
×
183
      return;
184

185
   uintptr_t mark = cpu->pc;
×
186
#ifndef __MINGW32__
187
   if (sig == SIGTRAP)
×
188
      mark--;   // Point to faulting instruction
×
189
#endif
190

191
   for (code_span_t *span = page->owner->spans; span; span = span->next) {
×
192
      if (pc >= span->base && pc < span->base + span->size && span->name)
×
193
         code_disassemble(span, mark, cpu);
×
194
   }
195
}
196

197
#ifdef DEBUG
198
static bool code_cache_contains(code_cache_t *code, uint8_t *base, size_t size)
9,472✔
199
{
200
   assert_lock_held(&code->lock);
9,472✔
201

202
   for (code_page_t *p = code->pages; p; p = p->next) {
9,472✔
203
      if (base >= p->mem && base + size <= p->mem + CODE_PAGE_SIZE)
9,472✔
204
         return true;
205
   }
206

207
   return false;
208
}
209
#endif
210

211
static code_span_t *code_span_new(code_cache_t *code, ident_t name,
9,472✔
212
                                  uint8_t *base, size_t size)
213
{
214
   SCOPED_LOCK(code->lock);
9,472✔
215

216
   assert(code_cache_contains(code, base, size));
9,472✔
217

218
   code_span_t *span = xcalloc(sizeof(code_span_t));
9,472✔
219
   span->name  = name;
9,472✔
220
   span->next  = code->spans;
9,472✔
221
   span->base  = base;
9,472✔
222
   span->entry = base;
9,472✔
223
   span->size  = size;
9,472✔
224
   span->owner = code;
9,472✔
225

226
   code->spans = span;
9,472✔
227
   return span;
9,472✔
228
}
229

230
static void code_page_new(code_cache_t *code)
3,598✔
231
{
232
   assert_lock_held(&code->lock);
3,598✔
233

234
   code_page_t *page = xcalloc(sizeof(code_page_t));
3,598✔
235
   page->owner = code;
3,598✔
236
   page->next  = code->pages;
3,598✔
237
   page->mem   = map_jit_pages(CODE_PAGE_ALIGN, CODE_PAGE_SIZE);
3,598✔
238

239
   add_fault_handler(code_fault_handler, page);
3,598✔
240
   debug_add_unwinder(page->mem, CODE_PAGE_SIZE, code_cache_unwinder, code);
3,598✔
241

242
   code->pages = page;
3,598✔
243

244
   code_span_t *span = xcalloc(sizeof(code_span_t));
3,598✔
245
   span->next  = code->spans;
3,598✔
246
   span->base  = page->mem;
3,598✔
247
   span->size  = CODE_PAGE_SIZE;
3,598✔
248
   span->owner = code;
3,598✔
249

250
   code->globalfree = code->spans = span;
3,598✔
251
}
3,598✔
252

253
code_cache_t *code_cache_new(void)
3,591✔
254
{
255
   code_cache_t *code = xcalloc(sizeof(code_cache_t));
3,591✔
256

257
   {
258
      SCOPED_LOCK(code->lock);
7,182✔
259
      code_page_new(code);
3,591✔
260
   }
261

262
#ifdef HAVE_CAPSTONE
263
#if defined ARCH_X86_64
264
   if (cs_open(CS_ARCH_X86, CS_MODE_64, &(code->capstone)) != CS_ERR_OK)
265
      fatal_trace("failed to init capstone for x86_64");
266
#elif defined ARCH_ARM64
267
   if (cs_open(CS_ARCH_ARM64, CS_MODE_ARM, &(code->capstone)) != CS_ERR_OK)
268
      fatal_trace("failed to init capstone for Arm64");
269
#else
270
#error Cannot configure capstone for this architecture
271
#endif
272

273
   if (cs_option(code->capstone, CS_OPT_DETAIL, 1) != CS_ERR_OK)
274
      fatal_trace("failed to set capstone detailed mode");
275
#endif
276

277
   return code;
3,591✔
278
}
279

280
void code_cache_free(code_cache_t *code)
3,589✔
281
{
282
   for (code_page_t *it = code->pages, *tmp; it; it = tmp) {
7,185✔
283
      debug_remove_unwinder(it->mem);
3,596✔
284
      remove_fault_handler(code_fault_handler, it);
3,596✔
285

286
      nvc_munmap(it->mem, CODE_PAGE_SIZE);
3,596✔
287

288
      tmp = it->next;
3,596✔
289
      free(it);
3,596✔
290
   }
291

292
   for (code_span_t *it = code->spans, *tmp; it; it = tmp) {
16,657✔
293
      tmp = it->next;
13,068✔
294
      free(it);
13,068✔
295
   }
296

297
#ifdef HAVE_CAPSTONE
298
   cs_close(&(code->capstone));
299
#endif
300

301
#ifdef DEBUG
302
   if (code->used > 0)
3,589✔
303
      debugf("JIT code footprint: %zu bytes", code->used);
1,272✔
304
#endif
305

306
   free(code);
3,589✔
307
}
3,589✔
308

309
#ifdef HAVE_CAPSTONE
310
static int code_print_spaces(int col, int tab)
311
{
312
   for (; col < tab; col++)
313
      fputc(' ', stdout);
314
   return col;
315
}
316
#endif
317

318
#ifdef DEBUG
319
static int code_comment_compare(const void *a, const void *b)
320
{
321
   const code_comment_t *ca = a;
322
   const code_comment_t *cb = b;
323

324
   if (ca->addr < cb->addr)
325
      return -1;
326
   else if (ca->addr > cb->addr)
327
      return 1;
328
   else
329
      return 0;
330
}
331
#endif
332

UNCOV
333
static void code_disassemble(code_span_t *span, uintptr_t mark,
×
334
                             struct cpu_state *cpu)
335
{
336
   SCOPED_LOCK(span->owner->lock);
×
337

338
   printf("--");
×
339

340
   const int namelen = ident_len(span->name);
×
341
   for (int i = 0; i < 72 - namelen; i++)
×
342
      fputc('-', stdout);
×
343

344
   printf(" %s ----\n", istr(span->name));
×
345

346
#ifdef HAVE_CAPSTONE
347
   cs_insn *insn = cs_malloc(span->owner->capstone);
348

349
#ifdef DEBUG
350
   qsort(span->debug.comments, span->debug.count, sizeof(code_comment_t),
351
         code_comment_compare);
352
   code_comment_t *comment = span->debug.comments;
353
#endif
354

355
   const uint8_t *const eptr = span->base + span->size;
356
   for (const uint8_t *ptr = span->base; ptr < eptr; ) {
357
      uint64_t address = (uint64_t)ptr;
358

359
#ifdef DEBUG
360
      for (; comment < span->debug.comments + span->debug.count
361
              && comment->addr <= address; comment++)
362
         printf("%30s;; %s\n", "", comment->text);
363
#endif
364

365
      int zeros = 0;
366
      for (const uint8_t *zp = ptr; zp < eptr && *zp == 0; zp++, zeros++);
367

368
      if (zeros > 8 || zeros == eptr - ptr) {
369
         printf("%30s;; skipping %d zero bytes\n", "", zeros);
370
         ptr += zeros;
371
         continue;
372
      }
373

374
      size_t size = eptr - ptr;
375
      int col = 0;
376
      if (cs_disasm_iter(span->owner->capstone, &ptr, &size, &address, insn)) {
377
         char hex1[33], *p = hex1;
378
         for (size_t k = 0; k < insn->size; k++)
379
            p += checked_sprintf(p, hex1 + sizeof(hex1) - p, "%02x",
380
                                 insn->bytes[k]);
381

382
         col = printf("%-12" PRIx64 " %-16.16s %s %s", insn->address,
383
                          hex1, insn->mnemonic, insn->op_str);
384

385
#ifdef ARCH_X86_64
386
         if (strcmp(insn->mnemonic, "movabs") == 0) {
387
            const cs_x86_op *src = &(insn->detail->x86.operands[1]);
388
            if (src->type == X86_OP_IMM) {
389
               const char *sym = debug_symbol_name((void *)src->imm);
390
               if (sym != NULL) {
391
                  col = code_print_spaces(col, 60);
392
                  col += printf(" ; %s", sym);
393
               }
394
            }
395
         }
396
#endif
397

398
         if (strlen(hex1) > 16)
399
            col = printf("\n%15s -%-16s", "", hex1 + 16) - 1;
400
      }
401
      else {
402
#ifdef ARCH_ARM64
403
         col = printf("%-12" PRIx64 " %-16.08x %s 0x%08x", (uint64_t)ptr,
404
                      *(uint32_t *)ptr, ".word", *(uint32_t *)ptr);
405
         ptr += 4;
406
#else
407
         col = printf("%-12" PRIx64 " %-16.02x %s 0x%02x", (uint64_t)ptr,
408
                      *ptr, ".byte", *ptr);
409
         ptr++;
410
#endif
411
      }
412

413
      if (mark != 0 && (ptr >= eptr || address > mark)) {
414
         col = code_print_spaces(col, 66);
415
         printf("<=============\n");
416
         if (cpu != NULL) {
417
#ifdef ARCH_X86_64
418
            const char *names[] = {
419
               "RAX", "RCX", "RDX", "RBX", "RSP", "RBP", "RSI", "RDI",
420
               "R8", "R9", "R10", "R11", "R12", "R13", "R14", "R15"
421
            };
422
            for (int i = 0; i < ARRAY_LEN(names); i++)
423
               printf("\t%s\t%"PRIxPTR"\n", names[i], cpu->regs[i]);
424
#else
425
            for (int i = 0; i < 32; i++)
426
               printf("\tR%d\t%"PRIxPTR"\n", i, cpu->regs[i]);
427
#endif
428
         }
429
         mark = 0;
430
      }
431
      else
432
         printf("\n");
433
   }
434

435
   cs_free(insn, 1);
436
#else
437
   jit_hexdump(span->base, span->size, 16, (void *)mark, "");
×
438
#endif
439

440
   for (int i = 0; i < 80; i++)
×
441
      fputc('-', stdout);
×
442
   printf("\n");
×
443
   fflush(stdout);
×
444
}
×
445

446
static void code_write_perf_map(code_span_t *span)
×
447
{
448
   SCOPED_LOCK(span->owner->lock);
×
449

450
   if (span->owner->perfmap == NULL) {
×
451
      char *fname LOCAL = xasprintf("/tmp/perf-%d.map", getpid());
×
452
      if ((span->owner->perfmap = fopen(fname, "w")) == NULL) {
×
453
         warnf("cannot create %s: %s", fname, last_os_error());
×
454
         opt_set_int(OPT_PERF_MAP, 0);
×
455
         return;
×
456
      }
457
      else
458
         debugf("writing perf map to %s", fname);
×
459
   }
460

461
   fprintf(span->owner->perfmap, "%p 0x%zx %s\n", span->base, span->size,
×
462
           istr(span->name));
463
   fflush(span->owner->perfmap);
×
464
}
465

466
code_blob_t *code_blob_new(code_cache_t *code, ident_t name, size_t hint)
8,198✔
467
{
468
   code_span_t **freeptr = &(code->freelist[thread_id()]);
8,198✔
469

470
   code_span_t *free = relaxed_load(freeptr);
8,198✔
471
   if (free == NULL) {
8,198✔
472
      free = code_span_new(code, NULL, code->pages->mem, 0);
1,274✔
473
      relaxed_store(freeptr, free);
1,274✔
474
   }
475

476
   const size_t reqsz = hint ?: MIN_BLOB_SIZE;
8,198✔
477

478
   if (free->size < reqsz) {
8,198✔
479
      SCOPED_LOCK(code->lock);
1,342✔
480

481
#ifdef DEBUG
482
      if (free->size > 0)
1,342✔
483
         debugf("thread %d needs new code cache from global free list "
21✔
484
                "(requested %zu bytes, wasted %zu bytes)",
485
                thread_id(), reqsz, free->size);
486
#endif
487

488
      const size_t chunksz = MAX(reqsz, THREAD_CACHE_SIZE);
1,342✔
489
      const size_t alignedsz = ALIGN_UP(chunksz, CODE_BLOB_ALIGN);
1,342✔
490

491
      if (alignedsz > code->globalfree->size) {
1,342✔
492
         DEBUG_ONLY(debugf("requesting new %d byte code page", CODE_PAGE_SIZE));
7✔
493
         code_page_new(code);
7✔
494
         assert(code->globalfree->size == CODE_PAGE_SIZE);
7✔
495
      }
496

497
      const size_t take = MIN(code->globalfree->size, alignedsz);
1,342✔
498

499
      free->size = take;
1,342✔
500
      free->base = code->globalfree->base;
1,342✔
501

502
      code->globalfree->base += take;
1,342✔
503
      code->globalfree->size -= take;
1,342✔
504
   }
505

506
   assert(reqsz <= free->size);
8,198✔
507
   assert(((uintptr_t)free->base & (CODE_BLOB_ALIGN - 1)) == 0);
8,198✔
508

509
   code_span_t *span = code_span_new(code, name, free->base, free->size);
8,198✔
510

511
   free->base += span->size;
8,198✔
512
   free->size -= span->size;
8,198✔
513

514
   code_blob_t *blob = xcalloc(sizeof(code_blob_t));
8,198✔
515
   blob->span = span;
8,198✔
516
   blob->wptr = span->base;
8,198✔
517

518
   thread_wx_mode(WX_WRITE);
8,198✔
519

520
   return blob;
8,198✔
521
}
522

523
void code_blob_finalise(code_blob_t *blob, jit_entry_fn_t *entry)
8,198✔
524
{
525
   code_span_t *span = blob->span;
8,198✔
526
   span->size = blob->wptr - span->base;
8,198✔
527

528
   code_span_t *freespan = relaxed_load(&(span->owner->freelist[thread_id()]));
8,198✔
529
   assert(freespan->size == 0);
8,198✔
530

531
   ihash_free(blob->labels);
8,198✔
532
   blob->labels = NULL;
8,198✔
533

534
   if (unlikely(blob->patches != NULL))
8,198✔
535
      fatal_trace("not all labels in %s were patched", istr(span->name));
536
   else if (unlikely(blob->overflow)) {
8,198✔
537
      // Return all the memory
538
      freespan->size = freespan->base - span->base;
1✔
539
      freespan->base = span->base;
1✔
540
      free(blob);
1✔
541
      return;
1✔
542
   }
543
   else if (span->size == 0)
8,197✔
544
      fatal_trace("code span %s is empty", istr(span->name));
545

546
   uint8_t *aligned = ALIGN_UP(blob->wptr, CODE_BLOB_ALIGN);
8,197✔
547
   freespan->size = freespan->base - aligned;
8,197✔
548
   freespan->base = aligned;
8,197✔
549

550
   if (opt_get_verbose(OPT_ASM_VERBOSE, istr(span->name))) {
8,197✔
551
      color_printf("\n$bold$$blue$");
×
552
      code_disassemble(span, 0, NULL);
×
553
      color_printf("$$\n");
×
554
   }
555

556
   __builtin___clear_cache((char *)span->base, (char *)blob->wptr);
8,197✔
557

558
   thread_wx_mode(WX_EXECUTE);
8,197✔
559

560
   store_release(entry, (jit_entry_fn_t)span->entry);
8,197✔
561

562
   DEBUG_ONLY(relaxed_add(&span->owner->used, span->size));
8,197✔
563
   free(blob);
8,197✔
564

565
   if (opt_get_int(OPT_PERF_MAP))
8,197✔
566
      code_write_perf_map(span);
×
567
}
568

569
__attribute__((cold, noinline))
570
static void code_blob_overflow(code_blob_t *blob)
1✔
571
{
572
   warnf("JIT code buffer for %s too small", istr(blob->span->name));
1✔
573
   for (patch_list_t *it = blob->patches, *tmp; it; it = tmp) {
1✔
574
      tmp = it->next;
×
575
      free(it);
×
576
   }
577
   blob->patches = NULL;
1✔
578
   blob->overflow = true;
1✔
579
}
1✔
580

581
void code_blob_emit(code_blob_t *blob, const uint8_t *bytes, size_t len)
33,805✔
582
{
583
   if (unlikely(blob->overflow))
33,805✔
584
      return;
585
   else if (unlikely(blob->wptr + len > blob->span->base + blob->span->size)) {
33,805✔
586
      code_blob_overflow(blob);
1✔
587
      return;
1✔
588
   }
589

590
   memcpy(blob->wptr, bytes, len);
33,804✔
591
   blob->wptr += len;
33,804✔
592
}
593

594
void code_blob_align(code_blob_t *blob, unsigned align)
8,488✔
595
{
596
#ifdef ARCH_X86_64
597
   const uint8_t pad[] = { 0x90 };
8,488✔
598
#else
599
   const uint8_t pad[] = { 0x00 };
600
#endif
601

602
   assert(is_power_of_2(align));
8,488✔
603
   assert(align % ARRAY_LEN(pad) == 0);
604

605
   while (((uintptr_t)blob->wptr & (align - 1)) && !blob->overflow)
11,440✔
606
      code_blob_emit(blob, pad, ARRAY_LEN(pad));
2,952✔
607
}
8,488✔
608

609
void code_blob_mark(code_blob_t *blob, jit_label_t label)
71✔
610
{
611
   if (unlikely(blob->overflow))
71✔
612
      return;
613
   else if (blob->labels == NULL)
71✔
614
      blob->labels = ihash_new(256);
66✔
615

616
   ihash_put(blob->labels, label, blob->wptr);
71✔
617

618
   for (patch_list_t **p = &(blob->patches); *p; ) {
88✔
619
      if ((*p)->label == label) {
17✔
620
         patch_list_t *next = (*p)->next;
7✔
621
         (*(*p)->fn)(blob, label, (*p)->wptr, blob->wptr);
7✔
622
         free(*p);
7✔
623
         *p = next;
7✔
624
      }
625
      else
626
         p = &((*p)->next);
10✔
627
   }
628
}
629

630
void code_blob_patch(code_blob_t *blob, jit_label_t label, code_patch_fn_t fn)
8✔
631
{
632
   void *ptr = NULL;
8✔
633
   if (unlikely(blob->overflow))
8✔
634
      return;
635
   else if (blob->labels != NULL && (ptr = ihash_get(blob->labels, label)))
8✔
636
      (*fn)(blob, label, blob->wptr, ptr);
1✔
637
   else {
638
      patch_list_t *new = xmalloc(sizeof(patch_list_t));
7✔
639
      new->next  = blob->patches;
7✔
640
      new->fn    = fn;
7✔
641
      new->label = label;
7✔
642
      new->wptr  = blob->wptr;
7✔
643

644
      blob->patches = new;
7✔
645
   }
646
}
647

648
#ifdef DEBUG
649
static void code_blob_print_value(text_buf_t *tb, jit_value_t value)
392✔
650
{
651
   switch (value.kind) {
392✔
652
   case JIT_VALUE_REG:
162✔
653
      tb_printf(tb, "R%d", value.reg);
162✔
654
      break;
162✔
655
   case JIT_VALUE_INT64:
203✔
656
      if (value.int64 < 4096)
203✔
657
         tb_printf(tb, "#%"PRIi64, value.int64);
199✔
658
      else
659
         tb_printf(tb, "#0x%"PRIx64, value.int64);
4✔
660
      break;
661
   case JIT_VALUE_DOUBLE:
1✔
662
      tb_printf(tb, "%%%g", value.dval);
1✔
663
      break;
1✔
664
   case JIT_ADDR_CPOOL:
×
665
      tb_printf(tb, "[CP+%"PRIi64"]", value.int64);
×
666
      break;
×
667
   case JIT_ADDR_REG:
19✔
668
      tb_printf(tb, "[R%d", value.reg);
19✔
669
      if (value.disp != 0)
19✔
670
         tb_printf(tb, "+%d", value.disp);
1✔
671
      tb_cat(tb, "]");
19✔
672
      break;
19✔
673
   case JIT_ADDR_ABS:
×
674
      tb_printf(tb, "[#%016"PRIx64"]", value.int64);
×
675
      break;
×
676
   case JIT_ADDR_COVER:
×
677
      tb_printf(tb, "@%"PRIi64, value.int64);
×
678
      break;
×
679
   case JIT_VALUE_LABEL:
5✔
680
      tb_printf(tb, "%d", value.label);
5✔
681
      break;
5✔
682
   case JIT_VALUE_HANDLE:
2✔
683
      tb_printf(tb, "<%d>", value.handle);
2✔
684
      break;
2✔
685
   case JIT_VALUE_EXIT:
×
686
      tb_printf(tb, "%s", jit_exit_name(value.exit));
×
687
      break;
×
688
   case JIT_VALUE_LOC:
×
689
      tb_printf(tb, "<%s:%d>", loc_file_str(&value.loc), value.loc.first_line);
×
690
      break;
×
691
   case JIT_VALUE_LOCUS:
×
692
      tb_printf(tb, "%p", value.locus);
×
693
      break;
×
694
   case JIT_VALUE_VPOS:
×
695
      tb_printf(tb, "%u:%u", value.vpos.block, value.vpos.op);
×
696
      break;
×
697
   default:
×
698
      tb_cat(tb, "???");
×
699
   }
700
}
392✔
701

702
static void code_blob_add_comment(code_blob_t *blob, uintptr_t addr, char *text)
70,932✔
703
{
704
   code_debug_t *dbg = &(blob->span->debug);
70,932✔
705

706
   if (dbg->count == dbg->max) {
70,932✔
707
      dbg->max = MAX(128, dbg->max * 2);
8,019✔
708
      dbg->comments = xrealloc_array(dbg->comments, dbg->max,
8,019✔
709
                                     sizeof(code_comment_t));
710
   }
711

712
   dbg->comments[dbg->count].addr = addr;
70,932✔
713
   dbg->comments[dbg->count].text = text;
70,932✔
714
   dbg->count++;
70,932✔
715
}
70,932✔
716

717
void code_blob_print_ir(code_blob_t *blob, jit_ir_t *ir)
348✔
718
{
719
   LOCAL_TEXT_BUF tb = tb_new();
696✔
720
   tb_printf(tb, "%s%s", jit_op_name(ir->op), jit_cc_name(ir->cc));
348✔
721

722
   if (ir->size != JIT_SZ_UNSPEC)
348✔
723
      tb_printf(tb, ".%d", 1 << (3 + ir->size));
36✔
724

725
   tb_printf(tb, "%*.s", (int)MAX(0, 10 - tb_len(tb)), "");
348✔
726

727
   if (ir->result != JIT_REG_INVALID)
348✔
728
      tb_printf(tb, "R%d", ir->result);
203✔
729

730
   if (ir->arg1.kind != JIT_VALUE_INVALID) {
348✔
731
      if (ir->result != JIT_REG_INVALID)
263✔
732
         tb_cat(tb, ", ");
187✔
733
      code_blob_print_value(tb, ir->arg1);
263✔
734
   }
735

736
   if (ir->arg2.kind != JIT_VALUE_INVALID) {
348✔
737
      tb_cat(tb, ", ");
129✔
738
      code_blob_print_value(tb, ir->arg2);
129✔
739
   }
740

741
   code_blob_add_comment(blob, (uintptr_t)blob->wptr, tb_claim(tb));
348✔
742
}
348✔
743

744
void code_blob_printf(code_blob_t *blob, const char *fmt, ...)
25,637✔
745
{
746
   va_list ap;
25,637✔
747
   va_start(ap, fmt);
25,637✔
748

749
   char *text = xvasprintf(fmt, ap);
25,637✔
750
   code_blob_add_comment(blob, (uintptr_t)blob->wptr, text);
25,637✔
751

752
   va_end(ap);
25,637✔
753
}
25,637✔
754

755
__attribute__((format(printf, 3, 4)))
756
static void debug_reloc(code_blob_t *blob, void *patch, const char *fmt, ...)
44,947✔
757
{
758
   va_list ap;
44,947✔
759
   va_start(ap, fmt);
44,947✔
760

761
   char *text = xvasprintf(fmt, ap);
44,947✔
762
   code_blob_add_comment(blob, (uintptr_t)patch, text);
44,947✔
763

764
   va_end(ap);
44,947✔
765
}
44,947✔
766
#else
767
#define debug_reloc(...)
768
#endif   // DEBUG
769

770
#ifdef ARCH_ARM64
771
static void arm64_patch_page_offset21(code_blob_t *blob, uint32_t *patch,
772
                                      void *ptr)
773
{
774
   switch ((*patch >> 23) & 0x7f) {
775
   case 0b1111010:   // LDR (immediate, SIMD&FP)
776
   case 0b1110010:   // LDR (immediate)
777
      assert(*patch & (1 << 30));  // Quadword
778
      assert(((uintptr_t)ptr & 7) == 0);
779
      *patch |= (((uintptr_t)ptr & 0xfff) >> 3) << 10;
780
      break;
781
   case 0b0100010:   // ADD (immediate)
782
      *patch |= ((uintptr_t)ptr & 0xfff) << 10;
783
      break;
784
   default:
785
      blob->span->size = blob->wptr - blob->span->base;
786
      code_disassemble(blob->span, (uintptr_t)patch, NULL);
787
      fatal_trace("cannot patch instruction");
788
   }
789
}
790

791
static void arm64_patch_page_base_rel21(uint32_t *patch, void *ptr)
792
{
793
   const intptr_t dst_page = (intptr_t)ptr & ~UINT64_C(0xfff);
794
   const intptr_t src_page = (intptr_t)patch & ~UINT64_C(0xfff);
795
   const intptr_t upper21 = (dst_page - src_page) >> 12;
796
   *(uint32_t *)patch |= (upper21 & 3) << 29;
797
   *(uint32_t *)patch |= ((upper21 >> 2) & 0x7ffff) << 5;
798
}
799
#endif
800

801
static void *code_emit_trampoline(code_blob_t *blob, void *dest)
40,807✔
802
{
803
#if defined ARCH_X86_64
804
   const uint8_t veneer[] = {
40,807✔
805
      0x48, 0xb8, __IMM64((uintptr_t)dest),  // MOVABS RAX, dest
40,807✔
806
      0xff, 0xe0                             // CALL RAX
807
   };
808
#elif defined ARCH_ARM64
809
   const uint8_t veneer[] = {
810
      0x50, 0x00, 0x00, 0x58,   // LDR X16, [PC+8]
811
      0x00, 0x02, 0x1f, 0xd6,   // BR X16
812
      __IMM64((uintptr_t)dest)
813
   };
814
#else
815
   should_not_reach_here();
816
#endif
817

818
   void *prev = memmem(blob->span->base, blob->span->size,
40,807✔
819
                       veneer, ARRAY_LEN(veneer));
820
   if (prev != NULL)
40,807✔
821
      return prev;
822
   else {
823
      DEBUG_ONLY(code_blob_printf(blob, "Trampoline for %p", dest));
17,149✔
824

825
      void *addr = blob->wptr;
17,149✔
826
      code_blob_emit(blob, veneer, ARRAY_LEN(veneer));
17,149✔
827
      return addr;
17,149✔
828
   }
829
}
830

831
#if defined __MINGW32__
832
static void code_load_pe(code_blob_t *blob, const void *data, size_t size)
833
{
834
   const IMAGE_FILE_HEADER *imghdr = data;
835

836
   switch (imghdr->Machine) {
837
   case IMAGE_FILE_MACHINE_AMD64:
838
   case IMAGE_FILE_MACHINE_ARM64:
839
      break;
840
   default:
841
      fatal_trace("unknown target machine %x", imghdr->Machine);
842
   }
843

844
   const IMAGE_SYMBOL *symtab = data + imghdr->PointerToSymbolTable;
845
   const char *strtab = data + imghdr->PointerToSymbolTable
846
      + imghdr->NumberOfSymbols * sizeof(IMAGE_SYMBOL);
847

848
   const IMAGE_SECTION_HEADER *sections =
849
      data + IMAGE_SIZEOF_FILE_HEADER + imghdr->SizeOfOptionalHeader;
850

851
   void **load_addr LOCAL =
852
      xmalloc_array(imghdr->NumberOfSections, sizeof(void *));
853

854
   for (int i = 0; i < imghdr->NumberOfSections; i++) {
855
      if ((sections[i].Characteristics & IMAGE_SCN_CNT_CODE)
856
          || (sections[i].Characteristics & IMAGE_SCN_CNT_INITIALIZED_DATA)) {
857
         const int align = sections[i].Characteristics & IMAGE_SCN_ALIGN_MASK;
858
         code_blob_align(blob, 1 << ((align >> 20) - 1));
859
         load_addr[i] = blob->wptr;
860
         code_blob_emit(blob, data + sections[i].PointerToRawData,
861
                        sections[i].SizeOfRawData);
862
      }
863
      else if ((sections[i].Characteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA)
864
               && sections[i].Misc.VirtualSize > 0)
865
         fatal_trace("non-empty BSS not supported");
866
   }
867

868
   if (blob->overflow)
869
      return;   // Relocations might point outside of code span
870

871
   for (int i = 0; i < imghdr->NumberOfSections; i++) {
872
      const IMAGE_RELOCATION *relocs = data + sections[i].PointerToRelocations;
873
      for (int j = 0; j < sections[i].NumberOfRelocations; j++) {
874
         const char *name = NULL;
875
         char tmp[9];
876

877
         assert(relocs[j].SymbolTableIndex < imghdr->NumberOfSymbols);
878
         const IMAGE_SYMBOL *sym = symtab + relocs[j].SymbolTableIndex;
879

880
         if (sym->N.Name.Short) {
881
            memcpy(tmp, sym->N.ShortName, 8);
882
            tmp[8] = '\0';
883
            name = tmp;
884
         }
885
         else
886
            name = strtab + sym->N.Name.Long;
887

888
         void *ptr = NULL;
889
         if (sym->SectionNumber > 0) {
890
            assert(sym->SectionNumber - 1 < imghdr->NumberOfSections);
891
            ptr = load_addr[sym->SectionNumber - 1] + sym->Value;
892
         }
893
#ifdef ARCH_X86_64
894
         else if (strcmp(name, "___chkstk_ms") == 0) {
895
            extern void ___chkstk_ms(void);
896
            ptr = &___chkstk_ms;
897
         }
898
#endif
899
         else
900
            ptr = ffi_find_symbol(NULL, name);
901

902
         if (ptr == NULL && icmp(blob->span->name, name))
903
            ptr = blob->span->base;
904

905
         if (ptr == NULL)
906
            fatal_trace("failed to resolve symbol %s", name);
907

908
         void *patch = load_addr[i] + relocs[j].VirtualAddress;
909
         assert((uint8_t *)patch >= blob->span->base);
910
         assert((uint8_t *)patch < blob->span->base + blob->span->size);
911

912
         switch (relocs[j].Type) {
913
#if defined ARCH_X86_64
914
         case IMAGE_REL_AMD64_ADDR64:
915
            *(uint64_t *)patch += (uint64_t)ptr;
916
            break;
917
         case IMAGE_REL_AMD64_ADDR32NB:
918
            *(uint32_t *)patch += (uint32_t)(ptr - (void *)blob->span->base);
919
            break;
920
#elif defined ARCH_ARM64
921
         case IMAGE_REL_ARM64_BRANCH26:
922
            {
923
               void *veneer = code_emit_trampoline(blob, ptr);
924
               const ptrdiff_t pcrel = (veneer - patch) >> 2;
925
               *(uint32_t *)patch &= ~0x3ffffff;
926
               *(uint32_t *)patch |= pcrel & 0x3ffffff;
927
            }
928
            break;
929
         case IMAGE_REL_ARM64_ADDR32NB:
930
            *(uint32_t *)patch += (uint32_t)(ptr - (void *)blob->span->base);
931
            break;
932
         case IMAGE_REL_ARM64_PAGEBASE_REL21:
933
            arm64_patch_page_base_rel21(patch, ptr);
934
            break;
935
         case IMAGE_REL_ARM64_PAGEOFFSET_12A:
936
         case IMAGE_REL_ARM64_PAGEOFFSET_12L:
937
            arm64_patch_page_offset21(blob, patch, ptr);
938
            break;
939
#endif
940
         default:
941
            blob->span->size = blob->wptr - blob->span->base;
942
            code_disassemble(blob->span, (uintptr_t)patch, NULL);
943
            fatal_trace("cannot handle relocation type %d for symbol %s",
944
                        relocs[j].Type, name);
945
         }
946
      }
947

948
      if (strncmp((const char *)sections[i].Name, ".pdata",
949
                  IMAGE_SIZEOF_SHORT_NAME) == 0) {
950
         assert(sections[i].SizeOfRawData % sizeof(RUNTIME_FUNCTION) == 0);
951
         const int count = sections[i].SizeOfRawData / sizeof(RUNTIME_FUNCTION);
952
         const DWORD64 base = (DWORD64)blob->span->base;
953

954
         // TODO: we should also call RtlDeleteFunctionTable at some point
955
         if (!RtlAddFunctionTable(load_addr[i], count, base))
956
            fatal_trace("RtlAddFunctionTable failed: %s", last_os_error());
957
      }
958
   }
959

960
   for (int i = 0; i < imghdr->NumberOfSymbols; i++) {
961
      const IMAGE_SYMBOL *sym = &(symtab[i]);
962

963
      if (sym->SectionNumber == 0 || sym->N.Name.Short)
964
         continue;
965
      else if ((sym->Type >> 4) != IMAGE_SYM_DTYPE_FUNCTION)
966
         continue;
967
      else if (icmp(blob->span->name, strtab + sym->N.Name.Long)) {
968
         blob->span->entry = load_addr[sym->SectionNumber - 1] + sym->Value;
969
         break;
970
      }
971
   }
972
}
973
#elif defined __APPLE__
974
static void code_load_macho(code_blob_t *blob, const void *data, size_t size)
975
{
976
   const void *rptr = data;
977

978
   const struct mach_header_64 *fhdr = rptr;
979
   rptr += sizeof(struct mach_header_64);
980

981
   if (fhdr->magic != MH_MAGIC_64)
982
      fatal_trace("bad Mach-O magic %x", fhdr->magic);
983

984
   const struct segment_command_64 *seg = NULL;
985
   const struct symtab_command *symtab = NULL;
986

987
   void **load_addr LOCAL = NULL;
988

989
   for (int i = 0; i < fhdr->ncmds; i++) {
990
      const struct load_command *load = rptr;
991
      switch (load->cmd) {
992
      case LC_SEGMENT_64:
993
         {
994
            seg = rptr;
995
            load_addr = xmalloc_array(seg->nsects, sizeof(void *));
996

997
            for (int j = 0; j < seg->nsects; j++) {
998
               const struct section_64 *sec =
999
                  (void *)seg + sizeof(struct segment_command_64)
1000
                  + j * sizeof(struct section_64);
1001
               code_blob_align(blob, 1 << sec->align);
1002
               load_addr[j] = blob->wptr;
1003
               code_blob_emit(blob, data + sec->offset, sec->size);
1004
            }
1005
         }
1006
         break;
1007
      case LC_SYMTAB:
1008
         symtab = rptr;
1009
         assert(symtab->cmdsize == sizeof(struct symtab_command));
1010
         break;
1011
      case LC_DATA_IN_CODE:
1012
      case LC_LINKER_OPTIMIZATION_HINT:
1013
      case LC_BUILD_VERSION:
1014
      case LC_DYSYMTAB:
1015
         break;
1016
      default:
1017
         warnf("unrecognised load command 0x%0x", load->cmd);
1018
      }
1019

1020
      rptr += load->cmdsize;
1021
   }
1022
   assert(rptr == data + sizeof(struct mach_header_64) + fhdr->sizeofcmds);
1023

1024
   if (blob->overflow)
1025
      return;   // Relocations might point outside of code span
1026

1027
   assert(seg != NULL);
1028
   assert(symtab != NULL);
1029

1030
   for (int i = 0; i < seg->nsects; i++) {
1031
      const struct section_64 *sec =
1032
         (void *)seg + sizeof(struct segment_command_64)
1033
         + i * sizeof(struct section_64);
1034

1035
      uint32_t addend = 0;
1036
      for (int j = 0; j < sec->nreloc; j++) {
1037
         const struct relocation_info *rel =
1038
            data + sec->reloff + j * sizeof(struct relocation_info);
1039
         const char *name = NULL;
1040
         void *ptr = NULL;
1041
         if (rel->r_extern) {
1042
            assert(rel->r_symbolnum < symtab->nsyms);
1043
            const struct nlist_64 *nl = data + symtab->symoff
1044
               + rel->r_symbolnum * sizeof(struct nlist_64);
1045
            name = data + symtab->stroff + nl->n_un.n_strx;
1046

1047
            if (nl->n_type & N_EXT) {
1048
               if (icmp(blob->span->name, name + 1))
1049
                  ptr = blob->span->base;
1050
               else if ((ptr = ffi_find_symbol(NULL, name + 1)) == NULL)
1051
                  fatal_trace("failed to resolve symbol %s", name + 1);
1052
            }
1053
            else if (nl->n_sect != NO_SECT)
1054
               ptr = blob->span->base + nl->n_value;
1055
         }
1056
         else
1057
            ptr = blob->span->base;
1058

1059
         ptr += addend;
1060
         addend = 0;
1061

1062
         void *patch = load_addr[i] + rel->r_address;
1063
         assert((uint8_t *)patch >= blob->span->base);
1064
         assert((uint8_t *)patch < blob->span->base + blob->span->size);
1065

1066
         switch (rel->r_type) {
1067
#ifdef ARCH_ARM64
1068
         case ARM64_RELOC_UNSIGNED:
1069
            assert(rel->r_length == 3);
1070
            *(void **)patch = ptr;
1071
            break;
1072
         case ARM64_RELOC_SUBTRACTOR:
1073
            break;   // What is this?
1074
         case ARM64_RELOC_GOT_LOAD_PAGEOFF12:
1075
         case ARM64_RELOC_PAGEOFF12:
1076
            arm64_patch_page_offset21(blob, patch, ptr);
1077
            break;
1078
         case ARM64_RELOC_GOT_LOAD_PAGE21:
1079
         case ARM64_RELOC_PAGE21:
1080
            arm64_patch_page_base_rel21(patch, ptr);
1081
            break;
1082
         case ARM64_RELOC_BRANCH26:
1083
            {
1084
               void *veneer = code_emit_trampoline(blob, ptr);
1085
               const ptrdiff_t pcrel = (veneer - patch) >> 2;
1086
               *(uint32_t *)patch &= ~0x3ffffff;
1087
               *(uint32_t *)patch |= pcrel & 0x3ffffff;
1088
            }
1089
            break;
1090
         case ARM64_RELOC_ADDEND:
1091
            addend = rel->r_symbolnum;
1092
            break;
1093
#elif defined ARCH_X86_64
1094
         case X86_64_RELOC_UNSIGNED:
1095
            *(uint64_t *)patch += (uint64_t)ptr;
1096
            break;
1097
         case X86_64_RELOC_BRANCH:
1098
            *(uint32_t *)patch += (uint32_t)(ptr - patch - 4);
1099
            break;
1100
#endif
1101
         default:
1102
            blob->span->size = blob->wptr - blob->span->base;
1103
            code_disassemble(blob->span, (uintptr_t)patch, NULL);
1104
            fatal_trace("cannot handle relocation type %d for symbol %s",
1105
                        rel->r_type, name);
1106
         }
1107
      }
1108
   }
1109

1110
   for (int i = 0; i < symtab->nsyms; i++) {
1111
      const struct nlist_64 *sym =
1112
         data + symtab->symoff + i * sizeof(struct nlist_64);
1113

1114
      if (sym->n_sect == NO_SECT || (sym->n_type & N_TYPE) != N_SECT)
1115
         continue;
1116

1117
      const char *name = data + symtab->stroff + sym->n_un.n_strx;
1118
      if (name[0] == '_' && icmp(blob->span->name, name + 1)) {
1119
         blob->span->entry = load_addr[sym->n_sect - 1] + sym->n_value;
1120
         break;
1121
      }
1122
   }
1123
}
1124
#elif !defined __MINGW32__
1125
static void code_load_elf(code_blob_t *blob, const void *data, size_t size)
7,943✔
1126
{
1127
   const Elf64_Ehdr *ehdr = data;
7,943✔
1128

1129
   if (ehdr->e_ident[EI_MAG0] != ELFMAG0
7,943✔
1130
       || ehdr->e_ident[EI_MAG1] != ELFMAG1
1131
       || ehdr->e_ident[EI_MAG2] != ELFMAG2
1132
       || ehdr->e_ident[EI_MAG3] != ELFMAG3)
7,943✔
1133
      fatal_trace("bad ELF magic");
1134
   else if (ehdr->e_shentsize != sizeof(Elf64_Shdr))
7,943✔
1135
      fatal_trace("bad section header size %d != %zu", ehdr->e_shentsize,
1136
                  sizeof(Elf64_Shdr));
1137

1138
   const Elf64_Shdr *strtab_hdr =
7,943✔
1139
      data + ehdr->e_shoff + ehdr->e_shstrndx * ehdr->e_shentsize;
7,943✔
1140
   const char *strtab = data + strtab_hdr->sh_offset;
7,943✔
1141

1142
   void **load_addr LOCAL = xcalloc_array(ehdr->e_shnum, sizeof(void *));
15,886✔
1143

1144
   for (int i = 0; i < ehdr->e_shnum; i++) {
71,944✔
1145
      const Elf64_Shdr *shdr = data + ehdr->e_shoff + i * ehdr->e_shentsize;
64,001✔
1146

1147
      switch (shdr->sh_type) {
64,001✔
1148
      case SHT_PROGBITS:
16,431✔
1149
         if (shdr->sh_flags & SHF_ALLOC) {
16,431✔
1150
            code_blob_align(blob, shdr->sh_addralign);
8,488✔
1151
            load_addr[i] = blob->wptr;
8,488✔
1152
            DEBUG_ONLY(code_blob_printf(blob, "%s", strtab + shdr->sh_name));
8,488✔
1153
            code_blob_emit(blob, data + shdr->sh_offset, shdr->sh_size);
8,488✔
1154
         }
1155
         break;
1156

1157
      case SHT_RELA:
1158
         // Handled in second pass
1159
         break;
1160

1161
      case SHT_NULL:
1162
      case SHT_STRTAB:
1163
      case SHT_X86_64_UNWIND:
1164
         break;
1165

1166
      case SHT_SYMTAB:
1167
         for (int i = 0; i < shdr->sh_size / shdr->sh_entsize; i++) {
32,317✔
1168
            const Elf64_Sym *sym =
32,317✔
1169
               data + shdr->sh_offset + i * shdr->sh_entsize;
32,317✔
1170

1171
            if (ELF64_ST_TYPE(sym->st_info) != STT_FUNC)
32,317✔
1172
               continue;
24,374✔
1173
            else if (!icmp(blob->span->name, strtab + sym->st_name))
7,943✔
1174
               continue;
×
1175
            else if (load_addr[sym->st_shndx] == NULL)
7,943✔
1176
               fatal_trace("missing section %d for symbol %s", sym->st_shndx,
1177
                           strtab + sym->st_name);
×
1178
            else {
1179
               blob->span->entry = load_addr[sym->st_shndx] + sym->st_value;
7,943✔
1180
               break;
7,943✔
1181
            }
1182
         }
1183
         break;
1184

1185
      default:
×
1186
         warnf("ignoring ELF section %s with type %x", strtab + shdr->sh_name,
×
1187
               shdr->sh_type);
1188
      }
1189
   }
1190

1191
   if (blob->overflow)
7,943✔
1192
      return;   // Relocations might point outside of code span
×
1193

1194
   for (int i = 0; i < ehdr->e_shnum; i++) {
71,944✔
1195
      const Elf64_Shdr *shdr = data + ehdr->e_shoff + i * ehdr->e_shentsize;
64,001✔
1196
      if (shdr->sh_type != SHT_RELA)
64,001✔
1197
         continue;
48,203✔
1198

1199
      const Elf64_Shdr *mod =
15,798✔
1200
         data + ehdr->e_shoff + shdr->sh_info * ehdr->e_shentsize;
15,798✔
1201
      if (mod->sh_type != SHT_PROGBITS || !(mod->sh_flags & SHF_ALLOC))
15,798✔
1202
         continue;
7,943✔
1203
      else if (load_addr[shdr->sh_info] == NULL)
7,855✔
1204
         fatal_trace("section %s not loaded", strtab + mod->sh_name);
1205

1206
      const Elf64_Shdr *symtab =
7,855✔
1207
         data + ehdr->e_shoff + shdr->sh_link * ehdr->e_shentsize;
7,855✔
1208
      if (symtab->sh_type != SHT_SYMTAB)
7,855✔
1209
         fatal_trace("section %s is not a symbol table",
1210
                     strtab + symtab->sh_name);
×
1211

1212
      const Elf64_Rela *endp = data + shdr->sh_offset + shdr->sh_size;
7,855✔
1213
      for (const Elf64_Rela *r = data + shdr->sh_offset; r < endp; r++) {
52,802✔
1214
         const Elf64_Sym *sym = data + symtab->sh_offset
44,947✔
1215
            + ELF64_R_SYM(r->r_info) * symtab->sh_entsize;
44,947✔
1216

1217
         char *ptr = NULL;
44,947✔
1218
         switch (ELF64_ST_TYPE(sym->st_info)) {
44,947✔
1219
         case STT_NOTYPE:
40,851✔
1220
         case STT_FUNC:
1221
            ptr = ffi_find_symbol(NULL, strtab + sym->st_name);
40,851✔
1222
            break;
40,851✔
1223
         case STT_SECTION:
4,096✔
1224
            ptr = load_addr[sym->st_shndx];
4,096✔
1225
            break;
4,096✔
1226
         }
1227

1228
         if (ptr == NULL && icmp(blob->span->name, strtab + sym->st_name))
44,947✔
1229
            ptr = (char *)blob->span->base;
44✔
1230

1231
         if (ptr == NULL && sym->st_shndx != 0)
44,947✔
NEW
1232
            ptr = load_addr[sym->st_shndx] + sym->st_value;
×
1233

1234
         if (ptr == NULL)
44,947✔
1235
            fatal_trace("cannot resolve symbol %s type %d",
1236
                        strtab + sym->st_name, ELF64_ST_TYPE(sym->st_info));
×
1237

1238
         void *patch = load_addr[shdr->sh_info] + r->r_offset;
44,947✔
1239
         assert(r->r_offset < mod->sh_size);
44,947✔
1240

1241
         switch (ELF64_R_TYPE(r->r_info)) {
44,947✔
1242
         case R_X86_64_64:
4,096✔
1243
            debug_reloc(blob, patch, "R_X86_64_64 %s", strtab + sym->st_name);
4,096✔
1244
            *(uint64_t *)patch = (uint64_t)ptr + r->r_addend;
4,096✔
1245
            break;
4,096✔
1246
         case R_X86_64_PC32:
44✔
1247
         case R_X86_64_GOTPCREL:
1248
            {
1249
               const ptrdiff_t pcrel = ptr + r->r_addend - (char *)patch;
44✔
1250
               debug_reloc(blob, patch, "R_X86_64_PC32 %s PC%+"PRIiPTR,
44✔
1251
                           strtab + sym->st_name, pcrel);
44✔
1252
               assert(pcrel >= INT32_MIN && pcrel <= INT32_MAX);
44✔
1253
               *(uint32_t *)patch = pcrel;
44✔
1254
            }
1255
            break;
44✔
1256
         case R_X86_64_PLT32:
40,807✔
1257
            {
1258
               void *veneer = code_emit_trampoline(blob, ptr);
40,807✔
1259
               const ptrdiff_t pcrel = veneer + r->r_addend - patch;
40,807✔
1260
               debug_reloc(blob, patch, "R_X86_64_PLT32 %s PC%+"PRIiPTR,
40,807✔
1261
                           strtab + sym->st_name, pcrel);
40,807✔
1262
               assert(pcrel >= INT32_MIN && pcrel <= INT32_MAX);
40,807✔
1263
               *(uint32_t *)patch = pcrel;
40,807✔
1264
            }
1265
            break;
40,807✔
1266
         case R_AARCH64_CALL26:
×
1267
            {
NEW
1268
               void *veneer = code_emit_trampoline(blob, ptr);
×
NEW
1269
               const ptrdiff_t pcrel = (veneer + r->r_addend - patch) >> 2;
×
1270
               *(uint32_t *)patch &= ~0x3ffffff;
×
1271
               *(uint32_t *)patch |= pcrel & 0x3ffffff;
×
1272
            }
1273
            break;
×
1274
         case R_AARCH64_PREL64:
×
NEW
1275
            *(uint64_t *)patch = ptr + r->r_addend - (char *)patch;
×
1276
            break;
×
1277
         case R_AARCH64_MOVW_UABS_G0_NC:
×
NEW
1278
            *(uint32_t *)patch |=
×
NEW
1279
               (((uintptr_t)ptr + r->r_addend) & 0xffff) << 5;
×
1280
            break;
×
1281
         case R_AARCH64_MOVW_UABS_G1_NC:
×
NEW
1282
            *(uint32_t *)patch |=
×
NEW
1283
               ((((uintptr_t)ptr + r->r_addend) >> 16) & 0xffff) << 5;
×
1284
            break;
×
1285
         case R_AARCH64_MOVW_UABS_G2_NC:
×
NEW
1286
            *(uint32_t *)patch |=
×
NEW
1287
               ((((uintptr_t)ptr + r->r_addend) >> 32) & 0xffff) << 5;
×
1288
            break;
×
1289
         case R_AARCH64_MOVW_UABS_G3:
×
NEW
1290
            *(uint32_t *)patch |=
×
NEW
1291
               ((((uintptr_t)ptr + r->r_addend) >> 48) & 0xffff) << 5;
×
1292
            break;
×
1293
         default:
×
1294
            blob->span->size = blob->wptr - blob->span->base;
×
1295
            code_disassemble(blob->span, (uintptr_t)patch, NULL);
×
1296
            fatal_trace("cannot handle relocation type %ld for symbol %s",
1297
                        ELF64_R_TYPE(r->r_info), strtab + sym->st_name);
×
1298
         }
1299
      }
1300
   }
1301
}
1302
#endif
1303

1304
void code_load_object(code_blob_t *blob, const void *data, size_t size)
7,943✔
1305
{
1306
#if defined __APPLE__
1307
   code_load_macho(blob, data, size);
1308
#elif defined __MINGW32__
1309
   code_load_pe(blob, data, size);
1310
#else
1311
   code_load_elf(blob, data, size);
7,943✔
1312
#endif
1313
}
7,943✔
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