-
-
Notifications
You must be signed in to change notification settings - Fork 216
/
jit.c
2055 lines (1950 loc) · 61.4 KB
/
jit.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
│ vi: set et ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi │
╞══════════════════════════════════════════════════════════════════════════════╡
│ Copyright 2022 Justine Alexandra Roberts Tunney │
│ │
│ Permission to use, copy, modify, and/or distribute this software for │
│ any purpose with or without fee is hereby granted, provided that the │
│ above copyright notice and this permission notice appear in all copies. │
│ │
│ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │
│ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │
│ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │
│ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │
│ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │
│ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │
│ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │
│ PERFORMANCE OF THIS SOFTWARE. │
╚─────────────────────────────────────────────────────────────────────────────*/
#include "blink/jit.h"
#include <errno.h>
#include <limits.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <unistd.h>
#include "blink/assert.h"
#include "blink/atomic.h"
#include "blink/bitscan.h"
#include "blink/builtin.h"
#include "blink/checked.h"
#include "blink/debug.h"
#include "blink/dll.h"
#include "blink/end.h"
#include "blink/endian.h"
#include "blink/errno.h"
#include "blink/flag.h"
#include "blink/log.h"
#include "blink/macros.h"
#include "blink/map.h"
#include "blink/memcpy.h"
#include "blink/stats.h"
#include "blink/thread.h"
#include "blink/tsan.h"
#include "blink/util.h"
/**
* @fileoverview Just-In-Time Function Builder
*
* This file implements a low-level systems abstraction that enables
* native functions to be written to memory and then executed. These
* interfaces are used by Jitter() which is a higher-level interface
* that's intended for generating implementations of x86 operations.
*
* This JIT only supports x86-64 and aarch64. That makes life easier
* since both architectures have many registers and a register-based
* calling convention. This JIT works around the restrictions placed
* upon self-modifying code imposed by both OSes and microprocessors
* such as:
*
* 1. ARM CPUs require a non-trivial flushing of instruction caches.
* 2. OpenBSD always imposes strict W^X memory protection invariant.
* 3. Apple requires we use JIT memory and toggle thread JIT states.
* 4. ISAs limit the distance between JIT memory and our executable.
* 5. Some platforms have a weird page size, e.g. Apple M1 is 16384.
*
* Meeting the requirements of all these platforms, means we have to
* follow a very narrow path of possibilities, in terms of practices
* plus design. These APIs make conformance easier. The way it works
* here is multiple pages of memory are allocated in chunks, that we
* call "blocks". Each time a thread wishes to create a function, it
* must lease one of these blocks using StartJit(), FinishJit(), and
* SpliceJit(). During that lease, functions may be generated, which
* call arbitrary functions built by the compiler. Any function made
* here needs to have a non-JIT implementation that can be called to
* allow time for the JIT block to be flushed, at which time the JIT
* updates a corresponding function hook.
*
* // setup a multi-threaded jit manager
* struct Jit jit;
* InitJit(&jit, 0);
*
* // workflow for composing two function calls
* i64 key = 1234;
* long Adder(long x, long y) { return x + y; }
* struct JitBlock *jb;
* jb = StartJit(jit, key);
* AppendJit(jb, kPrologue, sizeof(kPrologue));
* AppendJitSetReg(jb, kJitArg0, 1);
* AppendJitSetReg(jb, kJitArg1, 2);
* AppendJitCall(jb, (void *)Adder);
* AppendJitMovReg(jb, kJitRes0, kJitArg0);
* AppendJitSetReg(jb, kJitArg1, 3);
* AppendJitCall(jb, (void *)Adder);
* AppendJit(jb, kEpilogue, sizeof(kEpilogue));
* FinishJit(jit, jb);
* FlushJit(jit);
* printf("1+2+3=%ld\n", ((long (*)(void))(GetJitHook(jit, key)))());
*
* // destroy jit and all its functions
* DestroyJit(&jit);
*
* Note that FlushJit() should only be a last resort. Functions will
* become live immediately on operating systems which authorize self
* modifying-code using RWX memory and have the appropriate compiler
* builtin for flushing the CPU instruction cach. If weird platforms
* aren't a concern, then the hairiness of hooking and/or FlushJit()
* shouldn't be of any concern. Try using CanJitForImmediateEffect()
* after having called StartJit() to check.
*/
#define kMaximumAnticipatedPageSize 65536
const u8 kJitRes[2] = {kJitRes0, kJitRes1};
const u8 kJitArg[4] = {kJitArg0, kJitArg1, kJitArg2, kJitArg3};
const u8 kJitSav[5] = {kJitSav0, kJitSav1, kJitSav2, kJitSav3, kJitSav4};
#ifdef HAVE_JIT
#define ACTION_MOVE 0x010000
#define ACTION(a) ((0xff0000 & a))
#define MOVE(dst, src) ((dst) | (src) << 8 | ACTION_MOVE)
#define MOVE_DST(a) ((0x0000ff & (a)) >> 0)
#define MOVE_SRC(a) ((0x00ff00 & (a)) >> 8)
#define HASH(virt) (virt)
static u8 g_code[kJitMemorySize];
static struct JitGlobals {
pthread_mutex_t_ lock;
_Atomic(long) prot;
int freecount;
struct Dll *freeblocks;
} g_jit = {
PTHREAD_MUTEX_INITIALIZER_,
PROT_READ | PROT_WRITE | PROT_EXEC,
};
static inline u64 RoundupTwoPow(u64 x) {
return x > 1 ? (u64)2 << bsr(x - 1) : x ? 1 : 0;
}
// begins write operation to memory that may be read locklessly
// - generation is monotonic
// - even numbers mean memory is ready
// - odd numbers mean memory is actively being changed
static inline unsigned BeginUpdate(_Atomic(unsigned) *genptr) {
unsigned gen = atomic_load_explicit(genptr, memory_order_relaxed);
unassert(~gen & 1); // prevents re-entering transaction
atomic_store_explicit(genptr, gen + 1, memory_order_release);
return gen;
}
// finishes write operation to memory that may be read locklessly
static inline void EndUpdate(_Atomic(unsigned) *genptr, unsigned gen) {
unassert(~gen & 1);
atomic_store_explicit(genptr, gen + 2, memory_order_release);
}
// determines if lockless operation should be retried or abandoned
static inline unsigned ShallNotPass(unsigned gen1, _Atomic(unsigned) *genptr) {
unsigned gen2 = atomic_load_explicit(genptr, memory_order_acquire);
unsigned is_being_actively_changed = gen1 & 1;
unsigned we_lost_race_with_writers = gen1 ^ gen2;
return is_being_actively_changed | we_lost_race_with_writers;
}
// apple forbids rwx memory on their new m1 macbooks and requires that
// we use a non-posix api in order to have jit. the problem is the api
// frequently flakes with "Trace/BPT trap: 5" errors. this fixes that.
static void pthread_jit_write_protect_np_workaround(int enabled) {
#if defined(__APPLE__) && defined(__aarch64__)
int count_start = 8192;
volatile int count = count_start;
uint64_t *addr, val, val2, reread = -1;
addr = (uint64_t *)(!enabled ? _COMM_PAGE_APRR_WRITE_ENABLE
: _COMM_PAGE_APRR_WRITE_DISABLE);
// other = (uint64_t *)(enabled ? _COMM_PAGE_APRR_WRITE_ENABLE
// : _COMM_PAGE_APRR_WRITE_DISABLE);
switch (*(volatile uint8_t *)_COMM_PAGE_APRR_SUPPORT) {
case 1:
do {
val = *addr;
reread = -1;
asm volatile("msr S3_4_c15_c2_7, %0\n"
"isb sy\n"
: /* no outputs */
: "r"(val)
: "memory");
val2 = *addr;
asm volatile("mrs %0, S3_4_c15_c2_7\n"
: "=r"(reread)
: /* no inputs */
: "memory");
if (val2 == reread) {
return;
}
usleep(10);
} while (count-- > 0);
break;
case 3:
do {
val = *addr;
reread = -1;
asm volatile("msr S3_6_c15_c1_5, %0\n"
"isb sy\n"
: /* no outputs */
: "r"(val)
: "memory");
val2 = *addr;
asm volatile("mrs %0, S3_6_c15_c1_5\n"
: "=r"(reread)
: /* no inputs */
: "memory");
if (val2 == reread) {
return;
}
usleep(10);
} while (count-- > 0);
break;
default:
pthread_jit_write_protect_np(enabled);
return;
}
ERRF("failed to set jit write protection");
Abort();
#else
pthread_jit_write_protect_np(enabled);
#endif
}
static void *Calloc(size_t nmemb, size_t size) {
STATISTIC(++jit_callocs);
return calloc(nmemb, size);
#define calloc please_use_Calloc
}
static void *Realloc(void *p, size_t n) {
STATISTIC(++jit_reallocs);
return realloc(p, n);
#define realloc please_use_Realloc
}
static void Free(void *ptr) {
if (!ptr) return;
STATISTIC(++jit_frees);
free(ptr);
#define free please_use_Free
}
static struct JitJump *NewJitJump(struct Dll **freejumps) {
struct Dll *e;
struct JitJump *jj;
if ((e = dll_first(*freejumps))) {
STATISTIC(++jit_jump_alloc_freelist);
dll_remove(freejumps, e);
jj = JITJUMP_CONTAINER(e);
} else if ((jj = (struct JitJump *)Calloc(1, sizeof(struct JitJump)))) {
STATISTIC(++jit_jump_alloc_system);
dll_init(&jj->elem);
}
return jj;
}
static struct JitPage *NewJitPage(void) {
struct JitPage *jj;
if ((jj = (struct JitPage *)Calloc(1, sizeof(struct JitPage)))) {
dll_init(&jj->elem);
}
return jj;
}
static struct JitBlock *NewJitBlock(void) {
struct JitBlock *jb;
if ((jb = (struct JitBlock *)Calloc(1, sizeof(struct JitBlock)))) {
dll_init(&jb->elem);
dll_init(&jb->aged);
JIT_LOGF("new jit block %p", jb);
}
return jb;
}
static struct JitStage *NewJitStage(void) {
struct JitStage *js;
if ((js = (struct JitStage *)Calloc(1, sizeof(struct JitStage)))) {
dll_init(&js->elem);
}
return js;
}
static struct JitFreed *NewJitFreed(void) {
struct JitFreed *jf;
if ((jf = (struct JitFreed *)Calloc(1, sizeof(struct JitFreed)))) {
dll_init(&jf->elem);
}
return jf;
}
static struct JitIntsSlab *NewJitIntsSlab(void) {
struct JitIntsSlab *jis;
if ((jis = (struct JitIntsSlab *)Calloc(1, sizeof(struct JitIntsSlab)))) {
dll_init(&jis->elem);
}
return jis;
}
static void FreeJitJump(struct JitJump *jj) {
Free(jj);
}
static void FreeJitPage(struct JitPage *jp) {
Free(jp);
}
static void FreeJitFreed(struct JitFreed *jf) {
Free(jf->data);
Free(jf);
}
static void DestroyInts(struct JitInts *ji) {
if (ji->p != ji->m) {
Free(ji->p);
}
}
static void FreeJitBlock(struct JitBlock *jb) {
struct Dll *e;
JIT_LOGF("freed jit block %p", jb);
while ((e = dll_first(jb->freejumps))) {
dll_remove(&jb->freejumps, e);
FreeJitJump(JITJUMP_CONTAINER(e));
}
Free(jb);
}
static void FreeJitStage(struct JitStage *js) {
Free(js);
}
static void DestroyIntsAllocator(struct JitIntsAllocator *jia) {
int i;
struct Dll *e, *e2;
struct JitIntsSlab *jis;
Free(jia->p);
for (e = dll_first(jia->slabs); e; e = e2) {
e2 = dll_next(jia->slabs, e);
jis = JIASLAB_CONTAINER(e);
for (i = 0; i < ARRAYLEN(jis->p); ++i) {
DestroyInts(jis->p + i);
}
Free(jis);
}
}
static dontinline bool GrowIntsAllocator(struct JitIntsAllocator *jia) {
int n2;
struct JitInts **p2;
p2 = jia->p;
n2 = jia->n;
if (n2 >= 2) {
n2 += n2 >> 1;
} else {
n2 = 8;
}
if ((p2 = (struct JitInts **)Realloc(p2, n2 * sizeof(*p2)))) {
jia->p = p2;
jia->n = n2;
return true;
} else {
return false;
}
}
static struct JitInts *NewInts(struct JitIntsAllocator *jia) {
struct Dll *e;
struct JitInts *ji;
struct JitIntsSlab *slab;
if (jia->i) {
STATISTIC(++jit_ints_alloc_freelist);
return jia->p[--jia->i];
}
if ((e = dll_first(jia->slabs))) {
STATISTIC(++jit_ints_alloc_slab);
slab = JIASLAB_CONTAINER(e);
if (slab->i < ARRAYLEN(slab->p)) {
ji = slab->p + slab->i++;
ji->p = ji->m;
ji->n = ARRAYLEN(ji->m);
return ji;
}
}
if ((slab = NewJitIntsSlab())) {
STATISTIC(++jit_ints_alloc_system);
dll_make_first(&jia->slabs, &slab->elem);
return slab->p + slab->i++;
}
return 0;
}
static void FreeInts(struct JitIntsAllocator *jia, struct JitInts *ji) {
if (ji) {
ji->i = 0;
if (jia->i == jia->n && !GrowIntsAllocator(jia)) return;
jia->p[jia->i++] = ji;
}
}
static bool GrowInts(struct JitInts *ji) {
i64 *p2;
size_t i, n2;
p2 = ji->p;
if (!ji->p) {
unassert(!ji->n);
ji->p = ji->m;
ji->n = ARRAYLEN(ji->m);
return true;
} else if (ji->p == ji->m) {
unassert(ji->n == ARRAYLEN(ji->m));
n2 = ARRAYLEN(ji->m) * 2;
if ((p2 = Calloc(n2, sizeof(*p2)))) {
for (i = 0; i < ARRAYLEN(ji->m); ++i) {
p2[i] = ji->m[i];
}
ji->p = p2;
ji->n = n2;
return true;
} else {
return false;
}
} else {
n2 = ji->n;
n2 += n2 >> 1;
if ((p2 = (i64 *)Realloc(p2, n2 * sizeof(*p2)))) {
ji->p = p2;
ji->n = n2;
return true;
} else {
return false;
}
}
}
static bool AddInt(struct JitInts *ji, i64 x) {
if (ji->i == ji->n && !GrowInts(ji)) return false;
ji->p[ji->i++] = x;
return true;
}
static bool RemoveInt(struct JitInts *ji, i64 x) {
int i, j;
for (i = j = 0; i < ji->i; ++i) {
if (ji->p[i] != x) {
ji->p[j++] = ji->p[i];
}
}
ji->i -= i - j;
return i > j;
}
static void InitEdges(struct JitEdges *e) {
memset(e, 0, sizeof(*e));
e->n = RoundupTwoPow(kJitInitialEdges);
unassert(e->src = (i64 *)Calloc(e->n, sizeof(*e->src)));
unassert(e->dst = (struct JitInts **)Calloc(e->n, sizeof(*e->dst)));
}
static void DestroyEdges(struct JitEdges *edges) {
DestroyIntsAllocator(&edges->jia);
Free(edges->dst);
Free(edges->src);
}
static nosideeffect int GetEdge(const struct JitEdges *edges, i64 src) {
unsigned hash, spot, step;
hash = HASH(src);
for (spot = step = 0;; ++step) {
spot = (hash + step * ((step + 1) >> 1)) & (edges->n - 1);
if (!edges->src[spot] || edges->src[spot] == src) {
return spot;
}
}
}
static unsigned GrowEdges(struct JitEdges *edges) {
i64 *src, *src2;
struct JitInts **dst, **dst2;
unsigned i, i1, i2, n1, n2, used, hash, spot, step;
i1 = edges->i;
n1 = edges->n;
src = edges->src;
dst = edges->dst;
unassert(n1 > 1 && IS2POW(n1));
for (used = i = 0; i < n1; ++i) used += !!dst[i];
n2 = n1 << (used > (n1 >> 2));
if (!(src2 = (i64 *)Calloc(n2, sizeof(*src2))) ||
!(dst2 = (struct JitInts **)Calloc(n2, sizeof(*dst2)))) {
Free(src2);
return 0;
}
for (i2 = i = 0; i < n1; ++i) {
if (!src[i]) {
unassert(!dst[i]);
continue;
}
--i1;
if (!dst[i]) {
continue;
}
++i2;
spot = 0;
step = 0;
hash = HASH(src[i]);
do {
spot = (hash + step * ((step + 1) >> 1)) & (n2 - 1);
unassert(src2[spot] != src[i]);
++step;
} while (src2[spot]);
src2[spot] = src[i];
dst2[spot] = dst[i];
}
unassert(!i1);
edges->i = i2;
edges->n = n2;
edges->src = src2;
edges->dst = dst2;
Free(src);
Free(dst);
return n2;
}
static bool AddEdge(struct JitEdges *edges, i64 src, i64 dst) {
int s;
if (edges->i == (edges->n >> 1)) {
if (!GrowEdges(edges)) return false;
}
if (!edges->src[(s = GetEdge(edges, src))]) {
edges->src[s] = src;
++edges->i;
}
if (!edges->dst[s]) {
if (!(edges->dst[s] = NewInts(&edges->jia))) return false;
}
return AddInt(edges->dst[s], dst);
}
static void RemoveEdgesByIndex(struct JitEdges *edges, int s) {
unassert(s >= 0 && s < edges->n);
FreeInts(&edges->jia, edges->dst[s]);
edges->dst[s] = 0;
}
static bool RemoveEdges(struct JitEdges *edges, i64 src) {
int s;
if (!edges->dst[(s = GetEdge(edges, src))]) return false;
RemoveEdgesByIndex(edges, s);
return true;
}
static bool RemoveEdge(struct JitEdges *edges, i64 src, i64 dst) {
int s;
if (!edges->dst[(s = GetEdge(edges, src))]) return false;
if (!RemoveInt(edges->dst[s], dst)) return false;
if (!edges->dst[s]->i) RemoveEdgesByIndex(edges, s);
return true;
}
static void ClearEdges(struct JitEdges *edges) {
int i;
for (i = 0; i < edges->n; ++i) {
edges->src[i] = 0;
RemoveEdgesByIndex(edges, i);
}
edges->i = 0;
}
static bool IsCyclic(struct JitEdges *edges, i64 V[kJitDepth], int d, i64 dst) {
int i, s;
if (d == kJitDepth) {
return true;
}
for (i = 0; i < d; ++i) {
if (dst == V[i]) {
return true;
}
}
V[d++] = dst;
if (edges->dst[(s = GetEdge(edges, dst))]) {
for (i = 0; i < edges->dst[s]->i; ++i) {
if (IsCyclic(edges, V, d, edges->dst[s]->p[i])) {
return true;
}
}
}
return false;
}
static inline uintptr_t DecodeJitFunc(int func) {
unassert(func);
return (intptr_t)IMAGE_END + func;
}
static nosideeffect int EncodeJitFunc(intptr_t addr) {
int func;
intptr_t base, disp;
if (addr) {
base = (intptr_t)IMAGE_END;
disp = addr - base;
func = disp;
unassert(func && func == disp);
} else {
func = 0;
}
return func;
}
bool CanJitForImmediateEffect(void) {
return atomic_load_explicit(&g_jit.prot, memory_order_relaxed) & PROT_EXEC;
}
static u8 *AllocateJitMemory(long *state) {
long i, brk;
uintptr_t p;
brk = *state;
p = (uintptr_t)g_code;
i = ROUNDUP(p + brk, FLAG_pagesize) - p;
if (i + kJitBlockSize > kJitMemorySize) {
return 0;
}
*state = i + kJitBlockSize;
return g_code + i;
}
static int MakeJitJump(u8 buf[5], uintptr_t pc, uintptr_t addr) {
int n;
intptr_t disp;
#if defined(__x86_64__)
disp = addr - (pc + 5);
unassert(kAmdDispMin <= disp && disp <= kAmdDispMax);
buf[0] = kAmdJmp;
Write32(buf + 1, disp & kAmdDispMask);
n = 5;
#elif defined(__aarch64__)
disp = addr - pc;
disp >>= 2;
unassert(kArmDispMin <= disp && disp <= kArmDispMax);
Write32(buf, kArmJmp | (disp & kArmDispMask));
n = 4;
#endif
return n;
}
// Obtains JitBlock from global pool or creates one if none exist.
static struct JitBlock *AcquireJitBlock(struct Jit *jit) {
struct Dll *e;
struct JitBlock *jb;
LOCK(&g_jit.lock);
if ((e = dll_first(g_jit.freeblocks))) {
dll_remove(&g_jit.freeblocks, e);
jb = JITBLOCK_CONTAINER(e);
unassert(g_jit.freecount > 0);
--g_jit.freecount;
} else {
jb = 0;
}
UNLOCK(&g_jit.lock);
if (jb) dll_make_last(&jit->agedblocks, &jb->aged);
JIT_LOGF("acquired jit block %p (freecount=%d)", jb, g_jit.freecount);
return jb;
}
// Frees JitBlock. The JIT block is added to a global free list, so it
// can be reclaimed if a new Jit system is created. This is intended for
// once all threads have shut down, due to exit_group() or execve().
// @assume jit->lock
static void ReleaseJitBlock(struct JitBlock *jb) {
struct Dll *e;
JIT_LOGF("released jit block %p", jb);
while ((e = dll_first(jb->staged))) {
dll_remove(&jb->staged, e);
FreeJitStage(JITSTAGE_CONTAINER(e));
}
dll_make_first(&jb->freejumps, jb->jumps);
jb->jumps = 0;
jb->start = 0;
jb->index = 0;
jb->committed = 0;
jb->wasretired = false;
jb->isprotected = false;
dll_init(&jb->aged);
LOCK(&g_jit.lock);
dll_make_first(&g_jit.freeblocks, &jb->elem);
++g_jit.freecount;
UNLOCK(&g_jit.lock);
}
// Frees JitBlock and adds it to the global free list in such a way that
// it'll take a long time before it's reused. This is intended for a JIT
// under active use that's trying to reclaim jit memory.
// @assume jit->lock
static void RetireJitBlock(struct Jit *jit, struct JitBlock *jb) {
JIT_LOGF("retiring jit block %p", jb);
unassert(!jb->isprotected);
unassert(dll_is_empty(jb->jumps));
unassert(dll_is_empty(jb->staged));
STATISTIC(++jit_blocks_retired);
dll_remove(&jit->blocks, &jb->elem);
dll_remove(&jit->agedblocks, &jb->aged);
jb->start = 0;
jb->index = 0;
jb->committed = 0;
jb->wasretired = true;
LOCK(&g_jit.lock);
dll_make_last(&g_jit.freeblocks, &jb->elem);
++g_jit.freecount;
UNLOCK(&g_jit.lock);
}
// creates new jit block and sets up its jit memory
static struct JitBlock *InitJitBlock(struct Jit *jit, long *state) {
struct JitBlock *jb;
if ((jb = NewJitBlock())) {
if (!(jb->addr = AllocateJitMemory(state))) {
FreeJitBlock(jb);
jb = 0;
}
}
return jb;
}
static void LockJit(struct Jit *jit) {
if (jit->threaded) {
LOCK(&jit->lock);
}
}
static void UnlockJit(struct Jit *jit) {
if (jit->threaded) {
UNLOCK(&jit->lock);
}
}
/**
* Initializes memory object for Just-In-Time (JIT) threader.
*
* The `jit` struct itself is owned by the caller. Internal memory
* associated with this object should be reclaimed later by calling
* DestroyJit().
*
* @return 0 on success
*/
int InitJit(struct Jit *jit, uintptr_t opt_staging_function) {
long brk;
unsigned n;
struct JitBlock *jb;
_Atomic(int) *funcs;
_Atomic(uintptr_t) *virts;
_Static_assert(kJitAlign >= 1, "");
_Static_assert(kJitBlockSize >= 4096, "");
_Static_assert(kJitInitialHooks >= 2, "");
unassert(FLAG_pagesize >= 4096);
unassert(kJitBlockSize >= FLAG_pagesize);
unassert(!(kJitBlockSize % FLAG_pagesize));
memset(jit, 0, sizeof(*jit));
InitEdges(&jit->edges);
InitEdges(&jit->redges);
jit->staging = EncodeJitFunc(opt_staging_function);
unassert(!pthread_mutex_init(&jit->lock, 0));
jit->hooks.n = n = RoundupTwoPow(kJitInitialHooks);
unassert(virts = (_Atomic(uintptr_t) *)Calloc(n, sizeof(*virts)));
unassert(funcs = (_Atomic(int) *)Calloc(n, sizeof(*funcs)));
atomic_store_explicit(&jit->hooks.virts, virts, memory_order_relaxed);
atomic_store_explicit(&jit->hooks.funcs, funcs, memory_order_relaxed);
for (brk = 0; (jb = InitJitBlock(jit, &brk));) {
dll_make_last(&g_jit.freeblocks, &jb->elem);
++g_jit.freecount;
}
JIT_LOGF("initialized jit %p", jit);
return 0;
}
/**
* Destroys initialized JIT object.
*
* Passing a value not previously initialized by InitJit() is undefined.
*
* @return 0 on success
*/
int DestroyJit(struct Jit *jit) {
struct Dll *e, *e2;
LockJit(jit);
JIT_LOGF("destroying jit %p", jit);
for (e = dll_first(jit->freeds.p); e; e = e2) {
e2 = dll_next(jit->freeds.p, e);
FreeJitFreed(JITFREED_CONTAINER(e));
}
while ((e = dll_first(jit->blocks))) {
dll_remove(&jit->blocks, e);
ReleaseJitBlock(JITBLOCK_CONTAINER(e));
}
dll_make_first(&jit->freejumps, jit->jumps);
for (e = dll_first(jit->freejumps); e; e = e2) {
e2 = dll_next(jit->freejumps, e);
FreeJitJump(JITJUMP_CONTAINER(e));
}
for (e = dll_first(jit->pages); e; e = e2) {
e2 = dll_next(jit->pages, e);
FreeJitPage(JITPAGE_CONTAINER(e));
}
UnlockJit(jit);
unassert(!pthread_mutex_destroy(&jit->lock));
DestroyEdges(&jit->redges);
DestroyEdges(&jit->edges);
Free(jit->hooks.funcs);
Free(jit->hooks.virts);
return 0;
}
/**
* Releases global JIT resources at shutdown.
*/
int ShutdownJit(void) {
struct Dll *e;
JIT_LOGF("shutting down jit");
while ((e = dll_first(g_jit.freeblocks))) {
dll_remove(&g_jit.freeblocks, e);
FreeJitBlock(JITBLOCK_CONTAINER(e));
--g_jit.freecount;
}
unassert(!g_jit.freecount);
return 0;
}
/**
* Disables Just-In-Time threader.
*/
int DisableJit(struct Jit *jit) {
atomic_store_explicit(&jit->disabled, true, memory_order_release);
return 0;
}
/**
* Enables Just-In-Time threader.
*/
int EnableJit(struct Jit *jit) {
atomic_store_explicit(&jit->disabled, false, memory_order_release);
return 0;
}
/**
* Fixes the memory protection for existing Just-In-Time code blocks.
*/
int FixJitProtection(struct Jit *jit) {
int prot;
struct Dll *e;
LockJit(jit);
prot = atomic_load_explicit(&g_jit.prot, memory_order_relaxed);
for (e = dll_first(jit->blocks); e; e = dll_next(jit->blocks, e)) {
unassert(
!Mprotect(JITBLOCK_CONTAINER(e)->addr, kJitBlockSize, prot, "jit"));
}
UnlockJit(jit);
return 0;
}
// @assume jit->lock
static struct JitPage *GetJitPage(struct Jit *jit, i64 addr) {
i64 page;
bool lru;
struct Dll *e;
struct JitPage *jp;
lru = false;
page = addr & -4096;
for (e = dll_first(jit->pages); e; e = dll_next(jit->pages, e)) {
jp = JITPAGE_CONTAINER(e);
if (jp->page == page) {
if (!lru) {
STATISTIC(++jit_pages_hits_1);
} else {
STATISTIC(++jit_pages_hits_2);
dll_remove(&jit->pages, e);
dll_make_first(&jit->pages, e);
}
return jp;
}
lru = true;
}
return 0;
}
// @assume jit->lock
static struct JitPage *GetOrCreateJitPage(struct Jit *jit, i64 addr) {
i64 page;
struct JitPage *jp;
page = addr & -4096;
if (!(jp = GetJitPage(jit, page))) {
if ((jp = NewJitPage())) {
dll_make_first(&jit->pages, &jp->elem);
jp->page = page;
}
}
return jp;
}
// adds heap memory to freelist
// this is intended for synchronization cooloff
// @assume jit->lock
static void RetireJitHeap(struct Jit *jit, void *data, size_t size) {
struct Dll *e;
struct JitFreed *jf = 0;
if (!data) return;
if (!jit->threaded) {
Free(data);
return;
}
if ((e = dll_first(jit->freeds.f))) {
dll_remove(&jit->freeds.f, e);
jf = JITFREED_CONTAINER(e);
} else if (!(jf = NewJitFreed())) {
return; // we can't free data so just leak it
}
jf->data = data;
jf->size = size;
dll_make_last(&jit->freeds.p, &jf->elem);
++jit->freeds.n;
}
// same as calloc, but pilfers old retired heap memory from freelist
// @assume jit->lock
static void *GetJitHeap(struct Jit *jit, size_t count, size_t elsize) {
u64 size;
void *res = 0;
struct Dll *e;
struct JitFreed *jf;
if (ckd_mul(&size, count, elsize)) return 0;
if (jit->freeds.n > kJitRetireQueue) {
for (e = dll_first(jit->freeds.p); e; e = dll_next(jit->freeds.p, e)) {
dll_remove(&jit->freeds.p, e);
jf = JITFREED_CONTAINER(e);
if (jf->size >= size) {
res = jf->data;
dll_make_first(&jit->freeds.f, e);
break;
}
}
}
if (res) {
memset(res, 0, size);
} else {
res = Calloc(1, size);
}
return res;
}
// @assume jit->lock
static unsigned RehashJitHooks(struct Jit *jit) {
int func;
uintptr_t key, virt;
unsigned i, i2, n1, n2, used, hash, spot, step, kgen;
_Atomic(int) *funcs, *funcs2;
_Atomic(uintptr_t) *virts, *virts2;
virts = atomic_load_explicit(&jit->hooks.virts, memory_order_relaxed);
funcs = atomic_load_explicit(&jit->hooks.funcs, memory_order_relaxed);
// grow allocation unless this rehash is due to many deleted values
n1 = atomic_load_explicit(&jit->hooks.n, memory_order_relaxed);
unassert(n1 > 1 && IS2POW(n1));
for (used = i = 0; i < n1; ++i) {
used += !!atomic_load_explicit(funcs + i, memory_order_relaxed);
}
n2 = n1 << (used > (n1 >> 2));
JIT_LOGF("rehashing jit hooks %u -> %u", n1, n2);
// allocate an entirely new hash table
if (!(virts2 = (_Atomic(uintptr_t) *)GetJitHeap(jit, n2, sizeof(*virts2))) ||
!(funcs2 = (_Atomic(int) *)GetJitHeap(jit, n2, sizeof(*funcs2)))) {
RetireJitHeap(jit, virts2, n2 * sizeof(*virts2));
return 0;
}
// copy entries over to new hash table, removing deleted entries
for (i2 = i = 0; i < n1; ++i) {
virt = atomic_load_explicit(virts + i, memory_order_relaxed);
func = atomic_load_explicit(funcs + i, memory_order_relaxed);
if (virt && func) {
spot = 0;
step = 0;
hash = HASH(virt);
do {
spot = (hash + step * ((step + 1) >> 1)) & (n2 - 1);
key = atomic_load_explicit(virts2 + spot, memory_order_relaxed);
unassert(key != virt);
++step;
} while (key);
atomic_store_explicit(virts2 + spot, virt, memory_order_relaxed);
atomic_store_explicit(funcs2 + spot, func, memory_order_relaxed);
++i2;
}
}
// update the hash table pointers for the lockless reader
kgen = BeginUpdate(&jit->keygen);
atomic_store_explicit(&jit->hooks.virts, virts2, memory_order_release);
atomic_store_explicit(&jit->hooks.funcs, funcs2, memory_order_relaxed);