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

nickg / nvc / 14576867610

21 Apr 2025 04:13PM UTC coverage: 92.329%. Remained the same
14576867610

push

github

nickg
Restrict symbols accessible from JIT

23 of 24 new or added lines in 1 file covered. (95.83%)

1 existing line in 1 file now uncovered.

69236 of 74988 relevant lines covered (92.33%)

418852.03 hits per line

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

74.71
/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 "object.h"
25
#include "option.h"
26
#include "thread.h"
27

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

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

49
#ifdef HAVE_CAPSTONE
50
#include <capstone.h>
51
#endif
52

53
#ifndef R_AARCH64_MOVW_UABS_G0_NC
54
#define R_AARCH64_MOVW_UABS_G0_NC 264
55
#endif
56

57
#ifndef R_AARCH64_MOVW_UABS_G1_NC
58
#define R_AARCH64_MOVW_UABS_G1_NC 266
59
#endif
60

61
#ifndef R_AARCH64_MOVW_UABS_G2_NC
62
#define R_AARCH64_MOVW_UABS_G2_NC 268
63
#endif
64

65
#ifndef R_AARCH64_MOVW_UABS_G3
66
#define R_AARCH64_MOVW_UABS_G3 269
67
#endif
68

69
#ifndef SHT_X86_64_UNWIND
70
#define SHT_X86_64_UNWIND 0x70000001
71
#endif
72

73
#ifndef IMAGE_REL_ARM64_BRANCH26
74
#define IMAGE_REL_ARM64_BRANCH26 0x03
75
#endif
76

77
#ifndef IMAGE_REL_ARM64_ADDR32NB
78
#define IMAGE_REL_ARM64_ADDR32NB 0x02
79
#endif
80

81
#ifndef IMAGE_REL_ARM64_PAGEBASE_REL21
82
#define IMAGE_REL_ARM64_PAGEBASE_REL21 0x04
83
#endif
84

85
#ifndef IMAGE_REL_ARM64_PAGEOFFSET_12A
86
#define IMAGE_REL_ARM64_PAGEOFFSET_12A 0x06
87
#endif
88

89
#ifndef IMAGE_REL_ARM64_PAGEOFFSET_12L
90
#define IMAGE_REL_ARM64_PAGEOFFSET_12L 0x07
91
#endif
92

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

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

103
STATIC_ASSERT(MIN_BLOB_SIZE <= THREAD_CACHE_SIZE);
104
STATIC_ASSERT(MIN_BLOB_SIZE % CODE_BLOB_ALIGN == 0);
105
STATIC_ASSERT(CODE_PAGE_SIZE % THREAD_CACHE_SIZE == 0);
106

107
typedef struct _code_page code_page_t;
108

109
typedef struct {
110
   uintptr_t  addr;
111
   char      *text;
112
} code_comment_t;
113

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

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

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

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

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

161
static void code_disassemble(code_span_t *span, uintptr_t mark,
162
                             struct cpu_state *cpu);
163

164
static void code_cache_unwinder(uintptr_t addr, debug_frame_t *frame,
×
165
                                void *context)
166
{
167
   code_cache_t *code = context;
×
168

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

179
static void code_fault_handler(int sig, void *addr, struct cpu_state *cpu,
×
180
                               void *context)
181
{
182
   code_page_t *page = context;
×
183

184
   const uint8_t *pc = (uint8_t *)cpu->pc;
×
185
   if (pc < page->mem || pc > page->mem + CODE_PAGE_SIZE)
×
186
      return;
187

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

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

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

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

210
   return false;
211
}
212
#endif
213

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

219
   assert(code_cache_contains(code, base, size));
9,472✔
220

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

229
   code->spans = span;
9,472✔
230
   return span;
9,472✔
231
}
232

233
static void code_page_new(code_cache_t *code)
3,597✔
234
{
235
   assert_lock_held(&code->lock);
3,597✔
236

237
   code_page_t *page = xcalloc(sizeof(code_page_t));
3,597✔
238
   page->owner = code;
3,597✔
239
   page->next  = code->pages;
3,597✔
240
   page->mem   = map_jit_pages(CODE_PAGE_ALIGN, CODE_PAGE_SIZE);
3,597✔
241

242
   add_fault_handler(code_fault_handler, page);
3,597✔
243
   debug_add_unwinder(page->mem, CODE_PAGE_SIZE, code_cache_unwinder, code);
3,597✔
244

245
   code->pages = page;
3,597✔
246

247
   code_span_t *span = xcalloc(sizeof(code_span_t));
3,597✔
248
   span->next  = code->spans;
3,597✔
249
   span->base  = page->mem;
3,597✔
250
   span->size  = CODE_PAGE_SIZE;
3,597✔
251
   span->owner = code;
3,597✔
252

253
   code->globalfree = code->spans = span;
3,597✔
254
}
3,597✔
255

256
code_cache_t *code_cache_new(void)
3,591✔
257
{
258
   code_cache_t *code = xcalloc(sizeof(code_cache_t));
3,591✔
259

260
   {
261
      SCOPED_LOCK(code->lock);
7,182✔
262
      code_page_new(code);
3,591✔
263
   }
264

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

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

280
   shash_t *s = shash_new(32);
3,591✔
281

282
   extern void __nvc_putpriv(jit_handle_t, void *);
3,591✔
283
   extern void __nvc_sched_waveform(jit_anchor_t *, jit_scalar_t *, tlab_t *);
3,591✔
284
   extern void __nvc_sched_process(jit_anchor_t *, jit_scalar_t *, tlab_t *);
3,591✔
285
   extern void __nvc_test_event(jit_anchor_t *, jit_scalar_t *, tlab_t *);
3,591✔
286
   extern void __nvc_last_event(jit_anchor_t *, jit_scalar_t *, tlab_t *);
3,591✔
287

288
   shash_put(s, "__nvc_sched_waveform", &__nvc_sched_waveform);
3,591✔
289
   shash_put(s, "__nvc_sched_process", &__nvc_sched_process);
3,591✔
290
   shash_put(s, "__nvc_test_event", &__nvc_test_event);
3,591✔
291
   shash_put(s, "__nvc_last_event", &__nvc_last_event);
3,591✔
292
   shash_put(s, "__nvc_mspace_alloc", &__nvc_mspace_alloc);
3,591✔
293
   shash_put(s, "__nvc_putpriv", &__nvc_putpriv);
3,591✔
294
   shash_put(s, "__nvc_do_exit", &__nvc_do_exit);
3,591✔
295
   shash_put(s, "memmove", &memmove);
3,591✔
296
   shash_put(s, "memcpy", &memcpy);
3,591✔
297
   shash_put(s, "memset", &memset);
3,591✔
298
   shash_put(s, "pow", &pow);
3,591✔
299

300

301
#if defined __APPLE__
302
   shash_put(s, "bzero", &bzero);
303
#endif
304

305
#if defined __MINGW32__ && defined ARCH_X86_64
306
   extern void ___chkstk_ms(void);
307
   shash_put(s, "___chkstk_ms", &___chkstk_ms);
308
#endif
309

310
   store_release(&code->symbols, s);
3,591✔
311

312
   return code;
3,591✔
313
}
314

315
void code_cache_free(code_cache_t *code)
3,589✔
316
{
317
   for (code_page_t *it = code->pages, *tmp; it; it = tmp) {
7,184✔
318
      debug_remove_unwinder(it->mem);
3,595✔
319
      remove_fault_handler(code_fault_handler, it);
3,595✔
320

321
      nvc_munmap(it->mem, CODE_PAGE_SIZE);
3,595✔
322

323
      tmp = it->next;
3,595✔
324
      free(it);
3,595✔
325
   }
326

327
   for (code_span_t *it = code->spans, *tmp; it; it = tmp) {
16,656✔
328
      tmp = it->next;
13,067✔
329
      free(it);
13,067✔
330
   }
331

332
#ifdef HAVE_CAPSTONE
333
   cs_close(&(code->capstone));
334
#endif
335

336
#ifdef DEBUG
337
   if (code->used > 0)
3,589✔
338
      debugf("JIT code footprint: %zu bytes", code->used);
1,272✔
339
#endif
340

341
   shash_free(code->symbols);
3,589✔
342
   free(code);
3,589✔
343
}
3,589✔
344

345
#ifdef HAVE_CAPSTONE
346
static int code_print_spaces(int col, int tab)
347
{
348
   for (; col < tab; col++)
349
      fputc(' ', stdout);
350
   return col;
351
}
352
#endif
353

354
#ifdef DEBUG
355
static int code_comment_compare(const void *a, const void *b)
356
{
357
   const code_comment_t *ca = a;
358
   const code_comment_t *cb = b;
359

360
   if (ca->addr < cb->addr)
361
      return -1;
362
   else if (ca->addr > cb->addr)
363
      return 1;
364
   else
365
      return 0;
366
}
367
#endif
368

369
static void code_disassemble(code_span_t *span, uintptr_t mark,
×
370
                             struct cpu_state *cpu)
371
{
372
   SCOPED_LOCK(span->owner->lock);
×
373

374
   printf("--");
×
375

376
   const int namelen = ident_len(span->name);
×
377
   for (int i = 0; i < 72 - namelen; i++)
×
378
      fputc('-', stdout);
×
379

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

382
#ifdef HAVE_CAPSTONE
383
   cs_insn *insn = cs_malloc(span->owner->capstone);
384

385
#ifdef DEBUG
386
   qsort(span->debug.comments, span->debug.count, sizeof(code_comment_t),
387
         code_comment_compare);
388
   code_comment_t *comment = span->debug.comments;
389
#endif
390

391
   const uint8_t *const eptr = span->base + span->size;
392
   for (const uint8_t *ptr = span->base; ptr < eptr; ) {
393
      uint64_t address = (uint64_t)ptr;
394

395
#ifdef DEBUG
396
      for (; comment < span->debug.comments + span->debug.count
397
              && comment->addr <= address; comment++)
398
         printf("%30s;; %s\n", "", comment->text);
399
#endif
400

401
      int zeros = 0;
402
      for (const uint8_t *zp = ptr; zp < eptr && *zp == 0; zp++, zeros++);
403

404
      if (zeros > 8 || zeros == eptr - ptr) {
405
         printf("%30s;; skipping %d zero bytes\n", "", zeros);
406
         ptr += zeros;
407
         continue;
408
      }
409

410
      size_t size = eptr - ptr;
411
      int col = 0;
412
      if (cs_disasm_iter(span->owner->capstone, &ptr, &size, &address, insn)) {
413
         char hex1[33], *p = hex1;
414
         for (size_t k = 0; k < insn->size; k++)
415
            p += checked_sprintf(p, hex1 + sizeof(hex1) - p, "%02x",
416
                                 insn->bytes[k]);
417

418
         col = printf("%-12" PRIx64 " %-16.16s %s %s", insn->address,
419
                          hex1, insn->mnemonic, insn->op_str);
420

421
#ifdef ARCH_X86_64
422
         if (strcmp(insn->mnemonic, "movabs") == 0) {
423
            const cs_x86_op *src = &(insn->detail->x86.operands[1]);
424
            if (src->type == X86_OP_IMM) {
425
               const char *sym = debug_symbol_name((void *)src->imm);
426
               if (sym != NULL) {
427
                  col = code_print_spaces(col, 60);
428
                  col += printf(" ; %s", sym);
429
               }
430
            }
431
         }
432
#endif
433

434
         if (strlen(hex1) > 16)
435
            col = printf("\n%15s -%-16s", "", hex1 + 16) - 1;
436
      }
437
      else {
438
#ifdef ARCH_ARM64
439
         col = printf("%-12" PRIx64 " %-16.08x %s 0x%08x", (uint64_t)ptr,
440
                      *(uint32_t *)ptr, ".word", *(uint32_t *)ptr);
441
         ptr += 4;
442
#else
443
         col = printf("%-12" PRIx64 " %-16.02x %s 0x%02x", (uint64_t)ptr,
444
                      *ptr, ".byte", *ptr);
445
         ptr++;
446
#endif
447
      }
448

449
      if (mark != 0 && (ptr >= eptr || address > mark)) {
450
         col = code_print_spaces(col, 66);
451
         printf("<=============\n");
452
         if (cpu != NULL) {
453
#ifdef ARCH_X86_64
454
            const char *names[] = {
455
               "RAX", "RCX", "RDX", "RBX", "RSP", "RBP", "RSI", "RDI",
456
               "R8", "R9", "R10", "R11", "R12", "R13", "R14", "R15"
457
            };
458
            for (int i = 0; i < ARRAY_LEN(names); i++)
459
               printf("\t%s\t%"PRIxPTR"\n", names[i], cpu->regs[i]);
460
#else
461
            for (int i = 0; i < 32; i++)
462
               printf("\tR%d\t%"PRIxPTR"\n", i, cpu->regs[i]);
463
#endif
464
         }
465
         mark = 0;
466
      }
467
      else
468
         printf("\n");
469
   }
470

471
   cs_free(insn, 1);
472
#else
473
   jit_hexdump(span->base, span->size, 16, (void *)mark, "");
×
474
#endif
475

476
   for (int i = 0; i < 80; i++)
×
477
      fputc('-', stdout);
×
478
   printf("\n");
×
479
   fflush(stdout);
×
480
}
×
481

482
static void code_write_perf_map(code_span_t *span)
×
483
{
484
   SCOPED_LOCK(span->owner->lock);
×
485

486
   if (span->owner->perfmap == NULL) {
×
487
      char *fname LOCAL = xasprintf("/tmp/perf-%d.map", getpid());
×
488
      if ((span->owner->perfmap = fopen(fname, "w")) == NULL) {
×
489
         warnf("cannot create %s: %s", fname, last_os_error());
×
490
         opt_set_int(OPT_PERF_MAP, 0);
×
491
         return;
×
492
      }
493
      else
494
         debugf("writing perf map to %s", fname);
×
495
   }
496

497
   fprintf(span->owner->perfmap, "%p 0x%zx %s\n", span->base, span->size,
×
498
           istr(span->name));
499
   fflush(span->owner->perfmap);
×
500
}
501

502
code_blob_t *code_blob_new(code_cache_t *code, ident_t name, size_t hint)
8,198✔
503
{
504
   code_span_t **freeptr = &(code->freelist[thread_id()]);
8,198✔
505

506
   code_span_t *free = relaxed_load(freeptr);
8,198✔
507
   if (free == NULL) {
8,198✔
508
      free = code_span_new(code, NULL, code->pages->mem, 0);
1,274✔
509
      relaxed_store(freeptr, free);
1,274✔
510
   }
511

512
   const size_t reqsz = hint ?: MIN_BLOB_SIZE;
8,198✔
513

514
   if (free->size < reqsz) {
8,198✔
515
      SCOPED_LOCK(code->lock);
1,342✔
516

517
#ifdef DEBUG
518
      if (free->size > 0)
1,342✔
519
         debugf("thread %d needs new code cache from global free list "
20✔
520
                "(requested %zu bytes, wasted %zu bytes)",
521
                thread_id(), reqsz, free->size);
522
#endif
523

524
      const size_t chunksz = MAX(reqsz, THREAD_CACHE_SIZE);
1,342✔
525
      const size_t alignedsz = ALIGN_UP(chunksz, CODE_BLOB_ALIGN);
1,342✔
526

527
      if (alignedsz > code->globalfree->size) {
1,342✔
528
         DEBUG_ONLY(debugf("requesting new %d byte code page", CODE_PAGE_SIZE));
6✔
529
         code_page_new(code);
6✔
530
         assert(code->globalfree->size == CODE_PAGE_SIZE);
6✔
531
      }
532

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

535
      free->size = take;
1,342✔
536
      free->base = code->globalfree->base;
1,342✔
537

538
      code->globalfree->base += take;
1,342✔
539
      code->globalfree->size -= take;
1,342✔
540
   }
541

542
   assert(reqsz <= free->size);
8,198✔
543
   assert(((uintptr_t)free->base & (CODE_BLOB_ALIGN - 1)) == 0);
8,198✔
544

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

547
   free->base += span->size;
8,198✔
548
   free->size -= span->size;
8,198✔
549

550
   code_blob_t *blob = xcalloc(sizeof(code_blob_t));
8,198✔
551
   blob->span = span;
8,198✔
552
   blob->wptr = span->base;
8,198✔
553

554
   thread_wx_mode(WX_WRITE);
8,198✔
555

556
   return blob;
8,198✔
557
}
558

559
void code_blob_finalise(code_blob_t *blob, jit_entry_fn_t *entry)
8,198✔
560
{
561
   code_span_t *span = blob->span;
8,198✔
562
   span->size = blob->wptr - span->base;
8,198✔
563

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

567
   ihash_free(blob->labels);
8,198✔
568
   blob->labels = NULL;
8,198✔
569

570
   if (unlikely(blob->patches != NULL))
8,198✔
571
      fatal_trace("not all labels in %s were patched", istr(span->name));
572
   else if (unlikely(blob->overflow)) {
8,198✔
573
      // Return all the memory
574
      freespan->size = freespan->base - span->base;
1✔
575
      freespan->base = span->base;
1✔
576
      free(blob);
1✔
577
      return;
1✔
578
   }
579
   else if (span->size == 0)
8,197✔
580
      fatal_trace("code span %s is empty", istr(span->name));
581

582
   uint8_t *aligned = ALIGN_UP(blob->wptr, CODE_BLOB_ALIGN);
8,197✔
583
   freespan->size = freespan->base - aligned;
8,197✔
584
   freespan->base = aligned;
8,197✔
585

586
   if (opt_get_verbose(OPT_ASM_VERBOSE, istr(span->name))) {
8,197✔
587
      color_printf("\n$bold$$blue$");
×
588
      code_disassemble(span, 0, NULL);
×
589
      color_printf("$$\n");
×
590
   }
591

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

594
   thread_wx_mode(WX_EXECUTE);
8,197✔
595

596
   store_release(entry, (jit_entry_fn_t)span->entry);
8,197✔
597

598
   DEBUG_ONLY(relaxed_add(&span->owner->used, span->size));
8,197✔
599
   free(blob);
8,197✔
600

601
   if (opt_get_int(OPT_PERF_MAP))
8,197✔
602
      code_write_perf_map(span);
×
603
}
604

605
__attribute__((cold, noinline))
606
static void code_blob_overflow(code_blob_t *blob)
1✔
607
{
608
   warnf("JIT code buffer for %s too small", istr(blob->span->name));
1✔
609
   for (patch_list_t *it = blob->patches, *tmp; it; it = tmp) {
1✔
610
      tmp = it->next;
×
611
      free(it);
×
612
   }
613
   blob->patches = NULL;
1✔
614
   blob->overflow = true;
1✔
615
}
1✔
616

617
void code_blob_emit(code_blob_t *blob, const uint8_t *bytes, size_t len)
33,805✔
618
{
619
   if (unlikely(blob->overflow))
33,805✔
620
      return;
621
   else if (unlikely(blob->wptr + len > blob->span->base + blob->span->size)) {
33,805✔
622
      code_blob_overflow(blob);
1✔
623
      return;
1✔
624
   }
625

626
   memcpy(blob->wptr, bytes, len);
33,804✔
627
   blob->wptr += len;
33,804✔
628
}
629

630
void code_blob_align(code_blob_t *blob, unsigned align)
8,488✔
631
{
632
#ifdef ARCH_X86_64
633
   const uint8_t pad[] = { 0x90 };
8,488✔
634
#else
635
   const uint8_t pad[] = { 0x00 };
636
#endif
637

638
   assert(is_power_of_2(align));
8,488✔
639
   assert(align % ARRAY_LEN(pad) == 0);
640

641
   while (((uintptr_t)blob->wptr & (align - 1)) && !blob->overflow)
11,440✔
642
      code_blob_emit(blob, pad, ARRAY_LEN(pad));
2,952✔
643
}
8,488✔
644

645
void code_blob_mark(code_blob_t *blob, jit_label_t label)
71✔
646
{
647
   if (unlikely(blob->overflow))
71✔
648
      return;
649
   else if (blob->labels == NULL)
71✔
650
      blob->labels = ihash_new(256);
66✔
651

652
   ihash_put(blob->labels, label, blob->wptr);
71✔
653

654
   for (patch_list_t **p = &(blob->patches); *p; ) {
88✔
655
      if ((*p)->label == label) {
17✔
656
         patch_list_t *next = (*p)->next;
7✔
657
         (*(*p)->fn)(blob, label, (*p)->wptr, blob->wptr);
7✔
658
         free(*p);
7✔
659
         *p = next;
7✔
660
      }
661
      else
662
         p = &((*p)->next);
10✔
663
   }
664
}
665

666
void code_blob_patch(code_blob_t *blob, jit_label_t label, code_patch_fn_t fn)
8✔
667
{
668
   void *ptr = NULL;
8✔
669
   if (unlikely(blob->overflow))
8✔
670
      return;
671
   else if (blob->labels != NULL && (ptr = ihash_get(blob->labels, label)))
8✔
672
      (*fn)(blob, label, blob->wptr, ptr);
1✔
673
   else {
674
      patch_list_t *new = xmalloc(sizeof(patch_list_t));
7✔
675
      new->next  = blob->patches;
7✔
676
      new->fn    = fn;
7✔
677
      new->label = label;
7✔
678
      new->wptr  = blob->wptr;
7✔
679

680
      blob->patches = new;
7✔
681
   }
682
}
683

684
#ifdef DEBUG
685
static void code_blob_print_value(text_buf_t *tb, jit_value_t value)
392✔
686
{
687
   switch (value.kind) {
392✔
688
   case JIT_VALUE_REG:
162✔
689
      tb_printf(tb, "R%d", value.reg);
162✔
690
      break;
162✔
691
   case JIT_VALUE_INT64:
203✔
692
      if (value.int64 < 4096)
203✔
693
         tb_printf(tb, "#%"PRIi64, value.int64);
199✔
694
      else
695
         tb_printf(tb, "#0x%"PRIx64, value.int64);
4✔
696
      break;
697
   case JIT_VALUE_DOUBLE:
1✔
698
      tb_printf(tb, "%%%g", value.dval);
1✔
699
      break;
1✔
700
   case JIT_ADDR_CPOOL:
×
701
      tb_printf(tb, "[CP+%"PRIi64"]", value.int64);
×
702
      break;
×
703
   case JIT_ADDR_REG:
19✔
704
      tb_printf(tb, "[R%d", value.reg);
19✔
705
      if (value.disp != 0)
19✔
706
         tb_printf(tb, "+%d", value.disp);
1✔
707
      tb_cat(tb, "]");
19✔
708
      break;
19✔
709
   case JIT_ADDR_ABS:
×
710
      tb_printf(tb, "[#%016"PRIx64"]", value.int64);
×
711
      break;
×
712
   case JIT_ADDR_COVER:
×
713
      tb_printf(tb, "@%"PRIi64, value.int64);
×
714
      break;
×
715
   case JIT_VALUE_LABEL:
5✔
716
      tb_printf(tb, "%d", value.label);
5✔
717
      break;
5✔
718
   case JIT_VALUE_HANDLE:
2✔
719
      tb_printf(tb, "<%d>", value.handle);
2✔
720
      break;
2✔
721
   case JIT_VALUE_EXIT:
×
722
      tb_printf(tb, "%s", jit_exit_name(value.exit));
×
723
      break;
×
724
   case JIT_VALUE_LOC:
×
725
      tb_printf(tb, "<%s:%d>", loc_file_str(&value.loc), value.loc.first_line);
×
726
      break;
×
727
   case JIT_VALUE_LOCUS:
×
728
      tb_printf(tb, "%p", value.locus);
×
729
      break;
×
730
   case JIT_VALUE_VPOS:
×
731
      tb_printf(tb, "%u:%u", value.vpos.block, value.vpos.op);
×
732
      break;
×
733
   default:
×
734
      tb_cat(tb, "???");
×
735
   }
736
}
392✔
737

738
static void code_blob_add_comment(code_blob_t *blob, uintptr_t addr, char *text)
70,932✔
739
{
740
   code_debug_t *dbg = &(blob->span->debug);
70,932✔
741

742
   if (dbg->count == dbg->max) {
70,932✔
743
      dbg->max = MAX(128, dbg->max * 2);
8,019✔
744
      dbg->comments = xrealloc_array(dbg->comments, dbg->max,
8,019✔
745
                                     sizeof(code_comment_t));
746
   }
747

748
   dbg->comments[dbg->count].addr = addr;
70,932✔
749
   dbg->comments[dbg->count].text = text;
70,932✔
750
   dbg->count++;
70,932✔
751
}
70,932✔
752

753
void code_blob_print_ir(code_blob_t *blob, jit_ir_t *ir)
348✔
754
{
755
   LOCAL_TEXT_BUF tb = tb_new();
696✔
756
   tb_printf(tb, "%s%s", jit_op_name(ir->op), jit_cc_name(ir->cc));
348✔
757

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

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

763
   if (ir->result != JIT_REG_INVALID)
348✔
764
      tb_printf(tb, "R%d", ir->result);
203✔
765

766
   if (ir->arg1.kind != JIT_VALUE_INVALID) {
348✔
767
      if (ir->result != JIT_REG_INVALID)
263✔
768
         tb_cat(tb, ", ");
187✔
769
      code_blob_print_value(tb, ir->arg1);
263✔
770
   }
771

772
   if (ir->arg2.kind != JIT_VALUE_INVALID) {
348✔
773
      tb_cat(tb, ", ");
129✔
774
      code_blob_print_value(tb, ir->arg2);
129✔
775
   }
776

777
   code_blob_add_comment(blob, (uintptr_t)blob->wptr, tb_claim(tb));
348✔
778
}
348✔
779

780
void code_blob_printf(code_blob_t *blob, const char *fmt, ...)
25,637✔
781
{
782
   va_list ap;
25,637✔
783
   va_start(ap, fmt);
25,637✔
784

785
   char *text = xvasprintf(fmt, ap);
25,637✔
786
   code_blob_add_comment(blob, (uintptr_t)blob->wptr, text);
25,637✔
787

788
   va_end(ap);
25,637✔
789
}
25,637✔
790

791
__attribute__((format(printf, 3, 4)))
792
static void debug_reloc(code_blob_t *blob, void *patch, const char *fmt, ...)
44,947✔
793
{
794
   va_list ap;
44,947✔
795
   va_start(ap, fmt);
44,947✔
796

797
   char *text = xvasprintf(fmt, ap);
44,947✔
798
   code_blob_add_comment(blob, (uintptr_t)patch, text);
44,947✔
799

800
   va_end(ap);
44,947✔
801
}
44,947✔
802
#else
803
#define debug_reloc(...)
804
#endif   // DEBUG
805

806
#ifdef ARCH_ARM64
807
static void arm64_patch_page_offset21(code_blob_t *blob, uint32_t *patch,
808
                                      void *ptr)
809
{
810
   switch ((*patch >> 23) & 0x7f) {
811
   case 0b1111010:   // LDR (immediate, SIMD&FP)
812
   case 0b1110010:   // LDR (immediate)
813
      assert(*patch & (1 << 30));  // Quadword
814
      assert(((uintptr_t)ptr & 7) == 0);
815
      *patch |= (((uintptr_t)ptr & 0xfff) >> 3) << 10;
816
      break;
817
   case 0b0100010:   // ADD (immediate)
818
      *patch |= ((uintptr_t)ptr & 0xfff) << 10;
819
      break;
820
   default:
821
      blob->span->size = blob->wptr - blob->span->base;
822
      code_disassemble(blob->span, (uintptr_t)patch, NULL);
823
      fatal_trace("cannot patch instruction");
824
   }
825
}
826

827
static void arm64_patch_page_base_rel21(uint32_t *patch, void *ptr)
828
{
829
   const intptr_t dst_page = (intptr_t)ptr & ~UINT64_C(0xfff);
830
   const intptr_t src_page = (intptr_t)patch & ~UINT64_C(0xfff);
831
   const intptr_t upper21 = (dst_page - src_page) >> 12;
832
   *(uint32_t *)patch |= (upper21 & 3) << 29;
833
   *(uint32_t *)patch |= ((upper21 >> 2) & 0x7ffff) << 5;
834
}
835
#endif
836

837
static void *code_emit_trampoline(code_blob_t *blob, void *dest)
40,807✔
838
{
839
#if defined ARCH_X86_64
840
   const uint8_t veneer[] = {
40,807✔
841
      0x48, 0xb8, __IMM64((uintptr_t)dest),  // MOVABS RAX, dest
40,807✔
842
      0xff, 0xe0                             // CALL RAX
843
   };
844
#elif defined ARCH_ARM64
845
   const uint8_t veneer[] = {
846
      0x50, 0x00, 0x00, 0x58,   // LDR X16, [PC+8]
847
      0x00, 0x02, 0x1f, 0xd6,   // BR X16
848
      __IMM64((uintptr_t)dest)
849
   };
850
#else
851
   should_not_reach_here();
852
#endif
853

854
   void *prev = memmem(blob->span->base, blob->span->size,
40,807✔
855
                       veneer, ARRAY_LEN(veneer));
856
   if (prev != NULL)
40,807✔
857
      return prev;
858
   else {
859
      DEBUG_ONLY(code_blob_printf(blob, "Trampoline for %p", dest));
17,149✔
860

861
      void *addr = blob->wptr;
17,149✔
862
      code_blob_emit(blob, veneer, ARRAY_LEN(veneer));
17,149✔
863
      return addr;
17,149✔
864
   }
865
}
866

867
#if defined __MINGW32__
868
static void code_load_pe(code_blob_t *blob, const void *data, size_t size)
869
{
870
   const IMAGE_FILE_HEADER *imghdr = data;
871

872
   switch (imghdr->Machine) {
873
   case IMAGE_FILE_MACHINE_AMD64:
874
   case IMAGE_FILE_MACHINE_ARM64:
875
      break;
876
   default:
877
      fatal_trace("unknown target machine %x", imghdr->Machine);
878
   }
879

880
   const IMAGE_SYMBOL *symtab = data + imghdr->PointerToSymbolTable;
881
   const char *strtab = data + imghdr->PointerToSymbolTable
882
      + imghdr->NumberOfSymbols * sizeof(IMAGE_SYMBOL);
883

884
   const IMAGE_SECTION_HEADER *sections =
885
      data + IMAGE_SIZEOF_FILE_HEADER + imghdr->SizeOfOptionalHeader;
886

887
   void **load_addr LOCAL =
888
      xmalloc_array(imghdr->NumberOfSections, sizeof(void *));
889

890
   for (int i = 0; i < imghdr->NumberOfSections; i++) {
891
      if ((sections[i].Characteristics & IMAGE_SCN_CNT_CODE)
892
          || (sections[i].Characteristics & IMAGE_SCN_CNT_INITIALIZED_DATA)) {
893
         const int align = sections[i].Characteristics & IMAGE_SCN_ALIGN_MASK;
894
         code_blob_align(blob, 1 << ((align >> 20) - 1));
895
         load_addr[i] = blob->wptr;
896
         code_blob_emit(blob, data + sections[i].PointerToRawData,
897
                        sections[i].SizeOfRawData);
898
      }
899
      else if ((sections[i].Characteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA)
900
               && sections[i].Misc.VirtualSize > 0)
901
         fatal_trace("non-empty BSS not supported");
902
   }
903

904
   if (blob->overflow)
905
      return;   // Relocations might point outside of code span
906

907
   shash_t *external = load_acquire(&blob->span->owner->symbols);
908

909
   for (int i = 0; i < imghdr->NumberOfSections; i++) {
910
      const IMAGE_RELOCATION *relocs = data + sections[i].PointerToRelocations;
911
      for (int j = 0; j < sections[i].NumberOfRelocations; j++) {
912
         const char *name = NULL;
913
         char tmp[9];
914

915
         assert(relocs[j].SymbolTableIndex < imghdr->NumberOfSymbols);
916
         const IMAGE_SYMBOL *sym = symtab + relocs[j].SymbolTableIndex;
917

918
         if (sym->N.Name.Short) {
919
            memcpy(tmp, sym->N.ShortName, 8);
920
            tmp[8] = '\0';
921
            name = tmp;
922
         }
923
         else
924
            name = strtab + sym->N.Name.Long;
925

926
         void *ptr = NULL;
927
         if (sym->SectionNumber > 0) {
928
            assert(sym->SectionNumber - 1 < imghdr->NumberOfSections);
929
            ptr = load_addr[sym->SectionNumber - 1] + sym->Value;
930
         }
931
         else
932
            ptr = shash_get(external, name);
933

934
         if (ptr == NULL && icmp(blob->span->name, name))
935
            ptr = blob->span->base;
936

937
         if (ptr == NULL)
938
            fatal_trace("failed to resolve symbol %s", name);
939

940
         void *patch = load_addr[i] + relocs[j].VirtualAddress;
941
         assert((uint8_t *)patch >= blob->span->base);
942
         assert((uint8_t *)patch < blob->span->base + blob->span->size);
943

944
         switch (relocs[j].Type) {
945
#if defined ARCH_X86_64
946
         case IMAGE_REL_AMD64_ADDR64:
947
            *(uint64_t *)patch += (uint64_t)ptr;
948
            break;
949
         case IMAGE_REL_AMD64_ADDR32NB:
950
            *(uint32_t *)patch += (uint32_t)(ptr - (void *)blob->span->base);
951
            break;
952
#elif defined ARCH_ARM64
953
         case IMAGE_REL_ARM64_BRANCH26:
954
            {
955
               void *veneer = code_emit_trampoline(blob, ptr);
956
               const ptrdiff_t pcrel = (veneer - patch) >> 2;
957
               *(uint32_t *)patch &= ~0x3ffffff;
958
               *(uint32_t *)patch |= pcrel & 0x3ffffff;
959
            }
960
            break;
961
         case IMAGE_REL_ARM64_ADDR32NB:
962
            *(uint32_t *)patch += (uint32_t)(ptr - (void *)blob->span->base);
963
            break;
964
         case IMAGE_REL_ARM64_PAGEBASE_REL21:
965
            arm64_patch_page_base_rel21(patch, ptr);
966
            break;
967
         case IMAGE_REL_ARM64_PAGEOFFSET_12A:
968
         case IMAGE_REL_ARM64_PAGEOFFSET_12L:
969
            arm64_patch_page_offset21(blob, patch, ptr);
970
            break;
971
#endif
972
         default:
973
            blob->span->size = blob->wptr - blob->span->base;
974
            code_disassemble(blob->span, (uintptr_t)patch, NULL);
975
            fatal_trace("cannot handle relocation type %d for symbol %s",
976
                        relocs[j].Type, name);
977
         }
978
      }
979

980
      if (strncmp((const char *)sections[i].Name, ".pdata",
981
                  IMAGE_SIZEOF_SHORT_NAME) == 0) {
982
         assert(sections[i].SizeOfRawData % sizeof(RUNTIME_FUNCTION) == 0);
983
         const int count = sections[i].SizeOfRawData / sizeof(RUNTIME_FUNCTION);
984
         const DWORD64 base = (DWORD64)blob->span->base;
985

986
         // TODO: we should also call RtlDeleteFunctionTable at some point
987
         if (!RtlAddFunctionTable(load_addr[i], count, base))
988
            fatal_trace("RtlAddFunctionTable failed: %s", last_os_error());
989
      }
990
   }
991

992
   for (int i = 0; i < imghdr->NumberOfSymbols; i++) {
993
      const IMAGE_SYMBOL *sym = &(symtab[i]);
994

995
      if (sym->SectionNumber == 0 || sym->N.Name.Short)
996
         continue;
997
      else if ((sym->Type >> 4) != IMAGE_SYM_DTYPE_FUNCTION)
998
         continue;
999
      else if (icmp(blob->span->name, strtab + sym->N.Name.Long)) {
1000
         blob->span->entry = load_addr[sym->SectionNumber - 1] + sym->Value;
1001
         break;
1002
      }
1003
   }
1004
}
1005
#elif defined __APPLE__
1006
static void code_load_macho(code_blob_t *blob, const void *data, size_t size)
1007
{
1008
   const void *rptr = data;
1009

1010
   const struct mach_header_64 *fhdr = rptr;
1011
   rptr += sizeof(struct mach_header_64);
1012

1013
   if (fhdr->magic != MH_MAGIC_64)
1014
      fatal_trace("bad Mach-O magic %x", fhdr->magic);
1015

1016
   const struct segment_command_64 *seg = NULL;
1017
   const struct symtab_command *symtab = NULL;
1018

1019
   void **load_addr LOCAL = NULL;
1020

1021
   for (int i = 0; i < fhdr->ncmds; i++) {
1022
      const struct load_command *load = rptr;
1023
      switch (load->cmd) {
1024
      case LC_SEGMENT_64:
1025
         {
1026
            seg = rptr;
1027
            load_addr = xmalloc_array(seg->nsects, sizeof(void *));
1028

1029
            for (int j = 0; j < seg->nsects; j++) {
1030
               const struct section_64 *sec =
1031
                  (void *)seg + sizeof(struct segment_command_64)
1032
                  + j * sizeof(struct section_64);
1033
               code_blob_align(blob, 1 << sec->align);
1034
               load_addr[j] = blob->wptr;
1035
               code_blob_emit(blob, data + sec->offset, sec->size);
1036
            }
1037
         }
1038
         break;
1039
      case LC_SYMTAB:
1040
         symtab = rptr;
1041
         assert(symtab->cmdsize == sizeof(struct symtab_command));
1042
         break;
1043
      case LC_DATA_IN_CODE:
1044
      case LC_LINKER_OPTIMIZATION_HINT:
1045
      case LC_BUILD_VERSION:
1046
      case LC_DYSYMTAB:
1047
         break;
1048
      default:
1049
         warnf("unrecognised load command 0x%0x", load->cmd);
1050
      }
1051

1052
      rptr += load->cmdsize;
1053
   }
1054
   assert(rptr == data + sizeof(struct mach_header_64) + fhdr->sizeofcmds);
1055

1056
   if (blob->overflow)
1057
      return;   // Relocations might point outside of code span
1058

1059
   assert(seg != NULL);
1060
   assert(symtab != NULL);
1061

1062
   shash_t *external = load_acquire(&blob->span->owner->symbols);
1063

1064
   for (int i = 0; i < seg->nsects; i++) {
1065
      const struct section_64 *sec =
1066
         (void *)seg + sizeof(struct segment_command_64)
1067
         + i * sizeof(struct section_64);
1068

1069
      uint32_t addend = 0;
1070
      for (int j = 0; j < sec->nreloc; j++) {
1071
         const struct relocation_info *rel =
1072
            data + sec->reloff + j * sizeof(struct relocation_info);
1073
         const char *name = NULL;
1074
         void *ptr = NULL;
1075
         if (rel->r_extern) {
1076
            assert(rel->r_symbolnum < symtab->nsyms);
1077
            const struct nlist_64 *nl = data + symtab->symoff
1078
               + rel->r_symbolnum * sizeof(struct nlist_64);
1079
            name = data + symtab->stroff + nl->n_un.n_strx;
1080

1081
            if (nl->n_type & N_EXT) {
1082
               if (icmp(blob->span->name, name + 1))
1083
                  ptr = blob->span->base;
1084
               else if ((ptr = shash_get(external, name + 1)) == NULL)
1085
                  fatal_trace("failed to resolve symbol %s", name + 1);
1086
            }
1087
            else if (nl->n_sect != NO_SECT)
1088
               ptr = blob->span->base + nl->n_value;
1089
         }
1090
         else
1091
            ptr = blob->span->base;
1092

1093
         ptr += addend;
1094
         addend = 0;
1095

1096
         void *patch = load_addr[i] + rel->r_address;
1097
         assert((uint8_t *)patch >= blob->span->base);
1098
         assert((uint8_t *)patch < blob->span->base + blob->span->size);
1099

1100
         switch (rel->r_type) {
1101
#ifdef ARCH_ARM64
1102
         case ARM64_RELOC_UNSIGNED:
1103
            assert(rel->r_length == 3);
1104
            *(void **)patch = ptr;
1105
            break;
1106
         case ARM64_RELOC_SUBTRACTOR:
1107
            break;   // What is this?
1108
         case ARM64_RELOC_GOT_LOAD_PAGEOFF12:
1109
         case ARM64_RELOC_PAGEOFF12:
1110
            arm64_patch_page_offset21(blob, patch, ptr);
1111
            break;
1112
         case ARM64_RELOC_GOT_LOAD_PAGE21:
1113
         case ARM64_RELOC_PAGE21:
1114
            arm64_patch_page_base_rel21(patch, ptr);
1115
            break;
1116
         case ARM64_RELOC_BRANCH26:
1117
            {
1118
               void *veneer = code_emit_trampoline(blob, ptr);
1119
               const ptrdiff_t pcrel = (veneer - patch) >> 2;
1120
               *(uint32_t *)patch &= ~0x3ffffff;
1121
               *(uint32_t *)patch |= pcrel & 0x3ffffff;
1122
            }
1123
            break;
1124
         case ARM64_RELOC_ADDEND:
1125
            addend = rel->r_symbolnum;
1126
            break;
1127
#elif defined ARCH_X86_64
1128
         case X86_64_RELOC_UNSIGNED:
1129
            *(uint64_t *)patch += (uint64_t)ptr;
1130
            break;
1131
         case X86_64_RELOC_BRANCH:
1132
            *(uint32_t *)patch += (uint32_t)(ptr - patch - 4);
1133
            break;
1134
#endif
1135
         default:
1136
            blob->span->size = blob->wptr - blob->span->base;
1137
            code_disassemble(blob->span, (uintptr_t)patch, NULL);
1138
            fatal_trace("cannot handle relocation type %d for symbol %s",
1139
                        rel->r_type, name);
1140
         }
1141
      }
1142
   }
1143

1144
   for (int i = 0; i < symtab->nsyms; i++) {
1145
      const struct nlist_64 *sym =
1146
         data + symtab->symoff + i * sizeof(struct nlist_64);
1147

1148
      if (sym->n_sect == NO_SECT || (sym->n_type & N_TYPE) != N_SECT)
1149
         continue;
1150

1151
      const char *name = data + symtab->stroff + sym->n_un.n_strx;
1152
      if (name[0] == '_' && icmp(blob->span->name, name + 1)) {
1153
         blob->span->entry = load_addr[sym->n_sect - 1] + sym->n_value;
1154
         break;
1155
      }
1156
   }
1157
}
1158
#elif !defined __MINGW32__
1159
static void code_load_elf(code_blob_t *blob, const void *data, size_t size)
7,943✔
1160
{
1161
   const Elf64_Ehdr *ehdr = data;
7,943✔
1162

1163
   if (ehdr->e_ident[EI_MAG0] != ELFMAG0
7,943✔
1164
       || ehdr->e_ident[EI_MAG1] != ELFMAG1
1165
       || ehdr->e_ident[EI_MAG2] != ELFMAG2
1166
       || ehdr->e_ident[EI_MAG3] != ELFMAG3)
7,943✔
1167
      fatal_trace("bad ELF magic");
1168
   else if (ehdr->e_shentsize != sizeof(Elf64_Shdr))
7,943✔
1169
      fatal_trace("bad section header size %d != %zu", ehdr->e_shentsize,
1170
                  sizeof(Elf64_Shdr));
1171

1172
   const Elf64_Shdr *strtab_hdr =
7,943✔
1173
      data + ehdr->e_shoff + ehdr->e_shstrndx * ehdr->e_shentsize;
7,943✔
1174
   const char *strtab = data + strtab_hdr->sh_offset;
7,943✔
1175

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

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

1181
      switch (shdr->sh_type) {
64,001✔
1182
      case SHT_PROGBITS:
16,431✔
1183
         if (shdr->sh_flags & SHF_ALLOC) {
16,431✔
1184
            code_blob_align(blob, shdr->sh_addralign);
8,488✔
1185
            load_addr[i] = blob->wptr;
8,488✔
1186
            DEBUG_ONLY(code_blob_printf(blob, "%s", strtab + shdr->sh_name));
8,488✔
1187
            code_blob_emit(blob, data + shdr->sh_offset, shdr->sh_size);
8,488✔
1188
         }
1189
         break;
1190

1191
      case SHT_RELA:
1192
         // Handled in second pass
1193
         break;
1194

1195
      case SHT_NULL:
1196
      case SHT_STRTAB:
1197
      case SHT_X86_64_UNWIND:
1198
         break;
1199

1200
      case SHT_SYMTAB:
1201
         for (int i = 0; i < shdr->sh_size / shdr->sh_entsize; i++) {
32,317✔
1202
            const Elf64_Sym *sym =
32,317✔
1203
               data + shdr->sh_offset + i * shdr->sh_entsize;
32,317✔
1204

1205
            if (ELF64_ST_TYPE(sym->st_info) != STT_FUNC)
32,317✔
1206
               continue;
24,374✔
1207
            else if (!icmp(blob->span->name, strtab + sym->st_name))
7,943✔
1208
               continue;
×
1209
            else if (load_addr[sym->st_shndx] == NULL)
7,943✔
1210
               fatal_trace("missing section %d for symbol %s", sym->st_shndx,
1211
                           strtab + sym->st_name);
×
1212
            else {
1213
               blob->span->entry = load_addr[sym->st_shndx] + sym->st_value;
7,943✔
1214
               break;
7,943✔
1215
            }
1216
         }
1217
         break;
1218

1219
      default:
×
1220
         warnf("ignoring ELF section %s with type %x", strtab + shdr->sh_name,
×
1221
               shdr->sh_type);
1222
      }
1223
   }
1224

1225
   if (blob->overflow)
7,943✔
1226
      return;   // Relocations might point outside of code span
×
1227

1228
   shash_t *external = load_acquire(&blob->span->owner->symbols);
7,943✔
1229

1230
   for (int i = 0; i < ehdr->e_shnum; i++) {
71,944✔
1231
      const Elf64_Shdr *shdr = data + ehdr->e_shoff + i * ehdr->e_shentsize;
64,001✔
1232
      if (shdr->sh_type != SHT_RELA)
64,001✔
1233
         continue;
48,203✔
1234

1235
      const Elf64_Shdr *mod =
15,798✔
1236
         data + ehdr->e_shoff + shdr->sh_info * ehdr->e_shentsize;
15,798✔
1237
      if (mod->sh_type != SHT_PROGBITS || !(mod->sh_flags & SHF_ALLOC))
15,798✔
1238
         continue;
7,943✔
1239
      else if (load_addr[shdr->sh_info] == NULL)
7,855✔
1240
         fatal_trace("section %s not loaded", strtab + mod->sh_name);
1241

1242
      const Elf64_Shdr *symtab =
7,855✔
1243
         data + ehdr->e_shoff + shdr->sh_link * ehdr->e_shentsize;
7,855✔
1244
      if (symtab->sh_type != SHT_SYMTAB)
7,855✔
1245
         fatal_trace("section %s is not a symbol table",
1246
                     strtab + symtab->sh_name);
×
1247

1248
      const Elf64_Rela *endp = data + shdr->sh_offset + shdr->sh_size;
7,855✔
1249
      for (const Elf64_Rela *r = data + shdr->sh_offset; r < endp; r++) {
52,802✔
1250
         const Elf64_Sym *sym = data + symtab->sh_offset
44,947✔
1251
            + ELF64_R_SYM(r->r_info) * symtab->sh_entsize;
44,947✔
1252

1253
         char *ptr = NULL;
44,947✔
1254
         switch (ELF64_ST_TYPE(sym->st_info)) {
44,947✔
1255
         case STT_NOTYPE:
40,851✔
1256
         case STT_FUNC:
1257
            if (sym->st_shndx == 0)
40,851✔
1258
               ptr = shash_get(external, strtab + sym->st_name);
40,807✔
1259
            else
1260
               ptr = load_addr[sym->st_shndx] + sym->st_value;
44✔
1261
            break;
1262
         case STT_SECTION:
4,096✔
1263
            ptr = load_addr[sym->st_shndx];
4,096✔
1264
            break;
4,096✔
NEW
1265
         default:
×
1266
            fatal_trace("cannot handle ELF symbol type %d",
1267
                        ELF64_ST_TYPE(sym->st_info));
1268
         }
1269

1270
         if (ptr == NULL)
44,947✔
1271
            fatal_trace("cannot resolve symbol %s type %d",
1272
                        strtab + sym->st_name, ELF64_ST_TYPE(sym->st_info));
×
1273

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

1277
         switch (ELF64_R_TYPE(r->r_info)) {
44,947✔
1278
         case R_X86_64_64:
4,096✔
1279
            debug_reloc(blob, patch, "R_X86_64_64 %s", strtab + sym->st_name);
4,096✔
1280
            *(uint64_t *)patch = (uint64_t)ptr + r->r_addend;
4,096✔
1281
            break;
4,096✔
1282
         case R_X86_64_PC32:
44✔
1283
         case R_X86_64_GOTPCREL:
1284
            {
1285
               const ptrdiff_t pcrel = ptr + r->r_addend - (char *)patch;
44✔
1286
               debug_reloc(blob, patch, "R_X86_64_PC32 %s PC%+"PRIiPTR,
44✔
1287
                           strtab + sym->st_name, pcrel);
44✔
1288
               assert(pcrel >= INT32_MIN && pcrel <= INT32_MAX);
44✔
1289
               *(uint32_t *)patch = pcrel;
44✔
1290
            }
1291
            break;
44✔
1292
         case R_X86_64_PLT32:
40,807✔
1293
            {
1294
               void *veneer = code_emit_trampoline(blob, ptr);
40,807✔
1295
               const ptrdiff_t pcrel = veneer + r->r_addend - patch;
40,807✔
1296
               debug_reloc(blob, patch, "R_X86_64_PLT32 %s PC%+"PRIiPTR,
40,807✔
1297
                           strtab + sym->st_name, pcrel);
40,807✔
1298
               assert(pcrel >= INT32_MIN && pcrel <= INT32_MAX);
40,807✔
1299
               *(uint32_t *)patch = pcrel;
40,807✔
1300
            }
1301
            break;
40,807✔
1302
         case R_AARCH64_CALL26:
×
1303
            {
1304
               void *veneer = code_emit_trampoline(blob, ptr);
×
1305
               const ptrdiff_t pcrel = (veneer + r->r_addend - patch) >> 2;
×
1306
               *(uint32_t *)patch &= ~0x3ffffff;
×
1307
               *(uint32_t *)patch |= pcrel & 0x3ffffff;
×
1308
            }
1309
            break;
×
1310
         case R_AARCH64_PREL64:
×
1311
            *(uint64_t *)patch = ptr + r->r_addend - (char *)patch;
×
1312
            break;
×
1313
         case R_AARCH64_MOVW_UABS_G0_NC:
×
1314
            *(uint32_t *)patch |=
×
1315
               (((uintptr_t)ptr + r->r_addend) & 0xffff) << 5;
×
1316
            break;
×
1317
         case R_AARCH64_MOVW_UABS_G1_NC:
×
1318
            *(uint32_t *)patch |=
×
1319
               ((((uintptr_t)ptr + r->r_addend) >> 16) & 0xffff) << 5;
×
1320
            break;
×
1321
         case R_AARCH64_MOVW_UABS_G2_NC:
×
1322
            *(uint32_t *)patch |=
×
1323
               ((((uintptr_t)ptr + r->r_addend) >> 32) & 0xffff) << 5;
×
1324
            break;
×
1325
         case R_AARCH64_MOVW_UABS_G3:
×
1326
            *(uint32_t *)patch |=
×
1327
               ((((uintptr_t)ptr + r->r_addend) >> 48) & 0xffff) << 5;
×
1328
            break;
×
1329
         default:
×
1330
            blob->span->size = blob->wptr - blob->span->base;
×
1331
            code_disassemble(blob->span, (uintptr_t)patch, NULL);
×
1332
            fatal_trace("cannot handle relocation type %ld for symbol %s",
1333
                        ELF64_R_TYPE(r->r_info), strtab + sym->st_name);
×
1334
         }
1335
      }
1336
   }
1337
}
1338
#endif
1339

1340
void code_load_object(code_blob_t *blob, const void *data, size_t size)
7,943✔
1341
{
1342
#if defined __APPLE__
1343
   code_load_macho(blob, data, size);
1344
#elif defined __MINGW32__
1345
   code_load_pe(blob, data, size);
1346
#else
1347
   code_load_elf(blob, data, size);
7,943✔
1348
#endif
1349
}
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

© 2025 Coveralls, Inc