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

nickg / nvc / 4702079372

pending completion
4702079372

push

github

Nick Gasson
Handle linking against ___chkstk_ms on MinGW as a special case. Issue #671

40757 of 45079 relevant lines covered (90.41%)

969590.09 hits per line

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

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

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

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

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

45
#ifdef HAVE_CAPSTONE
46
#include <capstone.h>
47
#endif
48

49
#ifndef R_AARCH64_MOVW_UABS_G0_NC
50
#define R_AARCH64_MOVW_UABS_G0_NC 264
51
#endif
52

53
#ifndef R_AARCH64_MOVW_UABS_G1_NC
54
#define R_AARCH64_MOVW_UABS_G1_NC 266
55
#endif
56

57
#ifndef R_AARCH64_MOVW_UABS_G2_NC
58
#define R_AARCH64_MOVW_UABS_G2_NC 268
59
#endif
60

61
#ifndef R_AARCH64_MOVW_UABS_G3
62
#define R_AARCH64_MOVW_UABS_G3 269
63
#endif
64

65
#ifndef SHT_X86_64_UNWIND
66
#define SHT_X86_64_UNWIND 0x70000001
67
#endif
68

69
#define CODECACHE_ALIGN   4096
70
#define CODECACHE_SIZE    0x400000
71
#define THREAD_CACHE_SIZE 0x10000
72
#define CODE_BLOB_ALIGN   256
73
#define MIN_BLOB_SIZE     0x4000
74

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

79
STATIC_ASSERT(MIN_BLOB_SIZE <= THREAD_CACHE_SIZE);
80
STATIC_ASSERT(MIN_BLOB_SIZE % CODE_BLOB_ALIGN == 0);
81
STATIC_ASSERT(CODECACHE_SIZE % THREAD_CACHE_SIZE == 0);
82

83
typedef struct _code_span {
84
   code_cache_t *owner;
85
   code_span_t  *next;
86
   ident_t       name;
87
   uint8_t      *base;
88
   size_t        size;
89
} code_span_t;
90

91
typedef struct _patch_list {
92
   patch_list_t    *next;
93
   uint8_t         *wptr;
94
   jit_label_t      label;
95
   code_patch_fn_t  fn;
96
} patch_list_t;
97

98
typedef struct _code_cache {
99
   nvc_lock_t   lock;
100
   uint8_t     *mem;
101
   code_span_t *spans;
102
   code_span_t *freelist[MAX_THREADS];
103
   code_span_t *globalfree;
104
   FILE        *perfmap;
105
#ifdef HAVE_CAPSTONE
106
   csh          capstone;
107
#endif
108
#ifdef DEBUG
109
   size_t       used;
110
#endif
111
} code_cache_t;
112

113
static void code_disassemble(code_span_t *span, uintptr_t mark,
114
                             struct cpu_state *cpu);
115

116
static void code_cache_unwinder(uintptr_t addr, debug_frame_t *frame,
×
117
                                void *context)
118
{
119
   code_cache_t *code = context;
×
120

121
   const uint8_t *pc = (uint8_t *)addr;
×
122
   for (code_span_t *span = code->spans; span; span = span->next) {
×
123
      if (pc >= span->base && pc < span->base + span->size) {
×
124
         frame->kind = FRAME_VHDL;
×
125
         frame->disp = pc - span->base;
×
126
         frame->symbol = istr(span->name);
×
127
      }
128
   }
129
}
×
130

131
static void code_fault_handler(int sig, void *addr, struct cpu_state *cpu,
×
132
                               void *context)
133
{
134
   code_cache_t *code = context;
×
135

136
   const uint8_t *pc = (uint8_t *)cpu->pc;
×
137
   if (pc < code->mem || pc > code->mem + CODECACHE_SIZE)
×
138
      return;
139

140
   uintptr_t mark = cpu->pc;
×
141
#ifndef __MINGW32__
142
   if (sig == SIGTRAP)
×
143
      mark--;   // Point to faulting instruction
144
#endif
145

146
   for (code_span_t *span = code->spans; span; span = span->next) {
×
147
      if (pc >= span->base && pc < span->base + span->size && span->name)
×
148
         code_disassemble(span, mark, cpu);
149
   }
150
}
151

152
static code_span_t *code_span_new(code_cache_t *code, ident_t name,
220✔
153
                                  uint8_t *base, size_t size)
154
{
155
   assert(base >= code->mem);
220✔
156
   assert(base + size <= code->mem + CODECACHE_SIZE);
220✔
157

158
   SCOPED_LOCK(code->lock);
220✔
159

160
   code_span_t *span = xcalloc(sizeof(code_span_t));
220✔
161
   span->name  = name;
220✔
162
   span->next  = code->spans;
220✔
163
   span->base  = base;
220✔
164
   span->size  = size;
220✔
165
   span->owner = code;
220✔
166

167
   code->spans = span;
220✔
168
   return span;
220✔
169
}
170

171
code_cache_t *code_cache_new(void)
19✔
172
{
173
   code_cache_t *code = xcalloc(sizeof(code_cache_t));
19✔
174
   code->mem = map_jit_pages(CODECACHE_ALIGN, CODECACHE_SIZE);
19✔
175

176
#ifdef HAVE_CAPSTONE
177
#if defined ARCH_X86_64
178
   if (cs_open(CS_ARCH_X86, CS_MODE_64, &(code->capstone)) != CS_ERR_OK)
179
      fatal_trace("failed to init capstone for x86_64");
180
#elif defined ARCH_ARM64
181
   if (cs_open(CS_ARCH_ARM64, CS_MODE_ARM, &(code->capstone)) != CS_ERR_OK)
182
      fatal_trace("failed to init capstone for Arm64");
183
#else
184
#error Cannot configure capstone for this architecture
185
#endif
186

187
   if (cs_option(code->capstone, CS_OPT_DETAIL, 1) != CS_ERR_OK)
188
      fatal_trace("failed to set capstone detailed mode");
189
#endif
190

191
   add_fault_handler(code_fault_handler, code);
19✔
192
   debug_add_unwinder(code->mem, CODECACHE_SIZE, code_cache_unwinder, code);
19✔
193

194
   code->globalfree = code_span_new(code, NULL, code->mem, CODECACHE_SIZE);
19✔
195

196
   return code;
19✔
197
}
198

199
void code_cache_free(code_cache_t *code)
19✔
200
{
201
   debug_remove_unwinder(code->mem);
19✔
202
   remove_fault_handler(code_fault_handler, code);
19✔
203

204
   nvc_munmap(code->mem, CODECACHE_SIZE);
19✔
205

206
   for (code_span_t *it = code->spans, *tmp; it; it = tmp) {
239✔
207
      tmp = it->next;
220✔
208
      free(it);
220✔
209
   }
210

211
#ifdef HAVE_CAPSTONE
212
   cs_close(&(code->capstone));
213
#endif
214

215
#ifdef DEBUG
216
   if (!opt_get_int(OPT_UNIT_TEST))
19✔
217
      debugf("JIT code footprint: %zu bytes", code->used);
×
218
#endif
219

220
   free(code);
19✔
221
}
19✔
222

223
#ifdef HAVE_CAPSTONE
224
static int code_print_spaces(int col, int tab)
225
{
226
   for (; col < tab; col++)
227
      fputc(' ', stdout);
228
   return col;
229
}
230
#endif
231

232
static void code_disassemble(code_span_t *span, uintptr_t mark,
233
                             struct cpu_state *cpu)
234
{
235
#ifdef HAVE_CAPSTONE
236
   SCOPED_LOCK(span->owner->lock);
237

238
   printf("--");
239

240
   const int namelen = ident_len(span->name);
241
   for (int i = 0; i < 72 - namelen; i++)
242
      fputc('-', stdout);
243

244
   printf(" %s ----\n", istr(span->name));
245

246
   cs_insn *insn = cs_malloc(span->owner->capstone);
247

248
   const uint8_t *const eptr = span->base + span->size;
249
   for (const uint8_t *ptr = span->base; ptr < eptr; ) {
250
      size_t size = eptr - ptr;
251
      uint64_t address = (uint64_t)ptr;
252
      int col = 0;
253
      if (cs_disasm_iter(span->owner->capstone, &ptr, &size, &address, insn)) {
254
         char hex1[33], *p = hex1;
255
         for (size_t k = 0; k < insn->size; k++)
256
            p += checked_sprintf(p, hex1 + sizeof(hex1) - p, "%02x",
257
                                 insn->bytes[k]);
258

259
         col = printf("%-12" PRIx64 " %-16.16s %s %s", insn->address,
260
                          hex1, insn->mnemonic, insn->op_str);
261

262
#ifdef ARCH_X86_64
263
         if (strcmp(insn->mnemonic, "movabs") == 0) {
264
            const cs_x86_op *src = &(insn->detail->x86.operands[1]);
265
            if (src->type == X86_OP_IMM) {
266
               const char *sym = debug_symbol_name((void *)src->imm);
267
               if (sym != NULL) {
268
                  col = code_print_spaces(col, 60);
269
                  col += printf(" ; %s", sym);
270
               }
271
            }
272
         }
273
#endif
274

275
         if (strlen(hex1) > 16)
276
            col = printf("\n%15s -%-16s", "", hex1 + 16) - 1;
277
      }
278
      else {
279
#ifdef ARCH_ARM64
280
         col = printf("%-12" PRIx64 " %-16.08x %s 0x%08x", (uint64_t)ptr,
281
                      *(uint32_t *)ptr, ".word", *(uint32_t *)ptr);
282
         ptr += 4;
283
#else
284
         col = printf("%-12" PRIx64 " %-16.02x %s 0x%02x", (uint64_t)ptr,
285
                      *ptr, ".byte", *ptr);
286
         ptr++;
287
#endif
288
      }
289

290
      if (mark != 0 && (ptr >= eptr || address > mark)) {
291
         col = code_print_spaces(col, 66);
292
         printf("<=============\n");
293
         if (cpu != NULL) {
294
#ifdef ARCH_X86_64
295
            const char *names[] = {
296
               "RAX", "RCX", "RDX", "RBX", "RSP", "RBP", "RSI", "RDI",
297
               "R8", "R9", "R10", "R11", "R12", "R13", "R14", "R15"
298
            };
299
            for (int i = 0; i < ARRAY_LEN(names); i++)
300
               printf("\t%s\t%"PRIx64"\n", names[i], cpu->regs[i]);
301
#else
302
            for (int i = 0; i < 32; i++)
303
               printf("\tR%d\t%"PRIxPTR"\n", i, cpu->regs[i]);
304
#endif
305
         }
306
         mark = 0;
307
      }
308
      else
309
         printf("\n");
310
   }
311

312
   cs_free(insn, 1);
313

314
   for (int i = 0; i < 80; i++)
315
      fputc('-', stdout);
316
   printf("\n");
317
   fflush(stdout);
318
#endif
319
}
320

321
static void code_write_perf_map(code_span_t *span)
×
322
{
323
   SCOPED_LOCK(span->owner->lock);
×
324

325
   if (span->owner->perfmap == NULL) {
×
326
      char *fname LOCAL = xasprintf("/tmp/perf-%d.map", getpid());
×
327
      if ((span->owner->perfmap = fopen(fname, "w")) == NULL) {
×
328
         warnf("cannot create %s: %s", fname, last_os_error());
×
329
         opt_set_int(OPT_PERF_MAP, 0);
×
330
         return;
×
331
      }
332
      else
333
         debugf("writing perf map to %s", fname);
×
334
   }
335

336
   fprintf(span->owner->perfmap, "%p 0x%zx %s\n", span->base, span->size,
×
337
           istr(span->name));
338
   fflush(span->owner->perfmap);
×
339
}
340

341
code_blob_t *code_blob_new(code_cache_t *code, ident_t name, size_t hint)
182✔
342
{
343
   code_span_t **freeptr = &(code->freelist[thread_id()]);
182✔
344

345
   code_span_t *free = relaxed_load(freeptr);
182✔
346
   if (free == NULL) {
182✔
347
      free = code_span_new(code, NULL, code->mem, 0);
19✔
348
      relaxed_store(freeptr, free);
19✔
349
   }
350

351
   const size_t reqsz = hint ?: MIN_BLOB_SIZE;
182✔
352

353
   if (free->size < reqsz) {
182✔
354
      SCOPED_LOCK(code->lock);
38✔
355

356
      if (code->globalfree->size == 0)
19✔
357
         return NULL;
×
358

359
#ifdef DEBUG
360
      if (free->size > 0)
19✔
361
         debugf("thread %d needs new code cache from global free list "
×
362
                "(requested %zu bytes, wasted %zu bytes)",
363
                thread_id(), reqsz, free->size);
364
#endif
365

366
      const size_t chunksz = MAX(reqsz, THREAD_CACHE_SIZE);
19✔
367
      const size_t alignedsz = ALIGN_UP(chunksz, CODE_BLOB_ALIGN);
19✔
368
      const size_t take = MIN(code->globalfree->size, alignedsz);
19✔
369

370
      free->size = take;
19✔
371
      free->base = code->globalfree->base;
19✔
372

373
      code->globalfree->base += take;
19✔
374
      code->globalfree->size -= take;
19✔
375

376
      if (code->globalfree->size == 0)
19✔
377
         warnf("global JIT code buffer exhausted");
×
378
   }
379

380
   assert(reqsz <= free->size);
182✔
381
   assert(((uintptr_t)free->base & (CODE_BLOB_ALIGN - 1)) == 0);
182✔
382

383
   code_span_t *span = code_span_new(code, name, free->base, free->size);
182✔
384

385
   free->base += span->size;
182✔
386
   free->size -= span->size;
182✔
387

388
   code_blob_t *blob = xcalloc(sizeof(code_blob_t));
182✔
389
   blob->span = span;
182✔
390
   blob->wptr = span->base;
182✔
391

392
   thread_wx_mode(WX_WRITE);
182✔
393

394
   return blob;
182✔
395
}
396

397
void code_blob_finalise(code_blob_t *blob, jit_entry_fn_t *entry)
182✔
398
{
399
   code_span_t *span = blob->span;
182✔
400
   span->size = blob->wptr - span->base;
182✔
401

402
   code_span_t *freespan = relaxed_load(&(span->owner->freelist[thread_id()]));
182✔
403
   assert(freespan->size == 0);
182✔
404

405
   ihash_free(blob->labels);
182✔
406
   blob->labels = NULL;
182✔
407

408
   if (unlikely(blob->patches != NULL))
182✔
409
      fatal_trace("not all labels in %s were patched", istr(span->name));
×
410
   else if (unlikely(blob->overflow)) {
182✔
411
      // Return all the memory
412
      freespan->size = freespan->base - span->base;
×
413
      freespan->base = span->base;
×
414
      free(blob);
×
415
      return;
×
416
   }
417
   else if (span->size == 0)
182✔
418
      fatal_trace("code span %s is empty", istr(span->name));
×
419

420
   uint8_t *aligned = ALIGN_UP(blob->wptr, CODE_BLOB_ALIGN);
182✔
421
   freespan->size = freespan->base - aligned;
182✔
422
   freespan->base = aligned;
182✔
423

424
   if (opt_get_verbose(OPT_ASM_VERBOSE, istr(span->name))) {
182✔
425
      color_printf("\n$bold$$blue$");
×
426
      code_disassemble(span, 0, NULL);
×
427
      color_printf("$$\n");
×
428
   }
429

430
   __builtin___clear_cache((char *)span->base, (char *)blob->wptr);
182✔
431

432
   thread_wx_mode(WX_EXECUTE);
182✔
433

434
   store_release(entry, (jit_entry_fn_t)span->base);
182✔
435

436
   DEBUG_ONLY(relaxed_add(&span->owner->used, span->size));
182✔
437
   free(blob);
182✔
438

439
   if (opt_get_int(OPT_PERF_MAP))
182✔
440
      code_write_perf_map(span);
×
441
}
442

443
void code_blob_emit(code_blob_t *blob, const uint8_t *bytes, size_t len)
8,118✔
444
{
445
   if (unlikely(blob->overflow))
8,118✔
446
      return;
447
   else if (unlikely(blob->wptr + len >= blob->span->base + blob->span->size)) {
8,118✔
448
      warnf("JIT code buffer for %s too small", istr(blob->span->name));
×
449
      for (patch_list_t *it = blob->patches, *tmp; it; it = tmp) {
×
450
         tmp = it->next;
×
451
         free(it);
×
452
      }
453
      blob->patches = NULL;
×
454
      blob->overflow = true;
×
455
      return;
×
456
   }
457

458
   for (size_t i = 0; i < len; i++)
19,400✔
459
      *(blob->wptr++) = bytes[i];
11,282✔
460
}
461

462
void code_blob_align(code_blob_t *blob, unsigned align)
×
463
{
464
#ifdef ARCH_X86_64
465
   const uint8_t pad[] = { 0x90 };
×
466
#else
467
   const uint8_t pad[] = { 0x00 };
468
#endif
469

470
   assert(is_power_of_2(align));
×
471
   assert(align % ARRAY_LEN(pad) == 0);
472

473
   while (((uintptr_t)blob->wptr & (align - 1)) && !blob->overflow)
×
474
      code_blob_emit(blob, pad, ARRAY_LEN(pad));
×
475
}
×
476

477
void code_blob_mark(code_blob_t *blob, jit_label_t label)
54✔
478
{
479
   if (unlikely(blob->overflow))
54✔
480
      return;
481
   else if (blob->labels == NULL)
54✔
482
      blob->labels = ihash_new(256);
49✔
483

484
   ihash_put(blob->labels, label, blob->wptr);
54✔
485

486
   for (patch_list_t **p = &(blob->patches); *p; ) {
71✔
487
      if ((*p)->label == label) {
17✔
488
         patch_list_t *next = (*p)->next;
7✔
489
         (*(*p)->fn)(blob, label, (*p)->wptr, blob->wptr);
7✔
490
         free(*p);
7✔
491
         *p = next;
7✔
492
      }
493
      else
494
         p = &((*p)->next);
10✔
495
   }
496
}
497

498
void code_blob_patch(code_blob_t *blob, jit_label_t label, code_patch_fn_t fn)
8✔
499
{
500
   void *ptr = NULL;
8✔
501
   if (unlikely(blob->overflow))
8✔
502
      return;
503
   else if (blob->labels != NULL && (ptr = ihash_get(blob->labels, label)))
8✔
504
      (*fn)(blob, label, blob->wptr, ptr);
1✔
505
   else {
506
      patch_list_t *new = xmalloc(sizeof(patch_list_t));
7✔
507
      new->next  = blob->patches;
7✔
508
      new->fn    = fn;
7✔
509
      new->label = label;
7✔
510
      new->wptr  = blob->wptr;
7✔
511

512
      blob->patches = new;
7✔
513
   }
514
}
515

516
#ifdef ARCH_ARM64
517
static void *arm64_emit_trampoline(code_blob_t *blob, uintptr_t dest)
518
{
519
   const uint8_t veneer[] = {
520
      0x50, 0x00, 0x00, 0x58,   // LDR X16, [PC+8]
521
      0x00, 0x02, 0x1f, 0xd6,   // BR X16
522
      __IMM64(dest)
523
   };
524

525
   void *prev = memmem(blob->span->base, blob->span->size,
526
                       veneer, ARRAY_LEN(veneer));
527
   if (prev != NULL)
528
      return prev;
529
   else {
530
      void *addr = blob->wptr;
531
      code_blob_emit(blob, veneer, ARRAY_LEN(veneer));
532
      return addr;
533
   }
534
}
535
#else
536
#define arm64_emit_trampoline(blob, dest) NULL
537
#endif
538

539
#if defined __MINGW32__
540
static void code_load_pe(code_blob_t *blob, const void *data, size_t size)
541
{
542
   const IMAGE_FILE_HEADER *imghdr = data;
543

544
   if (imghdr->Machine != IMAGE_FILE_MACHINE_AMD64)
545
      fatal_trace("unknown target machine %x", imghdr->Machine);
546

547
   const IMAGE_SYMBOL *symtab = data + imghdr->PointerToSymbolTable;
548
   const char *strtab = data + imghdr->PointerToSymbolTable
549
      + imghdr->NumberOfSymbols * sizeof(IMAGE_SYMBOL);
550

551
   const IMAGE_SECTION_HEADER *sections =
552
      data + IMAGE_SIZEOF_FILE_HEADER + imghdr->SizeOfOptionalHeader;
553

554
   void **load_addr LOCAL =
555
      xmalloc_array(imghdr->NumberOfSections, sizeof(void *));
556

557
   for (int i = 0; i < imghdr->NumberOfSections; i++) {
558
      if ((sections[i].Characteristics & IMAGE_SCN_CNT_CODE)
559
          || (sections[i].Characteristics & IMAGE_SCN_CNT_INITIALIZED_DATA)) {
560
         const int align = sections[i].Characteristics & IMAGE_SCN_ALIGN_MASK;
561
         code_blob_align(blob, 1 << ((align >> 20) - 1));
562
         load_addr[i] = blob->wptr;
563
         code_blob_emit(blob, data + sections[i].PointerToRawData,
564
                        sections[i].SizeOfRawData);
565
      }
566
      else if ((sections[i].Characteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA)
567
               && sections[i].Misc.VirtualSize > 0)
568
         fatal_trace("non-empty BSS not supported");
569
   }
570

571
   if (blob->overflow)
572
      return;   // Relocations might point outside of code span
573

574
   for (int i = 0; i < imghdr->NumberOfSections; i++) {
575
      const IMAGE_RELOCATION *relocs = data + sections[i].PointerToRelocations;
576
      for (int j = 0; j < sections[i].NumberOfRelocations; j++) {
577
         const char *name = NULL;
578
         char tmp[9];
579

580
         assert(relocs[j].SymbolTableIndex < imghdr->NumberOfSymbols);
581
         const IMAGE_SYMBOL *sym = symtab + relocs[j].SymbolTableIndex;
582

583
         if (sym->N.Name.Short) {
584
            memcpy(tmp, sym->N.ShortName, 8);
585
            tmp[8] = '\0';
586
            name = tmp;
587
         }
588
         else
589
            name = strtab + sym->N.Name.Long;
590

591
         void *ptr = NULL;
592
         if (sym->SectionNumber > 0) {
593
            assert(sym->SectionNumber - 1 < imghdr->NumberOfSections);
594
            ptr = load_addr[sym->SectionNumber - 1];
595
         }
596
         else if (strcmp(name, "___chkstk_ms") == 0) {
597
            extern void ___chkstk_ms(void);
598
            ptr = &___chkstk_ms;
599
         }
600
         else
601
            ptr = ffi_find_symbol(NULL, name);
602

603
         if (ptr == NULL)
604
            fatal_trace("failed to resolve symbol %s", name);
605

606
         void *patch = load_addr[i] + relocs[j].VirtualAddress;
607
         assert((uint8_t *)patch >= blob->span->base);
608
         assert((uint8_t *)patch < blob->span->base + blob->span->size);
609

610
         switch (relocs[j].Type) {
611
         case IMAGE_REL_AMD64_ADDR64:
612
            *(uint64_t *)patch += (uint64_t)ptr;
613
            break;
614
         case IMAGE_REL_AMD64_ADDR32NB:
615
            *(uint32_t *)patch += (uint32_t)(ptr - (void *)blob->span->base);
616
            break;
617
         default:
618
            blob->span->size = blob->wptr - blob->span->base;
619
            code_disassemble(blob->span, (uintptr_t)patch, NULL);
620
            fatal_trace("cannot handle relocation type %d for symbol %s",
621
                        relocs[j].Type, name);
622
         }
623
      }
624

625
      if (strncmp((const char *)sections[i].Name, ".pdata",
626
                  IMAGE_SIZEOF_SHORT_NAME) == 0) {
627
         assert(sections[i].SizeOfRawData % sizeof(RUNTIME_FUNCTION) == 0);
628
         const int count = sections[i].SizeOfRawData / sizeof(RUNTIME_FUNCTION);
629
         const DWORD64 base = (DWORD64)blob->span->base;
630

631
         // TODO: we should also call RtlDeleteFunctionTable at some point
632
         if (!RtlAddFunctionTable(load_addr[i], count, base))
633
            fatal_trace("RtlAddFunctionTable failed: %s", last_os_error());
634
      }
635
   }
636
}
637
#elif defined __APPLE__
638
static void code_load_macho(code_blob_t *blob, const void *data, size_t size)
639
{
640
   const void *rptr = data;
641

642
   const struct mach_header_64 *fhdr = rptr;
643
   rptr += sizeof(struct mach_header_64);
644

645
   if (fhdr->magic != MH_MAGIC_64)
646
      fatal_trace("bad Mach-O magic %x", fhdr->magic);
647

648
   const struct segment_command_64 *seg = NULL;
649
   const struct symtab_command *symtab = NULL;
650

651
   void **load_addr LOCAL = NULL;
652

653
   for (int i = 0; i < fhdr->ncmds; i++) {
654
      const struct load_command *load = rptr;
655
      switch (load->cmd) {
656
      case LC_SEGMENT_64:
657
         {
658
            seg = rptr;
659
            load_addr = xmalloc_array(seg->nsects, sizeof(void *));
660

661
            for (int j = 0; j < seg->nsects; j++) {
662
               const struct section_64 *sec =
663
                  (void *)seg + sizeof(struct segment_command_64)
664
                  + j * sizeof(struct section_64);
665
               code_blob_align(blob, 1 << sec->align);
666
               load_addr[j] = blob->wptr;
667
               code_blob_emit(blob, data + sec->offset, sec->size);
668
            }
669
         }
670
         break;
671
      case LC_SYMTAB:
672
         symtab = rptr;
673
         assert(symtab->cmdsize == sizeof(struct symtab_command));
674
         break;
675
      case LC_LINKER_OPTIMIZATION_HINT:
676
      case LC_BUILD_VERSION:
677
      case LC_DYSYMTAB:
678
         break;
679
      default:
680
         warnf("unrecognised load command 0x%0x", seg->cmd);
681
      }
682

683
      rptr += load->cmdsize;
684
   }
685
   assert(rptr == data + sizeof(struct mach_header_64) + fhdr->sizeofcmds);
686

687
   if (blob->overflow)
688
      return;   // Relocations might point outside of code span
689

690
   assert(seg != NULL);
691
   assert(symtab != NULL);
692

693
   for (int i = 0; i < seg->nsects; i++) {
694
      const struct section_64 *sec =
695
         (void *)seg + sizeof(struct segment_command_64)
696
         + i * sizeof(struct section_64);
697

698
      uint32_t addend = 0;
699
      for (int j = 0; j < sec->nreloc; j++) {
700
         const struct relocation_info *rel =
701
            data + sec->reloff + j * sizeof(struct relocation_info);
702
         const char *name = NULL;
703
         void *ptr = NULL;
704
         if (rel->r_extern) {
705
            assert(rel->r_symbolnum < symtab->nsyms);
706
            const struct nlist_64 *nl = data + symtab->symoff
707
               + rel->r_symbolnum * sizeof(struct nlist_64);
708
            name = data + symtab->stroff + nl->n_un.n_strx;
709

710
            if (nl->n_type & N_EXT) {
711
               if (icmp(blob->span->name, name + 1))
712
                  ptr = blob->span->base;
713
               else if ((ptr = ffi_find_symbol(NULL, name + 1)) == NULL)
714
                  fatal_trace("failed to resolve symbol %s", name + 1);
715
            }
716
            else if (nl->n_sect != NO_SECT)
717
               ptr = blob->span->base + nl->n_value;
718
         }
719
         else
720
            ptr = blob->span->base;
721

722
         ptr += addend;
723
         addend = 0;
724

725
         void *patch = load_addr[i] + rel->r_address;
726
         assert((uint8_t *)patch >= blob->span->base);
727
         assert((uint8_t *)patch < blob->span->base + blob->span->size);
728

729
         switch (rel->r_type) {
730
         case ARM64_RELOC_UNSIGNED:
731
            assert(rel->r_length == 3);
732
            *(void **)patch = ptr;
733
            break;
734
         case ARM64_RELOC_SUBTRACTOR:
735
            break;   // What is this?
736
         case ARM64_RELOC_GOT_LOAD_PAGEOFF12:
737
         case ARM64_RELOC_PAGEOFF12:
738
            switch ((*(uint32_t *)patch >> 23) & 0x7f) {
739
            case 0b1111010:   // LDR (immediate, SIMD&FP)
740
            case 0b1110010:   // LDR (immediate)
741
               assert(*(uint32_t *)patch & (1 << 30));  // Quadword
742
               assert(((uintptr_t)ptr & 7) == 0);
743
               *(uint32_t *)patch |= (((uintptr_t)ptr & 0xfff) >> 3) << 10;
744
               break;
745
            case 0b0100010:   // ADD (immediate)
746
               *(uint32_t *)patch |= ((uintptr_t)ptr & 0xfff) << 10;
747
               break;
748
            default:
749
               blob->span->size = blob->wptr - blob->span->base;
750
               code_disassemble(blob->span, (uintptr_t)patch, NULL);
751
               fatal_trace("cannot patch instruction");
752
            }
753
            break;
754
         case ARM64_RELOC_GOT_LOAD_PAGE21:
755
         case ARM64_RELOC_PAGE21:
756
            {
757
               const intptr_t dst_page = (intptr_t)ptr & ~UINT64_C(0xfff);
758
               const intptr_t src_page = (intptr_t)patch & ~UINT64_C(0xfff);
759
               const intptr_t upper21 = (dst_page - src_page) >> 12;
760
               *(uint32_t *)patch |= (upper21 & 3) << 29;
761
               *(uint32_t *)patch |= ((upper21 >> 2) & 0x7ffff) << 5;
762
            }
763
            break;
764
         case ARM64_RELOC_BRANCH26:
765
            {
766
               void *veneer = arm64_emit_trampoline(blob, (uintptr_t)ptr);
767
               const ptrdiff_t pcrel = (veneer - patch) >> 2;
768
               *(uint32_t *)patch &= ~0x3ffffff;
769
               *(uint32_t *)patch |= pcrel & 0x3ffffff;
770
            }
771
            break;
772
         case ARM64_RELOC_ADDEND:
773
            addend = rel->r_symbolnum;
774
            break;
775
         default:
776
            blob->span->size = blob->wptr - blob->span->base;
777
            code_disassemble(blob->span, (uintptr_t)patch, NULL);
778
            fatal_trace("cannot handle relocation type %d for symbol %s",
779
                        rel->r_type, name);
780
         }
781
      }
782
   }
783
}
784
#elif !defined __MINGW32__
785
static void code_load_elf(code_blob_t *blob, const void *data, size_t size)
786
{
787
   const Elf64_Ehdr *ehdr = data;
788

789
   if (ehdr->e_ident[EI_MAG0] != ELFMAG0
790
       || ehdr->e_ident[EI_MAG1] != ELFMAG1
791
       || ehdr->e_ident[EI_MAG2] != ELFMAG2
792
       || ehdr->e_ident[EI_MAG3] != ELFMAG3)
793
      fatal_trace("bad ELF magic");
794
   else if (ehdr->e_shentsize != sizeof(Elf64_Shdr))
795
      fatal_trace("bad section header size %d != %zu", ehdr->e_shentsize,
796
                  sizeof(Elf64_Shdr));
797

798
   const Elf64_Shdr *strtab_hdr =
799
      data + ehdr->e_shoff + ehdr->e_shstrndx * ehdr->e_shentsize;
800
   const char *strtab = data + strtab_hdr->sh_offset;
801

802
   void **load_addr LOCAL = xcalloc_array(ehdr->e_shnum, sizeof(void *));
803

804
   for (int i = 0; i < ehdr->e_shnum; i++) {
805
      const Elf64_Shdr *shdr = data + ehdr->e_shoff + i * ehdr->e_shentsize;
806

807
      switch (shdr->sh_type) {
808
      case SHT_PROGBITS:
809
         if (shdr->sh_flags & SHF_ALLOC) {
810
            code_blob_align(blob, shdr->sh_addralign);
811
            load_addr[i] = blob->wptr;
812
            code_blob_emit(blob, data + shdr->sh_offset, shdr->sh_size);
813
         }
814
         break;
815

816
      case SHT_RELA:
817
         // Handled in second pass
818
         break;
819

820
      case SHT_NULL:
821
      case SHT_STRTAB:
822
      case SHT_X86_64_UNWIND:
823
      case SHT_SYMTAB:
824
         break;
825

826
      default:
827
         warnf("ignoring ELF section %s with type %x", strtab + shdr->sh_name,
828
               shdr->sh_type);
829
      }
830
   }
831

832
   if (blob->overflow)
833
      return;   // Relocations might point outside of code span
834

835
   for (int i = 0; i < ehdr->e_shnum; i++) {
836
      const Elf64_Shdr *shdr = data + ehdr->e_shoff + i * ehdr->e_shentsize;
837
      if (shdr->sh_type != SHT_RELA)
838
         continue;
839

840
      const Elf64_Shdr *mod =
841
         data + ehdr->e_shoff + shdr->sh_info * ehdr->e_shentsize;
842
      if (mod->sh_type != SHT_PROGBITS || !(mod->sh_flags & SHF_ALLOC))
843
         continue;
844
      else if (load_addr[shdr->sh_info] == NULL)
845
         fatal_trace("section %s not loaded", strtab + mod->sh_name);
846

847
      const Elf64_Shdr *symtab =
848
         data + ehdr->e_shoff + shdr->sh_link * ehdr->e_shentsize;
849
      if (symtab->sh_type != SHT_SYMTAB)
850
         fatal_trace("section %s is not a symbol table",
851
                     strtab + symtab->sh_name);
852

853
      const Elf64_Rela *endp = data + shdr->sh_offset + shdr->sh_size;
854
      for (const Elf64_Rela *r = data + shdr->sh_offset; r < endp; r++) {
855
         const Elf64_Sym *sym = data + symtab->sh_offset
856
            + ELF64_R_SYM(r->r_info) * symtab->sh_entsize;
857

858
         char *ptr = NULL;
859
         switch (ELF64_ST_TYPE(sym->st_info)) {
860
         case STT_NOTYPE:
861
         case STT_FUNC:
862
            ptr = ffi_find_symbol(NULL, strtab + sym->st_name);
863
            break;
864
         case STT_SECTION:
865
            ptr = load_addr[sym->st_shndx];
866
            break;
867
         }
868

869
         if (ptr == NULL)
870
            fatal_trace("cannot resolve symbol %s type %d",
871
                        strtab + sym->st_name, ELF64_ST_TYPE(sym->st_info));
872

873
         ptr += r->r_addend;
874

875
         void *patch = load_addr[shdr->sh_info] + r->r_offset;
876
         assert(r->r_offset < mod->sh_size);
877

878
         switch (ELF64_R_TYPE(r->r_info)) {
879
         case R_X86_64_64:
880
            *(uint64_t *)patch = (uint64_t)ptr;
881
            break;
882
         case R_AARCH64_CALL26:
883
            {
884
               void *veneer = arm64_emit_trampoline(blob, (uintptr_t)ptr);
885
               const ptrdiff_t pcrel = (veneer - patch) >> 2;
886
               *(uint32_t *)patch &= ~0x3ffffff;
887
               *(uint32_t *)patch |= pcrel & 0x3ffffff;
888
            }
889
            break;
890
         case R_AARCH64_PREL64:
891
            *(uint64_t *)patch = ptr - (char *)patch;
892
            break;
893
         case R_AARCH64_MOVW_UABS_G0_NC:
894
            *(uint32_t *)patch |= ((uintptr_t)ptr & 0xffff) << 5;
895
            break;
896
         case R_AARCH64_MOVW_UABS_G1_NC:
897
            *(uint32_t *)patch |= (((uintptr_t)ptr >> 16) & 0xffff) << 5;
898
            break;
899
         case R_AARCH64_MOVW_UABS_G2_NC:
900
            *(uint32_t *)patch |= (((uintptr_t)ptr >> 32) & 0xffff) << 5;
901
            break;
902
         case R_AARCH64_MOVW_UABS_G3:
903
            *(uint32_t *)patch |= (((uintptr_t)ptr >> 48) & 0xffff) << 5;
904
            break;
905
         default:
906
            blob->span->size = blob->wptr - blob->span->base;
907
            code_disassemble(blob->span, (uintptr_t)patch, NULL);
908
            fatal_trace("cannot handle relocation type %ld for symbol %s",
909
                        ELF64_R_TYPE(r->r_info), strtab + sym->st_name);
910
         }
911
      }
912
   }
913
}
914
#endif
915

916
void code_load_object(code_blob_t *blob, const void *data, size_t size)
×
917
{
918
#if defined __APPLE__
919
   code_load_macho(blob, data, size);
920
#elif defined __MINGW32__
921
   code_load_pe(blob, data, size);
922
#else
923
   code_load_elf(blob, data, size);
×
924
#endif
925
}
×
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