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

nickg / nvc / 15522061791

08 Jun 2025 08:02PM UTC coverage: 92.187% (-0.06%) from 92.251%
15522061791

push

github

nickg
Constant fold SHL and OR opcodes

17 of 18 new or added lines in 1 file covered. (94.44%)

429 existing lines in 15 files now uncovered.

69452 of 75338 relevant lines covered (92.19%)

566858.25 hits per line

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

67.11
/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 <math.h>
29
#include <stdlib.h>
30
#include <string.h>
31
#include <stdio.h>
32
#include <unistd.h>
33
#include <inttypes.h>
34

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

106
typedef struct _code_page code_page_t;
107

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

209
   return false;
210
}
211
#endif
212

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

218
   assert(code_cache_contains(code, base, size));
15,043✔
219

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

228
   code->spans = span;
15,043✔
229
   return span;
15,043✔
230
}
231

232
static void code_page_new(code_cache_t *code)
4,879✔
233
{
234
   assert_lock_held(&code->lock);
4,879✔
235

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

241
   add_fault_handler(code_fault_handler, page);
4,879✔
242
   debug_add_unwinder(page->mem, CODE_PAGE_SIZE, code_cache_unwinder, code);
4,879✔
243

244
   code->pages = page;
4,879✔
245

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

252
   code->globalfree = code->spans = span;
4,879✔
253
}
4,879✔
254

255
code_cache_t *code_cache_new(void)
4,873✔
256
{
257
   code_cache_t *code = xcalloc(sizeof(code_cache_t));
4,873✔
258

259
   {
260
      SCOPED_LOCK(code->lock);
9,746✔
261
      code_page_new(code);
4,873✔
262
   }
263

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

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

279
   shash_t *s = shash_new(32);
4,873✔
280

281
   extern void __nvc_putpriv(jit_handle_t, void *);
4,873✔
282
   extern void __nvc_sched_waveform(jit_anchor_t *, jit_scalar_t *, tlab_t *);
4,873✔
283
   extern void __nvc_sched_process(jit_anchor_t *, jit_scalar_t *, tlab_t *);
4,873✔
284
   extern void __nvc_test_event(jit_anchor_t *, jit_scalar_t *, tlab_t *);
4,873✔
285
   extern void __nvc_last_event(jit_anchor_t *, jit_scalar_t *, tlab_t *);
4,873✔
286
   extern void __nvc_pack(const uint8_t *, int32_t, jit_scalar_t *);
4,873✔
287
   extern void __nvc_unpack(uint64_t, uint64_t, jit_scalar_t *);
4,873✔
288

289
   shash_put(s, "__nvc_sched_waveform", &__nvc_sched_waveform);
4,873✔
290
   shash_put(s, "__nvc_sched_process", &__nvc_sched_process);
4,873✔
291
   shash_put(s, "__nvc_test_event", &__nvc_test_event);
4,873✔
292
   shash_put(s, "__nvc_last_event", &__nvc_last_event);
4,873✔
293
   shash_put(s, "__nvc_mspace_alloc", &__nvc_mspace_alloc);
4,873✔
294
   shash_put(s, "__nvc_putpriv", &__nvc_putpriv);
4,873✔
295
   shash_put(s, "__nvc_do_exit", &__nvc_do_exit);
4,873✔
296
   shash_put(s, "__nvc_pack", &__nvc_pack);
4,873✔
297
   shash_put(s, "__nvc_unpack", &__nvc_unpack);
4,873✔
298
   shash_put(s, "memmove", &memmove);
4,873✔
299
   shash_put(s, "memcpy", &memcpy);
4,873✔
300
   shash_put(s, "memset", &memset);
4,873✔
301
   shash_put(s, "pow", &pow);
4,873✔
302

303
#if defined __APPLE__ && defined ARCH_ARM64
304
   shash_put(s, "bzero", &bzero);
305
#elif defined __APPLE__ && defined ARCH_X86_64
306
   shash_put(s, "__bzero", &bzero);
307
#elif defined __MINGW32__ && defined ARCH_X86_64
308
   extern void ___chkstk_ms(void);
309
   shash_put(s, "___chkstk_ms", &___chkstk_ms);
310
#endif
311

312
   store_release(&code->symbols, s);
4,873✔
313

314
   return code;
4,873✔
315
}
316

317
void code_cache_free(code_cache_t *code)
4,867✔
318
{
319
   for (code_page_t *it = code->pages, *tmp; it; it = tmp) {
9,740✔
320
      debug_remove_unwinder(it->mem);
4,873✔
321
      remove_fault_handler(code_fault_handler, it);
4,873✔
322

323
      nvc_munmap(it->mem, CODE_PAGE_SIZE);
4,873✔
324

325
      tmp = it->next;
4,873✔
326
      free(it);
4,873✔
327
   }
328

329
   for (code_span_t *it = code->spans, *tmp; it; it = tmp) {
24,778✔
330
      tmp = it->next;
19,911✔
331
      DEBUG_ONLY(free(it->debug.comments));
19,911✔
332
      free(it);
19,911✔
333
   }
334

335
#ifdef HAVE_CAPSTONE
336
   cs_close(&(code->capstone));
337
#endif
338

339
#ifdef DEBUG
340
   if (code->used > 0)
4,867✔
341
      debugf("JIT code footprint: %zu bytes", code->used);
1,356✔
342
#endif
343

344
   shash_free(code->symbols);
4,867✔
345
   free(code);
4,867✔
346
}
4,867✔
347

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

357
#ifdef DEBUG
358
static int code_comment_compare(const void *a, const void *b)
359
{
360
   const code_comment_t *ca = a;
361
   const code_comment_t *cb = b;
362

363
   if (ca->addr < cb->addr)
364
      return -1;
365
   else if (ca->addr > cb->addr)
366
      return 1;
367
   else
368
      return 0;
369
}
370
#endif
371

UNCOV
372
static void code_disassemble(code_span_t *span, uintptr_t mark,
×
373
                             struct cpu_state *cpu)
374
{
375
   SCOPED_LOCK(span->owner->lock);
×
376

377
   printf("--");
×
378

379
   const int namelen = ident_len(span->name);
×
UNCOV
380
   for (int i = 0; i < 72 - namelen; i++)
×
UNCOV
381
      fputc('-', stdout);
×
382

UNCOV
383
   printf(" %s ----\n", istr(span->name));
×
384

385
#ifdef HAVE_CAPSTONE
386
   cs_insn *insn = cs_malloc(span->owner->capstone);
387

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

394
   const uint8_t *const eptr = span->base + span->size;
395
   for (const uint8_t *ptr = span->base; ptr < eptr; ) {
396
      uint64_t address = (uint64_t)ptr;
397

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

404
      int zeros = 0;
405
      for (const uint8_t *zp = ptr; zp < eptr && *zp == 0; zp++, zeros++);
406

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

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

421
         col = printf("%-12" PRIx64 " %-16.16s %s %s", insn->address,
422
                          hex1, insn->mnemonic, insn->op_str);
423

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

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

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

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

479
   for (int i = 0; i < 80; i++)
×
UNCOV
480
      fputc('-', stdout);
×
481
   printf("\n");
×
UNCOV
482
   fflush(stdout);
×
483
}
×
484

485
static void code_write_perf_map(code_span_t *span)
×
486
{
487
   SCOPED_LOCK(span->owner->lock);
×
488

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

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

505
code_blob_t *code_blob_new(code_cache_t *code, ident_t name, size_t hint)
13,650✔
506
{
507
   code_span_t **freeptr = &(code->freelist[thread_id()]);
13,650✔
508

509
   code_span_t *free = relaxed_load(freeptr);
13,650✔
510
   if (free == NULL) {
13,650✔
511
      free = code_span_new(code, NULL, code->pages->mem, 0);
1,393✔
512
      relaxed_store(freeptr, free);
1,393✔
513
   }
514

515
   const size_t reqsz = hint ?: MIN_BLOB_SIZE;
13,650✔
516

517
   if (free->size < reqsz) {
13,650✔
518
      SCOPED_LOCK(code->lock);
1,471✔
519

520
#ifdef DEBUG
521
      if (free->size > 0)
1,471✔
522
         debugf("thread %d needs new code cache from global free list "
32✔
523
                "(requested %zu bytes, wasted %zu bytes)",
524
                thread_id(), reqsz, free->size);
525
#endif
526

527
      const size_t chunksz = MAX(reqsz, THREAD_CACHE_SIZE);
1,471✔
528
      const size_t alignedsz = ALIGN_UP(chunksz, CODE_BLOB_ALIGN);
1,471✔
529

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

536
      const size_t take = MIN(code->globalfree->size, alignedsz);
1,471✔
537

538
      free->size = take;
1,471✔
539
      free->base = code->globalfree->base;
1,471✔
540

541
      code->globalfree->base += take;
1,471✔
542
      code->globalfree->size -= take;
1,471✔
543
   }
544

545
   assert(reqsz <= free->size);
13,650✔
546
   assert(((uintptr_t)free->base & (CODE_BLOB_ALIGN - 1)) == 0);
13,650✔
547

548
   code_span_t *span = code_span_new(code, name, free->base, free->size);
13,650✔
549

550
   free->base += span->size;
13,650✔
551
   free->size -= span->size;
13,650✔
552

553
   code_blob_t *blob = xcalloc(sizeof(code_blob_t));
13,650✔
554
   blob->span = span;
13,650✔
555
   blob->wptr = span->base;
13,650✔
556

557
   thread_wx_mode(WX_WRITE);
13,650✔
558

559
   return blob;
13,650✔
560
}
561

562
void code_blob_finalise(code_blob_t *blob, jit_entry_fn_t *entry)
13,650✔
563
{
564
   code_span_t *span = blob->span;
13,650✔
565
   span->size = blob->wptr - span->base;
13,650✔
566

567
   code_span_t *freespan = relaxed_load(&(span->owner->freelist[thread_id()]));
13,650✔
568
   assert(freespan->size == 0);
13,650✔
569

570
   ihash_free(blob->labels);
13,650✔
571
   blob->labels = NULL;
13,650✔
572

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

585
   uint8_t *aligned = ALIGN_UP(blob->wptr, CODE_BLOB_ALIGN);
13,649✔
586
   freespan->size = freespan->base - aligned;
13,649✔
587
   freespan->base = aligned;
13,649✔
588

589
   if (opt_get_verbose(OPT_ASM_VERBOSE, istr(span->name))) {
13,649✔
UNCOV
590
      color_printf("\n$bold$$blue$");
×
UNCOV
591
      code_disassemble(span, 0, NULL);
×
UNCOV
592
      color_printf("$$\n");
×
593
   }
594

595
   __builtin___clear_cache((char *)span->base, (char *)blob->wptr);
13,649✔
596

597
   thread_wx_mode(WX_EXECUTE);
13,649✔
598

599
   store_release(entry, (jit_entry_fn_t)span->entry);
13,649✔
600

601
   DEBUG_ONLY(relaxed_add(&span->owner->used, span->size));
13,649✔
602
   free(blob);
13,649✔
603

604
   if (opt_get_int(OPT_PERF_MAP))
13,649✔
UNCOV
605
      code_write_perf_map(span);
×
606
}
607

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

620
void code_blob_emit(code_blob_t *blob, const uint8_t *bytes, size_t len)
23,820✔
621
{
622
   if (unlikely(blob->overflow))
23,820✔
623
      return;
624
   else if (unlikely(blob->wptr + len > blob->span->base + blob->span->size)) {
23,820✔
625
      code_blob_overflow(blob);
1✔
626
      return;
1✔
627
   }
628

629
   memcpy(blob->wptr, bytes, len);
23,819✔
630
   blob->wptr += len;
23,819✔
631
}
632

633
void code_blob_align(code_blob_t *blob, unsigned align)
14,136✔
634
{
635
#ifdef ARCH_X86_64
636
   const uint8_t pad[] = { 0x90 };
14,136✔
637
#else
638
   const uint8_t pad[] = { 0x00 };
639
#endif
640

641
   assert(is_power_of_2(align));
14,136✔
642
   assert(align % ARRAY_LEN(pad) == 0);
643

644
   while (((uintptr_t)blob->wptr & (align - 1)) && !blob->overflow)
18,604✔
645
      code_blob_emit(blob, pad, ARRAY_LEN(pad));
4,468✔
646
}
14,136✔
647

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

655
   ihash_put(blob->labels, label, blob->wptr);
71✔
656

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

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

683
      blob->patches = new;
7✔
684
   }
685
}
686

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

741
static void code_blob_add_comment(code_blob_t *blob, uintptr_t addr, char *text)
72,739✔
742
{
743
   code_debug_t *dbg = &(blob->span->debug);
72,739✔
744

745
   if (dbg->count == dbg->max) {
72,739✔
746
      dbg->max = MAX(128, dbg->max * 2);
13,470✔
747
      dbg->comments = xrealloc_array(dbg->comments, dbg->max,
13,470✔
748
                                     sizeof(code_comment_t));
749
   }
750

751
   dbg->comments[dbg->count].addr = addr;
72,739✔
752
   dbg->comments[dbg->count].text = text;
72,739✔
753
   dbg->count++;
72,739✔
754
}
72,739✔
755

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

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

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

766
   if (ir->result != JIT_REG_INVALID)
348✔
767
      tb_printf(tb, "R%d", ir->result);
203✔
768

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

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

780
   code_blob_add_comment(blob, (uintptr_t)blob->wptr, tb_claim(tb));
348✔
781
}
348✔
782

783
void code_blob_printf(code_blob_t *blob, const char *fmt, ...)
14,136✔
784
{
785
   va_list ap;
14,136✔
786
   va_start(ap, fmt);
14,136✔
787

788
   char *text = xvasprintf(fmt, ap);
14,136✔
789
   code_blob_add_comment(blob, (uintptr_t)blob->wptr, text);
14,136✔
790

791
   va_end(ap);
14,136✔
792
}
14,136✔
793

794
__attribute__((format(printf, 3, 4)))
795
static void debug_reloc(code_blob_t *blob, void *patch, const char *fmt, ...)
58,255✔
796
{
797
   va_list ap;
58,255✔
798
   va_start(ap, fmt);
58,255✔
799

800
   char *text = xvasprintf(fmt, ap);
58,255✔
801
   code_blob_add_comment(blob, (uintptr_t)patch, text);
58,255✔
802

803
   va_end(ap);
58,255✔
804
}
58,255✔
805
#else
806
#define debug_reloc(...)
807
#endif   // DEBUG
808

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

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

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

UNCOV
858
   void *prev = memmem(blob->veneers, blob->wptr - blob->veneers,
×
859
                       veneer, ARRAY_LEN(veneer));
UNCOV
860
   if (prev != NULL)
×
861
      return prev;
862
   else {
863
      DEBUG_ONLY(code_blob_printf(blob, "Trampoline for %p", dest));
×
864

UNCOV
865
      void *addr = blob->wptr;
×
UNCOV
866
      code_blob_emit(blob, veneer, ARRAY_LEN(veneer));
×
UNCOV
867
      return addr;
×
868
   }
869
}
870

871
#if defined ARCH_X86_64
872
static void *code_emit_got(code_blob_t *blob, void *dest)
×
873
{
874
   const uint8_t data[] = { __IMM64((uintptr_t)dest) };
×
875

UNCOV
876
   void *prev = memmem(blob->veneers, blob->veneers - blob->wptr,
×
877
                       data, ARRAY_LEN(data));
UNCOV
878
   if (prev != NULL)
×
879
      return prev;
880
   else {
881
      DEBUG_ONLY(code_blob_printf(blob, "GOT entry for %p", dest));
×
882

UNCOV
883
      void *addr = blob->wptr;
×
UNCOV
884
      code_blob_emit(blob, data, ARRAY_LEN(data));
×
UNCOV
885
      return addr;
×
886
   }
887
}
888
#endif
889

890
#if defined __MINGW32__
891
static void code_load_pe(code_blob_t *blob, const void *data, size_t size)
892
{
893
   const IMAGE_FILE_HEADER *imghdr = data;
894

895
   switch (imghdr->Machine) {
896
   case IMAGE_FILE_MACHINE_AMD64:
897
   case IMAGE_FILE_MACHINE_ARM64:
898
      break;
899
   default:
900
      fatal_trace("unknown target machine %x", imghdr->Machine);
901
   }
902

903
   const IMAGE_SYMBOL *symtab = data + imghdr->PointerToSymbolTable;
904
   const char *strtab = data + imghdr->PointerToSymbolTable
905
      + imghdr->NumberOfSymbols * sizeof(IMAGE_SYMBOL);
906

907
   const IMAGE_SECTION_HEADER *sections =
908
      data + IMAGE_SIZEOF_FILE_HEADER + imghdr->SizeOfOptionalHeader;
909

910
   void **load_addr LOCAL =
911
      xmalloc_array(imghdr->NumberOfSections, sizeof(void *));
912

913
   for (int i = 0; i < imghdr->NumberOfSections; i++) {
914
      if ((sections[i].Characteristics & IMAGE_SCN_CNT_CODE)
915
          || (sections[i].Characteristics & IMAGE_SCN_CNT_INITIALIZED_DATA)) {
916
         const int align = sections[i].Characteristics & IMAGE_SCN_ALIGN_MASK;
917
         code_blob_align(blob, 1 << ((align >> 20) - 1));
918
         load_addr[i] = blob->wptr;
919
         code_blob_emit(blob, data + sections[i].PointerToRawData,
920
                        sections[i].SizeOfRawData);
921
      }
922
      else if ((sections[i].Characteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA)
923
               && sections[i].Misc.VirtualSize > 0)
924
         fatal_trace("non-empty BSS not supported");
925
   }
926

927
   if (blob->overflow)
928
      return;   // Relocations might point outside of code span
929

930
   blob->veneers = blob->wptr;
931

932
   shash_t *external = load_acquire(&blob->span->owner->symbols);
933

934
   for (int i = 0; i < imghdr->NumberOfSections; i++) {
935
      const IMAGE_RELOCATION *relocs = data + sections[i].PointerToRelocations;
936
      for (int j = 0; j < sections[i].NumberOfRelocations; j++) {
937
         const char *name = NULL;
938
         char tmp[9];
939

940
         assert(relocs[j].SymbolTableIndex < imghdr->NumberOfSymbols);
941
         const IMAGE_SYMBOL *sym = symtab + relocs[j].SymbolTableIndex;
942

943
         if (sym->N.Name.Short) {
944
            memcpy(tmp, sym->N.ShortName, 8);
945
            tmp[8] = '\0';
946
            name = tmp;
947
         }
948
         else
949
            name = strtab + sym->N.Name.Long;
950

951
         void *ptr = NULL;
952
         if (sym->SectionNumber > 0) {
953
            assert(sym->SectionNumber - 1 < imghdr->NumberOfSections);
954
            ptr = load_addr[sym->SectionNumber - 1] + sym->Value;
955
         }
956
         else
957
            ptr = shash_get(external, name);
958

959
         if (ptr == NULL && icmp(blob->span->name, name))
960
            ptr = blob->span->base;
961

962
         if (ptr == NULL)
963
            fatal_trace("failed to resolve symbol %s", name);
964

965
         void *patch = load_addr[i] + relocs[j].VirtualAddress;
966
         assert((uint8_t *)patch >= blob->span->base);
967
         assert((uint8_t *)patch < blob->span->base + blob->span->size);
968

969
         switch (relocs[j].Type) {
970
#if defined ARCH_X86_64
971
         case IMAGE_REL_AMD64_ADDR64:
972
            *(uint64_t *)patch += (uint64_t)ptr;
973
            break;
974
         case IMAGE_REL_AMD64_ADDR32NB:
975
            *(uint32_t *)patch += (uint32_t)(ptr - (void *)blob->span->base);
976
            break;
977
#elif defined ARCH_ARM64
978
         case IMAGE_REL_ARM64_BRANCH26:
979
            {
980
               void *veneer = code_emit_trampoline(blob, ptr);
981
               const ptrdiff_t pcrel = (veneer - patch) >> 2;
982
               *(uint32_t *)patch &= ~0x3ffffff;
983
               *(uint32_t *)patch |= pcrel & 0x3ffffff;
984
            }
985
            break;
986
         case IMAGE_REL_ARM64_ADDR32NB:
987
            *(uint32_t *)patch += (uint32_t)(ptr - (void *)blob->span->base);
988
            break;
989
         case IMAGE_REL_ARM64_PAGEBASE_REL21:
990
            arm64_patch_page_base_rel21(patch, ptr);
991
            break;
992
         case IMAGE_REL_ARM64_PAGEOFFSET_12A:
993
         case IMAGE_REL_ARM64_PAGEOFFSET_12L:
994
            arm64_patch_page_offset21(blob, patch, ptr);
995
            break;
996
#endif
997
         default:
998
            blob->span->size = blob->wptr - blob->span->base;
999
            code_disassemble(blob->span, (uintptr_t)patch, NULL);
1000
            fatal_trace("cannot handle relocation type %d for symbol %s",
1001
                        relocs[j].Type, name);
1002
         }
1003
      }
1004

1005
      if (strncmp((const char *)sections[i].Name, ".pdata",
1006
                  IMAGE_SIZEOF_SHORT_NAME) == 0) {
1007
         assert(sections[i].SizeOfRawData % sizeof(RUNTIME_FUNCTION) == 0);
1008
         const int count = sections[i].SizeOfRawData / sizeof(RUNTIME_FUNCTION);
1009
         const DWORD64 base = (DWORD64)blob->span->base;
1010

1011
         // TODO: we should also call RtlDeleteFunctionTable at some point
1012
         if (!RtlAddFunctionTable(load_addr[i], count, base))
1013
            fatal_trace("RtlAddFunctionTable failed: %s", last_os_error());
1014
      }
1015
   }
1016

1017
   for (int i = 0; i < imghdr->NumberOfSymbols; i++) {
1018
      const IMAGE_SYMBOL *sym = &(symtab[i]);
1019

1020
      if (sym->SectionNumber == 0 || sym->N.Name.Short)
1021
         continue;
1022
      else if ((sym->Type >> 4) != IMAGE_SYM_DTYPE_FUNCTION)
1023
         continue;
1024
      else if (icmp(blob->span->name, strtab + sym->N.Name.Long)) {
1025
         blob->span->entry = load_addr[sym->SectionNumber - 1] + sym->Value;
1026
         break;
1027
      }
1028
   }
1029
}
1030
#elif defined __APPLE__
1031
static void code_load_macho(code_blob_t *blob, const void *data, size_t size)
1032
{
1033
   const void *rptr = data;
1034

1035
   const struct mach_header_64 *fhdr = rptr;
1036
   rptr += sizeof(struct mach_header_64);
1037

1038
   if (fhdr->magic != MH_MAGIC_64)
1039
      fatal_trace("bad Mach-O magic %x", fhdr->magic);
1040

1041
   const struct segment_command_64 *seg = NULL;
1042
   const struct symtab_command *symtab = NULL;
1043

1044
   void **load_addr LOCAL = NULL;
1045

1046
   for (int i = 0; i < fhdr->ncmds; i++) {
1047
      const struct load_command *load = rptr;
1048
      switch (load->cmd) {
1049
      case LC_SEGMENT_64:
1050
         {
1051
            seg = rptr;
1052
            load_addr = xmalloc_array(seg->nsects, sizeof(void *));
1053

1054
            for (int j = 0; j < seg->nsects; j++) {
1055
               const struct section_64 *sec =
1056
                  (void *)seg + sizeof(struct segment_command_64)
1057
                  + j * sizeof(struct section_64);
1058
               code_blob_align(blob, 1 << sec->align);
1059
               load_addr[j] = blob->wptr;
1060
               DEBUG_ONLY(code_blob_printf(blob, "%s", sec->sectname));
1061
               code_blob_emit(blob, data + sec->offset, sec->size);
1062
            }
1063
         }
1064
         break;
1065
      case LC_SYMTAB:
1066
         symtab = rptr;
1067
         assert(symtab->cmdsize == sizeof(struct symtab_command));
1068
         break;
1069
      case LC_DATA_IN_CODE:
1070
      case LC_LINKER_OPTIMIZATION_HINT:
1071
      case LC_BUILD_VERSION:
1072
      case LC_DYSYMTAB:
1073
         break;
1074
      default:
1075
         warnf("unrecognised load command 0x%0x", load->cmd);
1076
      }
1077

1078
      rptr += load->cmdsize;
1079
   }
1080
   assert(rptr == data + sizeof(struct mach_header_64) + fhdr->sizeofcmds);
1081

1082
   if (blob->overflow)
1083
      return;   // Relocations might point outside of code span
1084

1085
   blob->veneers = blob->wptr;
1086

1087
   assert(seg != NULL);
1088
   assert(symtab != NULL);
1089

1090
   shash_t *external = load_acquire(&blob->span->owner->symbols);
1091

1092
   for (int i = 0; i < seg->nsects; i++) {
1093
      const struct section_64 *sec =
1094
         (void *)seg + sizeof(struct segment_command_64)
1095
         + i * sizeof(struct section_64);
1096

1097
      uint32_t addend = 0;
1098
      for (int j = 0; j < sec->nreloc; j++) {
1099
         const struct relocation_info *rel =
1100
            data + sec->reloff + j * sizeof(struct relocation_info);
1101
         const char *name = NULL;
1102
         void *ptr = NULL;
1103
         if (rel->r_extern) {
1104
            assert(rel->r_symbolnum < symtab->nsyms);
1105
            const struct nlist_64 *nl = data + symtab->symoff
1106
               + rel->r_symbolnum * sizeof(struct nlist_64);
1107
            name = data + symtab->stroff + nl->n_un.n_strx;
1108

1109
            if (nl->n_type & N_EXT) {
1110
               if (icmp(blob->span->name, name + 1))
1111
                  ptr = blob->span->base;
1112
               else if ((ptr = shash_get(external, name + 1)) == NULL)
1113
                  fatal_trace("failed to resolve symbol %s", name + 1);
1114
            }
1115
            else if (nl->n_sect != NO_SECT)
1116
               ptr = blob->span->base + nl->n_value;
1117
         }
1118
         else
1119
            ptr = blob->span->base;
1120

1121
         ptr += addend;
1122
         addend = 0;
1123

1124
         void *patch = load_addr[i] + rel->r_address;
1125
         assert((uint8_t *)patch >= blob->span->base);
1126
         assert((uint8_t *)patch < blob->span->base + blob->span->size);
1127

1128
         switch (rel->r_type) {
1129
#ifdef ARCH_ARM64
1130
         case ARM64_RELOC_UNSIGNED:
1131
            assert(rel->r_length == 3);
1132
            *(void **)patch = ptr;
1133
            break;
1134
         case ARM64_RELOC_SUBTRACTOR:
1135
            break;   // What is this?
1136
         case ARM64_RELOC_GOT_LOAD_PAGEOFF12:
1137
         case ARM64_RELOC_PAGEOFF12:
1138
            arm64_patch_page_offset21(blob, patch, ptr);
1139
            break;
1140
         case ARM64_RELOC_GOT_LOAD_PAGE21:
1141
         case ARM64_RELOC_PAGE21:
1142
            arm64_patch_page_base_rel21(patch, ptr);
1143
            break;
1144
         case ARM64_RELOC_BRANCH26:
1145
            {
1146
               void *veneer = code_emit_trampoline(blob, ptr);
1147
               const ptrdiff_t pcrel = (veneer - patch) >> 2;
1148
               debug_reloc(blob, patch, "ARM64_RELOC_BRANCH26 %s PC%+"PRIiPTR,
1149
                           name, pcrel);
1150
               *(uint32_t *)patch &= ~0x3ffffff;
1151
               *(uint32_t *)patch |= pcrel & 0x3ffffff;
1152
            }
1153
            break;
1154
         case ARM64_RELOC_ADDEND:
1155
            addend = rel->r_symbolnum;
1156
            break;
1157
#elif defined ARCH_X86_64
1158
         case X86_64_RELOC_UNSIGNED:
1159
            *(uint64_t *)patch += (uint64_t)ptr;
1160
            break;
1161
         case X86_64_RELOC_BRANCH:
1162
            *(uint32_t *)patch += (uint32_t)(ptr - patch - 4);
1163
            break;
1164
#endif
1165
         default:
1166
            blob->span->size = blob->wptr - blob->span->base;
1167
            code_disassemble(blob->span, (uintptr_t)patch, NULL);
1168
            fatal_trace("cannot handle relocation type %d for symbol %s",
1169
                        rel->r_type, name);
1170
         }
1171
      }
1172
   }
1173

1174
   for (int i = 0; i < symtab->nsyms; i++) {
1175
      const struct nlist_64 *sym =
1176
         data + symtab->symoff + i * sizeof(struct nlist_64);
1177

1178
      if (sym->n_sect == NO_SECT || (sym->n_type & N_TYPE) != N_SECT)
1179
         continue;
1180

1181
      const char *name = data + symtab->stroff + sym->n_un.n_strx;
1182
      if (name[0] == '_' && icmp(blob->span->name, name + 1)) {
1183
         blob->span->entry = load_addr[sym->n_sect - 1] + sym->n_value;
1184
         break;
1185
      }
1186
   }
1187
}
1188
#elif !defined __MINGW32__
1189
static void code_load_elf(code_blob_t *blob, const void *data, size_t size)
13,395✔
1190
{
1191
   const Elf64_Ehdr *ehdr = data;
13,395✔
1192

1193
   if (ehdr->e_ident[EI_MAG0] != ELFMAG0
13,395✔
1194
       || ehdr->e_ident[EI_MAG1] != ELFMAG1
1195
       || ehdr->e_ident[EI_MAG2] != ELFMAG2
1196
       || ehdr->e_ident[EI_MAG3] != ELFMAG3)
13,395✔
1197
      fatal_trace("bad ELF magic");
1198
   else if (ehdr->e_shentsize != sizeof(Elf64_Shdr))
13,395✔
1199
      fatal_trace("bad section header size %d != %zu", ehdr->e_shentsize,
1200
                  sizeof(Elf64_Shdr));
1201

1202
   const Elf64_Shdr *strtab_hdr =
13,395✔
1203
      data + ehdr->e_shoff + ehdr->e_shstrndx * ehdr->e_shentsize;
13,395✔
1204
   const char *strtab = data + strtab_hdr->sh_offset;
13,395✔
1205

1206
   void **load_addr LOCAL = xcalloc_array(ehdr->e_shnum, sizeof(void *));
26,790✔
1207

1208
   for (int i = 0; i < ehdr->e_shnum; i++) {
120,423✔
1209
      const Elf64_Shdr *shdr = data + ehdr->e_shoff + i * ehdr->e_shentsize;
107,028✔
1210

1211
      switch (shdr->sh_type) {
107,028✔
1212
      case SHT_PROGBITS:
27,531✔
1213
         if (shdr->sh_flags & SHF_ALLOC) {
27,531✔
1214
            code_blob_align(blob, shdr->sh_addralign);
14,136✔
1215
            load_addr[i] = blob->wptr;
14,136✔
1216
            DEBUG_ONLY(code_blob_printf(blob, "%s", strtab + shdr->sh_name));
14,136✔
1217
            code_blob_emit(blob, data + shdr->sh_offset, shdr->sh_size);
14,136✔
1218
         }
1219
         break;
1220

1221
      case SHT_RELA:
1222
         // Handled in second pass
1223
         break;
1224

1225
      case SHT_NULL:
1226
      case SHT_STRTAB:
1227
      case SHT_X86_64_UNWIND:
1228
         break;
1229

1230
      case SHT_SYMTAB:
1231
         for (int i = 0; i < shdr->sh_size / shdr->sh_entsize; i++) {
54,321✔
1232
            const Elf64_Sym *sym =
54,321✔
1233
               data + shdr->sh_offset + i * shdr->sh_entsize;
54,321✔
1234

1235
            if (ELF64_ST_TYPE(sym->st_info) != STT_FUNC)
54,321✔
1236
               continue;
40,926✔
1237
            else if (!icmp(blob->span->name, strtab + sym->st_name))
13,395✔
UNCOV
1238
               continue;
×
1239
            else if (load_addr[sym->st_shndx] == NULL)
13,395✔
1240
               fatal_trace("missing section %d for symbol %s", sym->st_shndx,
UNCOV
1241
                           strtab + sym->st_name);
×
1242
            else {
1243
               blob->span->entry = load_addr[sym->st_shndx] + sym->st_value;
13,395✔
1244
               break;
13,395✔
1245
            }
1246
         }
1247
         break;
1248

UNCOV
1249
      default:
×
UNCOV
1250
         warnf("ignoring ELF section %s with type %x", strtab + shdr->sh_name,
×
1251
               shdr->sh_type);
1252
      }
1253
   }
1254

1255
   if (blob->overflow)
13,395✔
UNCOV
1256
      return;   // Relocations might point outside of code span
×
1257

1258
   blob->veneers = blob->wptr;
13,395✔
1259

1260
   shash_t *external = load_acquire(&blob->span->owner->symbols);
13,395✔
1261

1262
   for (int i = 0; i < ehdr->e_shnum; i++) {
120,423✔
1263
      const Elf64_Shdr *shdr = data + ehdr->e_shoff + i * ehdr->e_shentsize;
107,028✔
1264
      if (shdr->sh_type != SHT_RELA)
107,028✔
1265
         continue;
81,111✔
1266

1267
      const Elf64_Shdr *mod =
25,917✔
1268
         data + ehdr->e_shoff + shdr->sh_info * ehdr->e_shentsize;
25,917✔
1269
      if (mod->sh_type != SHT_PROGBITS || !(mod->sh_flags & SHF_ALLOC))
25,917✔
1270
         continue;
13,395✔
1271
      else if (load_addr[shdr->sh_info] == NULL)
12,522✔
1272
         fatal_trace("section %s not loaded", strtab + mod->sh_name);
1273

1274
      const Elf64_Shdr *symtab =
12,522✔
1275
         data + ehdr->e_shoff + shdr->sh_link * ehdr->e_shentsize;
12,522✔
1276
      if (symtab->sh_type != SHT_SYMTAB)
12,522✔
1277
         fatal_trace("section %s is not a symbol table",
UNCOV
1278
                     strtab + symtab->sh_name);
×
1279

1280
      const Elf64_Rela *endp = data + shdr->sh_offset + shdr->sh_size;
12,522✔
1281
      for (const Elf64_Rela *r = data + shdr->sh_offset; r < endp; r++) {
70,777✔
1282
         const Elf64_Sym *sym = data + symtab->sh_offset
58,255✔
1283
            + ELF64_R_SYM(r->r_info) * symtab->sh_entsize;
58,255✔
1284

1285
         void *ptr = NULL;
58,255✔
1286
         switch (ELF64_ST_TYPE(sym->st_info)) {
58,255✔
1287
         case STT_NOTYPE:
41,982✔
1288
         case STT_FUNC:
1289
            if (sym->st_shndx == 0)
41,982✔
1290
               ptr = shash_get(external, strtab + sym->st_name);
41,673✔
1291
            else
1292
               ptr = load_addr[sym->st_shndx] + sym->st_value;
309✔
1293
            break;
1294
         case STT_SECTION:
16,273✔
1295
            ptr = load_addr[sym->st_shndx];
16,273✔
1296
            break;
16,273✔
UNCOV
1297
         default:
×
1298
            fatal_trace("cannot handle ELF symbol type %d",
1299
                        ELF64_ST_TYPE(sym->st_info));
1300
         }
1301

1302
         if (ptr == NULL)
58,255✔
1303
            fatal_trace("cannot resolve symbol %s type %d",
UNCOV
1304
                        strtab + sym->st_name, ELF64_ST_TYPE(sym->st_info));
×
1305

1306
         void *patch = load_addr[shdr->sh_info] + r->r_offset;
58,255✔
1307
         assert(r->r_offset < mod->sh_size);
58,255✔
1308

1309
         switch (ELF64_R_TYPE(r->r_info)) {
58,255✔
1310
         case R_X86_64_64:
58,255✔
1311
            debug_reloc(blob, patch, "R_X86_64_64 %s", strtab + sym->st_name);
58,255✔
1312
            *(uint64_t *)patch = (uint64_t)ptr + r->r_addend;
58,255✔
1313
            break;
58,255✔
1314
         case R_X86_64_PC32:
×
1315
            {
1316
               const ptrdiff_t pcrel = ptr + r->r_addend - patch;
×
UNCOV
1317
               debug_reloc(blob, patch, "R_X86_64_PC32 %s PC%+"PRIiPTR,
×
1318
                           strtab + sym->st_name, pcrel);
×
1319
               assert(pcrel >= INT32_MIN && pcrel <= INT32_MAX);
×
UNCOV
1320
               *(uint32_t *)patch = pcrel;
×
1321
            }
1322
            break;
×
1323
         case R_X86_64_GOTPCREL:
×
1324
            {
1325
               void *got = code_emit_got(blob, ptr);
×
1326
               const ptrdiff_t pcrel = got + r->r_addend - patch;
×
UNCOV
1327
               debug_reloc(blob, patch, "R_X86_64_GOTPCREL %s PC%+"PRIiPTR,
×
1328
                           strtab + sym->st_name, pcrel);
×
1329
               assert(pcrel >= INT32_MIN && pcrel <= INT32_MAX);
×
UNCOV
1330
               *(uint32_t *)patch = pcrel;
×
1331
            }
1332
            break;
×
1333
         case R_X86_64_PLT32:
×
1334
            {
1335
               void *veneer = code_emit_trampoline(blob, ptr);
×
1336
               const ptrdiff_t pcrel = veneer + r->r_addend - patch;
×
UNCOV
1337
               debug_reloc(blob, patch, "R_X86_64_PLT32 %s PC%+"PRIiPTR,
×
1338
                           strtab + sym->st_name, pcrel);
×
1339
               assert(pcrel >= INT32_MIN && pcrel <= INT32_MAX);
×
UNCOV
1340
               *(uint32_t *)patch = pcrel;
×
1341
            }
1342
            break;
×
1343
         case R_AARCH64_CALL26:
×
1344
            {
UNCOV
1345
               void *veneer = code_emit_trampoline(blob, ptr);
×
1346
               const ptrdiff_t pcrel = (veneer + r->r_addend - patch) >> 2;
×
1347
               *(uint32_t *)patch &= ~0x3ffffff;
×
1348
               *(uint32_t *)patch |= pcrel & 0x3ffffff;
×
1349
            }
1350
            break;
×
1351
         case R_AARCH64_PREL64:
×
1352
            *(uint64_t *)patch = ptr + r->r_addend - patch;
×
1353
            break;
×
1354
         case R_AARCH64_MOVW_UABS_G0_NC:
×
1355
            *(uint32_t *)patch |=
×
1356
               (((uintptr_t)ptr + r->r_addend) & 0xffff) << 5;
×
1357
            break;
×
1358
         case R_AARCH64_MOVW_UABS_G1_NC:
×
1359
            *(uint32_t *)patch |=
×
1360
               ((((uintptr_t)ptr + r->r_addend) >> 16) & 0xffff) << 5;
×
1361
            break;
×
1362
         case R_AARCH64_MOVW_UABS_G2_NC:
×
1363
            *(uint32_t *)patch |=
×
1364
               ((((uintptr_t)ptr + r->r_addend) >> 32) & 0xffff) << 5;
×
1365
            break;
×
1366
         case R_AARCH64_MOVW_UABS_G3:
×
1367
            *(uint32_t *)patch |=
×
1368
               ((((uintptr_t)ptr + r->r_addend) >> 48) & 0xffff) << 5;
×
UNCOV
1369
            break;
×
1370
         default:
×
UNCOV
1371
            blob->span->size = blob->wptr - blob->span->base;
×
UNCOV
1372
            code_disassemble(blob->span, (uintptr_t)patch, NULL);
×
1373
            fatal_trace("cannot handle relocation type %ld for symbol %s",
UNCOV
1374
                        ELF64_R_TYPE(r->r_info), strtab + sym->st_name);
×
1375
         }
1376
      }
1377
   }
1378
}
1379
#endif
1380

1381
void code_load_object(code_blob_t *blob, const void *data, size_t size)
13,395✔
1382
{
1383
#if defined __APPLE__
1384
   code_load_macho(blob, data, size);
1385
#elif defined __MINGW32__
1386
   code_load_pe(blob, data, size);
1387
#else
1388
   code_load_elf(blob, data, size);
13,395✔
1389
#endif
1390
}
13,395✔
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