asmkit-rs 0.7.3

Portable assembler toolkit for encoding x86/x64, AArch64, and RISC-V
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
/* Copyright (c) 2008-2024 The AsmJit Authors

   This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software.

   Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:

   The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
   Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
   This notice may not be removed or altered from any source distribution.

*/

use crate::AsmError;
use crate::util::virtual_memory::{
    self, DualMapping, MemoryFlags, alloc, alloc_dual_mapping, flush_instruction_cache, release,
    release_dual_mapping,
};
use crate::util::{
    align_down, align_up, bit_vector_clear, bit_vector_fill, bit_vector_get_bit,
    bit_vector_index_of, bit_vector_set_bit,
};
use alloc::vec::Vec;
use core::cell::{Cell, UnsafeCell};
use core::mem::size_of;
use core::ops::Range;
use core::ptr::null_mut;

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(u32)]
/// A policy that can be used with `reset()` functions.
pub enum ResetPolicy {
    /// Soft reset, does not deeallocate memory (default).
    Soft = 0,

    /// Hard reset, releases all memory used, if any.
    Hard = 1,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct JitAllocatorOptions {
    /// Enables the use of an anonymous memory-mapped memory that is mapped into two buffers having a different pointer.
    /// The first buffer has read and execute permissions and the second buffer has read+write permissions.
    ///
    /// See the internal `alloc_dual_mapping` implementation for details about this feature.
    ///
    /// ## Remarks
    ///
    /// Dual mapping would be automatically turned on by [JitAllocator] in case of hardened runtime that
    /// enforces `W^X` policy, so specifying this flag is essentually forcing to use dual mapped pages even when RWX
    /// pages can be allocated and dual mapping is not necessary.
    pub use_dual_mapping: bool,
    /// Enables the use of multiple pools with increasing granularity instead of a single pool. This flag would enable
    /// 3 internal pools in total having 64, 128, and 256 bytes granularity.
    ///
    /// This feature is only recommended for users that generate a lot of code and would like to minimize the overhead
    /// of `JitAllocator` itself by having blocks of different allocation granularities. Using this feature only for
    /// few allocations won't pay off as the allocator may need to create more blocks initially before it can take the
    /// advantage of variable block granularity.
    pub use_multiple_pools: bool,
    /// Always fill reserved memory by a fill-pattern.
    ///
    /// Causes a new block to be cleared by the fill pattern and freshly released memory to be cleared before making
    /// it ready for another use.
    pub fill_unused_memory: bool,
    /// When this flag is set the allocator would immediately release unused blocks during `release()` or `reset()`.
    /// When this flag is not set the allocator would keep one empty block in each pool to prevent excessive virtual
    /// memory allocations and deallocations in border cases, which involve constantly allocating and deallocating a
    /// single block caused by repetitive calling `alloc()` and `release()` when the allocator has either no blocks
    /// or have all blocks fully occupied.
    pub immediate_release: bool,
    pub custom_fill_pattern: Option<u32>,

    pub block_size: u32,
    pub granularity: u32,
}

impl Default for JitAllocatorOptions {
    fn default() -> Self {
        Self {
            use_dual_mapping: true,
            use_multiple_pools: true,
            fill_unused_memory: true,
            immediate_release: false,
            custom_fill_pattern: None,
            block_size: 0,
            granularity: 0,
        }
    }
}

#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
const DEFAULT_FILL_PATTERN: u32 = 0xCCCCCCCC; // int3
#[cfg(not(any(target_arch = "x86", target_arch = "x86_64")))]
const DEFAULT_FILL_PATTERN: u32 = 0x0; // int3

/// Number of pools to use when `JitAllocatorOptions::use_multiple_pools` is set.
///
/// Each pool increases granularity twice to make memory management more
/// efficient. Ideal number of pools appears to be 3 to 4 as it distributes
/// small and large functions properly.
const MULTI_POOL_COUNT: usize = 3;

/// Minimum granularity (and the default granularity for pool #0).
const MIN_GRANULARITY: usize = 64;

/// Maximum block size (32MB).
const MAX_BLOCK_SIZE: usize = 32 * 1024 * 1024;

struct BitVectorRangeIterator<'a, const B: u32> {
    slice: &'a [u32],
    idx: usize,
    end: usize,
    bit_word: u32,
}

const BIT_WORD_SIZE: usize = core::mem::size_of::<u32>() * 8;

impl<'a, const B: u32> BitVectorRangeIterator<'a, B> {
    const XOR_MASK: u32 = if B == 0 { u32::MAX } else { 0 };

    fn from_slice_and_nbitwords(data: &'a [u32], num_bit_words: usize) -> Self {
        Self::new(data, num_bit_words, 0, num_bit_words * BIT_WORD_SIZE)
    }

    fn new(data: &'a [u32], _num_bit_words: usize, start: usize, end: usize) -> Self {
        let idx = align_down(start, BIT_WORD_SIZE);
        let slice = &data[idx / BIT_WORD_SIZE..];

        let mut bit_word = 0;

        if idx < end {
            bit_word =
                (slice[0] ^ Self::XOR_MASK) & (u32::MAX << (start as u32 % BIT_WORD_SIZE as u32));
        }

        Self {
            slice,
            idx,
            end,
            bit_word,
        }
    }

    fn next_range(&mut self, range_hint: u32) -> Option<Range<u32>> {
        while self.bit_word == 0 {
            self.idx += BIT_WORD_SIZE;

            if self.idx >= self.end {
                return None;
            }

            self.slice = &self.slice[1..];
            self.bit_word = self.slice[0] ^ Self::XOR_MASK;
        }

        let i = self.bit_word.trailing_zeros();
        let start = self.idx as u32 + i;
        self.bit_word = !(self.bit_word ^ !(u32::MAX << i));
        let mut end;
        if self.bit_word == 0 {
            end = (self.idx as u32 + BIT_WORD_SIZE as u32).min(self.end as _);

            while end.wrapping_sub(start) < range_hint {
                self.idx += BIT_WORD_SIZE;

                if self.idx >= self.end {
                    break;
                }

                self.slice = &self.slice[1..];
                self.bit_word = self.slice[0] ^ Self::XOR_MASK;

                if self.bit_word != u32::MAX {
                    let j = self.bit_word.trailing_zeros();
                    end = (self.idx as u32 + j).min(self.end as _);
                    self.bit_word = !(self.bit_word ^ !(u32::MAX << j));
                    break;
                }

                end = (self.idx as u32 + BIT_WORD_SIZE as u32).min(self.end as _);
                self.bit_word = 0;
                continue;
            }

            Some(start..end)
        } else {
            let j = self.bit_word.trailing_zeros();
            end = (self.idx as u32 + j).min(self.end as _);

            self.bit_word = !(self.bit_word ^ !(u32::MAX << j));

            Some(start..end)
        }
    }
}

impl<'a> Iterator for BitVectorRangeIterator<'a, 0> {
    type Item = Range<u32>;

    fn next(&mut self) -> Option<Self::Item> {
        self.next_range(u32::MAX)
    }
}

use intrusive_collections::{KeyAdapter, UnsafeRef};
use intrusive_collections::{intrusive_adapter, rbtree::*};

struct JitAllocatorBlock {
    node: Link,
    list_node: intrusive_collections::LinkedListLink,

    /// Link to the pool that owns this block.
    pool: *mut JitAllocatorPool,
    /// Virtual memory mapping - either single mapping (both pointers equal) or
    /// dual mapping, where one pointer is Read+Execute and the second Read+Write.
    mapping: DualMapping,
    /// Virtual memory size (block size) [bytes].
    block_size: usize,

    flags: Cell<u32>,
    area_size: Cell<u32>,
    area_used: Cell<u32>,
    largest_unused_area: Cell<u32>,
    search_start: Cell<u32>,
    search_end: Cell<u32>,

    used_bitvector: UnsafeCell<alloc::vec::Vec<u32>>,
    stop_bitvector: UnsafeCell<alloc::vec::Vec<u32>>,
}

impl JitAllocatorBlock {
    const FLAG_EMPTY: u32 = 0x00000001;
    const FLAG_DIRTY: u32 = 0x00000002;
    const FLAG_DUAL_MAPPED: u32 = 0x00000004;

    fn pool(&self) -> *mut JitAllocatorPool {
        self.pool
    }

    fn rx_ptr(&self) -> *const u8 {
        self.mapping.rx
    }

    fn rw_ptr(&self) -> *mut u8 {
        self.mapping.rw
    }

    fn flags(&self) -> u32 {
        self.flags.get()
    }

    fn add_flags(&self, flags: u32) {
        self.flags.set(self.flags() | flags);
    }

    fn clear_flags(&self, flags: u32) {
        self.flags.set(self.flags() & !flags);
    }

    fn is_dirty(&self) -> bool {
        (self.flags() & Self::FLAG_DIRTY) != 0
    }

    fn block_size(&self) -> usize {
        self.block_size
    }

    fn area_used(&self) -> u32 {
        self.area_used.get()
    }

    fn area_size(&self) -> u32 {
        self.area_size.get()
    }

    fn largest_unused_area(&self) -> u32 {
        self.largest_unused_area.get()
    }

    fn search_start(&self) -> u32 {
        self.search_start.get()
    }

    fn search_end(&self) -> u32 {
        self.search_end.get()
    }

    fn used_bitvector(&self) -> &alloc::vec::Vec<u32> {
        // SAFETY: `JitAllocatorBlock` is only reachable through
        // `JitAllocator`, which is `!Send`/`!Sync` (it holds raw pointers).
        // Every caller mutates bitvectors only while holding `&mut
        // JitAllocator`, and never holds a shared reference to the same vector
        // at the same time.
        unsafe { &*self.used_bitvector.get() }
    }

    fn stop_bitvector(&self) -> &alloc::vec::Vec<u32> {
        // SAFETY: same invariant as `used_bitvector`: exclusive access
        // through `&mut JitAllocator`, and no aliasing shared borrow at the
        // call site.
        unsafe { &*self.stop_bitvector.get() }
    }

    #[allow(clippy::mut_from_ref)]
    fn used_bitvector_mut(&self) -> &mut alloc::vec::Vec<u32> {
        // SAFETY: the block is owned by a `JitAllocator` that is only
        // mutated through `&mut JitAllocator`, and this module never creates
        // a live `&`/`&mut` pair to the same vector: `mark_*` callers use one
        // bitvector at a time and drop the borrow before the next.
        unsafe { &mut *self.used_bitvector.get() }
    }

    #[allow(clippy::mut_from_ref)]
    fn stop_bitvector_mut(&self) -> &mut alloc::vec::Vec<u32> {
        // SAFETY: same exclusive-access invariant as `used_bitvector_mut`.
        unsafe { &mut *self.stop_bitvector.get() }
    }

    fn area_available(&self) -> u32 {
        self.area_size() - self.area_used()
    }

    fn mark_allocated_area(&self, allocated_area_start: u32, allocated_area_end: u32) {
        let allocated_area_size = allocated_area_end - allocated_area_start;

        bit_vector_fill(
            self.used_bitvector_mut(),
            allocated_area_start as _,
            allocated_area_size as _,
        );
        bit_vector_set_bit(
            self.stop_bitvector_mut(),
            allocated_area_end as usize - 1,
            true,
        );

        // SAFETY: `self.pool` is assigned in `new_block` before the block is
        // published to any list/tree and is never changed afterwards. The pool
        // is owned by the `JitAllocator` that owns this block, and freed
        // only after every block is removed in `Drop`, so it is live here.
        unsafe {
            (*self.pool).total_area_used += allocated_area_size as usize;
        }

        self.area_used.set(self.area_used() + allocated_area_size);

        if self.area_available() == 0 {
            self.search_start.set(self.area_size());
            self.search_end.set(0);
            self.largest_unused_area.set(0);
            self.clear_flags(Self::FLAG_DIRTY);
        } else {
            if self.search_start.get() == allocated_area_start {
                self.search_start.set(allocated_area_end as _);
            }

            if self.search_end.get() == allocated_area_end {
                self.search_end.set(allocated_area_start as _);
            }

            self.add_flags(Self::FLAG_DIRTY);
        }
    }
    fn mark_released_area(&self, released_area_start: u32, released_area_end: u32) {
        let released_area_size = released_area_end - released_area_start;

        // SAFETY: same invariant as `mark_allocated_area`: `self.pool` is live
        // and owned by the allocator state that owns this block, and all
        // mutations are serialized through `&mut JitAllocator`.
        unsafe {
            (*self.pool).total_area_used -= released_area_size as usize;
        }

        self.area_used.set(self.area_used() - released_area_size);
        self.search_start
            .set(self.search_start.get().min(released_area_start));
        self.search_end
            .set(self.search_end.get().max(released_area_end));

        bit_vector_clear(
            self.used_bitvector_mut(),
            released_area_start as _,
            released_area_size as _,
        );
        bit_vector_set_bit(
            self.stop_bitvector_mut(),
            released_area_end as usize - 1,
            false,
        );

        if self.area_used() == 0 {
            self.search_start.set(0);
            self.search_end.set(self.area_size());
            self.largest_unused_area.set(self.area_size());
            self.add_flags(Self::FLAG_EMPTY);
            self.clear_flags(Self::FLAG_DIRTY);
        } else {
            self.add_flags(Self::FLAG_DIRTY);
        }
    }

    fn mark_shrunk_area(&self, shrunk_area_start: u32, shrunk_area_end: u32) {
        let shrunk_area_size = shrunk_area_end - shrunk_area_start;

        // Shrunk area cannot start at zero as it would mean that we have shrunk the first
        // block to zero bytes, which is not allowed as such block must be released instead.
        assert!(shrunk_area_start != 0);
        assert!(shrunk_area_end <= self.area_size());

        // SAFETY: same invariant as `mark_allocated_area`: `self.pool` is live
        // and owned by the allocator state that owns this block, and all
        // mutations are serialized through `&mut JitAllocator`.
        unsafe {
            (*self.pool).total_area_used -= shrunk_area_size as usize;
        }

        self.area_used.set(self.area_used() - shrunk_area_size);
        self.search_start
            .set(self.search_start.get().min(shrunk_area_start));
        self.search_end
            .set(self.search_end.get().max(shrunk_area_end));

        bit_vector_clear(
            self.used_bitvector_mut(),
            shrunk_area_start as _,
            shrunk_area_size as _,
        );
        bit_vector_set_bit(
            self.stop_bitvector_mut(),
            shrunk_area_end as usize - 1,
            false,
        );
        bit_vector_set_bit(
            self.stop_bitvector_mut(),
            shrunk_area_start as usize - 1,
            true,
        );

        self.add_flags(Self::FLAG_DIRTY);
    }
}

impl PartialOrd for JitAllocatorBlock {
    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for JitAllocatorBlock {
    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
        self.rx_ptr().cmp(&other.rx_ptr())
    }
}

impl PartialEq for JitAllocatorBlock {
    fn eq(&self, other: &Self) -> bool {
        self.rx_ptr() == other.rx_ptr()
    }
}

impl Eq for JitAllocatorBlock {}
use intrusive_collections::linked_list::LinkedList;
intrusive_adapter!(JitAllocatorBlockAdapter = UnsafeRef<JitAllocatorBlock> : JitAllocatorBlock { node: Link });
intrusive_adapter!(BlockListAdapter = UnsafeRef<JitAllocatorBlock> : JitAllocatorBlock { list_node: intrusive_collections::LinkedListLink });

struct BlockKey {
    rxptr: *const u8,
    block_size: u32,
}

impl PartialEq for BlockKey {
    fn eq(&self, other: &Self) -> bool {
        self.rxptr == other.rxptr
    }
}

impl Eq for BlockKey {}

impl PartialOrd for BlockKey {
    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for BlockKey {
    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
        let addr_off = other.rxptr as usize + other.block_size as usize;

        if addr_off <= self.rxptr as usize {
            core::cmp::Ordering::Less
        } else if other.rxptr > self.rxptr {
            core::cmp::Ordering::Greater
        } else {
            core::cmp::Ordering::Equal
        }
    }
}

impl<'a> KeyAdapter<'a> for JitAllocatorBlockAdapter {
    type Key = BlockKey;

    fn get_key(
        &self,
        value: &'a <Self::PointerOps as intrusive_collections::PointerOps>::Value,
    ) -> Self::Key {
        BlockKey {
            rxptr: value.rx_ptr(),
            block_size: value.block_size as _,
        }
    }
}

struct JitAllocatorPool {
    blocks: LinkedList<BlockListAdapter>,
    cursor: *mut JitAllocatorBlock,

    block_count: u32,
    granularity: u16,
    granularity_log2: u8,
    empty_block_count: u8,
    total_area_size: usize,
    total_area_used: usize,
    total_overhead_bytes: usize,
}

impl JitAllocatorPool {
    fn new(granularity: u32) -> Self {
        let granularity_log2 = granularity.trailing_zeros() as u8;
        let granularity = granularity as u16;

        Self {
            blocks: LinkedList::new(BlockListAdapter::new()),
            cursor: core::ptr::null_mut(),
            block_count: 0,
            granularity,
            granularity_log2,
            empty_block_count: 0,
            total_area_size: 0,
            total_area_used: 0,
            total_overhead_bytes: 0,
        }
    }

    fn reset(&mut self) {
        self.blocks.clear();
        self.cursor = core::ptr::null_mut();
        self.block_count = 0;
        self.empty_block_count = 0;
        self.total_area_size = 0;
        self.total_area_used = 0;
        self.total_overhead_bytes = 0;
    }

    fn byte_size_from_area_size(&self, area_size: u32) -> usize {
        area_size as usize * self.granularity as usize
    }

    fn area_size_from_byte_size(&self, byte_size: usize) -> u32 {
        ((byte_size + self.granularity as usize - 1) >> self.granularity_log2) as u32
    }

    fn bit_word_count_from_area_size(&self, area_size: u32) -> usize {
        align_up(area_size as _, 32) / 32
    }
}
use alloc::boxed::Box;

/// A simple implementation of memory manager that uses [virtual_memory].
/// functions to manage virtual memory for JIT compiled code.
///
/// Implementation notes:
///
/// - Granularity of allocated blocks is different than granularity for a typical C malloc. In addition, the allocator
///   can use several memory pools having a different granularity to minimize the maintenance overhead. Multiple pools
///   feature requires `use_multiple_pools` flag to be set.
///
/// - The allocator doesn't store any information in executable memory, instead, the implementation uses two
///   bit-vectors to manage allocated memory of each allocator-block. The first bit-vector called 'used' is used to
///   track used memory (where each bit represents memory size defined by granularity) and the second bit vector called
///   'stop' is used as a sentinel to mark where the allocated area ends.
///
/// - Internally, the allocator also uses RB tree to keep track of all blocks across all pools. Each inserted block is
///   added to the tree so it can be matched fast during `release()` and `shrink()`.
///
/// Like asmjit's `JitAllocator`, this is a low-level interface: [`Span`]s are plain handles that do not own
/// their memory. Allocations live until they are passed to [`JitAllocator::release`], or until the allocator
/// is reset or dropped, and it is up to the caller not to use a span past that point.
pub struct JitAllocator {
    options: JitAllocatorOptions,
    block_size: usize,
    granulariy: usize,
    fill_pattern: u32,

    allocation_count: usize,
    tree: RBTree<JitAllocatorBlockAdapter>,
    pools: Box<[*mut JitAllocatorPool]>,
}

impl JitAllocator {
    /// Creates a new JIT allocator.
    pub fn new(mut params: JitAllocatorOptions) -> Box<Self> {
        let vm_info = virtual_memory::info();

        // Apple platforms refuse executable `MAP_SHARED` mappings, so dual
        // mapping fails there. Use a single `MAP_JIT` mapping instead and toggle
        // write access with `pthread_jit_write_protect_np`, as asmjit does.
        #[cfg(not(windows))]
        if virtual_memory::has_map_jit_support() {
            params.use_dual_mapping = false;
        }

        let mut block_size = params.block_size;
        let mut granularity = params.granularity;

        let mut pool_count = 1;

        if params.use_multiple_pools {
            pool_count = MULTI_POOL_COUNT;
        }

        if !(64 * 1024..=MAX_BLOCK_SIZE as u32).contains(&block_size)
            || !block_size.is_power_of_two()
        {
            block_size = vm_info.page_granularity as _;
        }

        if !(64..=256).contains(&granularity) || !granularity.is_power_of_two() {
            granularity = MIN_GRANULARITY as _;
        }

        let fill_pattern = params.custom_fill_pattern.unwrap_or(DEFAULT_FILL_PATTERN);

        let mut pools = Vec::with_capacity(pool_count);

        for _ in 0..pool_count {
            pools.push(Box::into_raw(Box::new(JitAllocatorPool::new(granularity))));
        }

        Box::new(Self {
            options: params,
            block_size: block_size as _,
            granulariy: granularity as _,
            fill_pattern,
            allocation_count: 0,
            tree: RBTree::new(JitAllocatorBlockAdapter::new()),
            pools: pools.into_boxed_slice(),
        })
    }

    fn size_to_pool_id(&self, size: usize) -> usize {
        let mut pool_id = self.pools.len() - 1;
        let mut granularity = self.granulariy << pool_id;

        while pool_id != 0 {
            if align_up(size, granularity) == size {
                break;
            }

            pool_id -= 1;
            granularity >>= 1;
        }

        pool_id
    }

    fn bitvector_size_to_byte_size(area_size: u32) -> usize {
        (area_size as usize).div_ceil(32) * size_of::<u32>()
    }

    fn calculate_ideal_block_size(
        &self,
        pool: *mut JitAllocatorPool,
        allocation_size: usize,
    ) -> usize {
        // SAFETY: callers pass a pointer taken from `self.pools`, which owns the
        // pool for the lifetime of the state, and call this while holding the
        // allocator's exclusive borrow.
        unsafe {
            let last = (*pool).blocks.back();

            let mut block_size = match last.get() {
                Some(block) => block.block_size(),
                None => self.block_size,
            };

            if block_size < MAX_BLOCK_SIZE {
                block_size *= 2;
            }

            if allocation_size > block_size {
                block_size = align_up(allocation_size, block_size);

                // overflow
                if block_size < allocation_size {
                    return 0;
                }
            }

            block_size
        }
    }

    /// Creates a new block owned by `pool` and maps `block_size` bytes for it.
    ///
    /// # Safety
    ///
    /// `pool` must be a live pool pointer owned by the same `JitAllocator`
    /// as `self`, and `self` must hold the state's exclusive borrow. The
    /// returned `Box` owns the only pointer to the block until the caller
    /// publishes it with [`Self::insert_block`].
    unsafe fn new_block(
        &mut self,
        pool: *mut JitAllocatorPool,
        block_size: usize,
    ) -> Result<Box<JitAllocatorBlock>, AsmError> {
        // SAFETY: `pool` is live per the function contract; the area size is
        // computed from the block size and the pool's power-of-two granularity
        // (validated in `JitAllocator::new`), no arithmetic can overflow
        // because `block_size` is validated to be at most `MAX_BLOCK_SIZE`.
        unsafe {
            let area_size =
                (block_size + (*pool).granularity as usize - 1) >> (*pool).granularity_log2;
            let num_bit_words = area_size.div_ceil(32);

            let mut block = Box::new(JitAllocatorBlock {
                node: Link::new(),
                list_node: intrusive_collections::LinkedListLink::new(),
                pool,
                mapping: DualMapping {
                    rx: null_mut(),
                    rw: null_mut(),
                },
                block_size: block_size as _,
                flags: Cell::new(0),
                area_size: Cell::new(0),
                area_used: Cell::new(0),
                largest_unused_area: Cell::new(area_size as _),
                search_end: Cell::new(area_size as _),
                search_start: Cell::new(0),
                used_bitvector: UnsafeCell::new(alloc::vec![0; num_bit_words]),
                stop_bitvector: UnsafeCell::new(alloc::vec![0; num_bit_words]),
            });
            let mut block_flags = 0;
            let virt_mem = if self.options.use_dual_mapping {
                block_flags |= JitAllocatorBlock::FLAG_DUAL_MAPPED;
                alloc_dual_mapping(block_size, MemoryFlags::ACCESS_RWX.into())?
            } else {
                let rx = alloc(block_size, MemoryFlags::ACCESS_RWX.into())?;
                DualMapping { rx, rw: rx }
            };

            if self.options.fill_unused_memory {
                virtual_memory::with_jit_write_access(|| {
                    fill_pattern(virt_mem.rw, self.fill_pattern, block_size);
                });
                let _ = flush_instruction_cache(virt_mem.rx, block_size);
            }

            block.area_size.set(area_size as _);
            block.mapping = virt_mem;
            block.flags.set(block_flags);
            Ok(block)
        }
    }

    /// Destroys `block`, unmapping its memory.
    ///
    /// # Safety
    ///
    /// `block` must be a pointer previously returned by [`Self::new_block`] (or
    /// `Box::into_raw` of such a block) that has already been removed from the
    /// RB tree and its pool's list, and must not be used afterwards.
    unsafe fn delete_block(&mut self, block: *mut JitAllocatorBlock) {
        // SAFETY: per the contract, `block` is an owned `Box` allocation that is
        // no longer reachable from any tree/list, so reclaiming it with
        // `Box::from_raw` is the unique owner. The mapping pointers stored in
        // the block were produced by `alloc`/`alloc_dual_mapping` and are
        // released exactly once here, matching the mapping kind recorded in
        // `FLAG_DUAL_MAPPED`.
        unsafe {
            let mut block = Box::from_raw(block);
            if (block.flags() & JitAllocatorBlock::FLAG_DUAL_MAPPED) != 0 {
                let _ = release_dual_mapping(&mut block.mapping, block.block_size);
            } else {
                let _ = release(block.mapping.rx as _, block.block_size);
            }

            drop(block);
        }
    }

    /// Publishes `block` into the RB tree and its pool's block list.
    ///
    /// # Safety
    ///
    /// `block` must be a live, uniquely owned pointer from [`Self::new_block`]
    /// that has not yet been inserted, and `self` must hold the state's
    /// exclusive borrow. Ownership of the pointer is transferred to the tree
    /// and list (reclaimed by [`Self::remove_block`]).
    unsafe fn insert_block(&mut self, block: *mut JitAllocatorBlock) {
        // SAFETY: per the contract `block` is a live uniquely owned allocation;
        // `b.pool()` was set by `new_block` and points at a live pool, so
        // `&mut *b.pool()` is a unique borrow. `UnsafeRef::from_raw` hands the
        // raw pointer to the tree/list, which now own it until removal.
        unsafe {
            let b = &mut *block;
            let pool = &mut *b.pool();

            if pool.cursor.is_null() {
                pool.cursor = block;
            }

            self.tree.insert(UnsafeRef::from_raw(block));
            pool.blocks.push_front(UnsafeRef::from_raw(block));

            pool.block_count += 1;
            pool.total_area_size += b.area_size() as usize;

            pool.total_overhead_bytes += size_of::<JitAllocatorBlock>()
                + Self::bitvector_size_to_byte_size(b.area_size()) * 2;
        }
    }

    /// Removes the block under `block` from the RB tree and its pool list and
    /// returns its raw pointer, transferring ownership back to the caller.
    ///
    /// # Safety
    ///
    /// `block` must be a non-null cursor positioned on a block that was
    /// published by [`Self::insert_block`], and `self` must hold the state's
    /// exclusive borrow. The returned pointer must be reclaimed exactly once,
    /// normally with [`Self::delete_block`].
    unsafe fn remove_block(
        &mut self,
        block: &mut intrusive_collections::linked_list::CursorMut<'_, BlockListAdapter>,
    ) -> *mut JitAllocatorBlock {
        // SAFETY: per the contract the cursor is positioned on a live block
        // owned by the list; the block's `pool` pointer is still valid because
        // the pool outlives all of its blocks, and all other accesses happen
        // under the state's exclusive borrow.
        unsafe {
            let b = match block.get() {
                Some(b) => b,
                None => unreachable!("remove_block is only called on a positioned cursor"),
            };
            let pool = &mut *b.pool();

            if core::ptr::eq(pool.cursor, b) {
                pool.cursor = if let Some(block) = block.peek_prev().get() {
                    block as *const _ as *mut _
                } else if let Some(block) = block.peek_next().get() {
                    block as *const _ as *mut _
                } else {
                    null_mut()
                };
            }

            if let Entry::Occupied(mut c) = self.tree.entry(&BlockKey {
                rxptr: b.rx_ptr(),
                block_size: b.block_size as _,
            }) {
                let removed = match c.remove() {
                    Some(removed) => removed,
                    None => unreachable!("an occupied tree entry always yields its block"),
                };
                assert_eq!(
                    UnsafeRef::into_raw(removed),
                    b as *const _ as *mut JitAllocatorBlock,
                    "blocks are not the same"
                );
            }
            let area_size = b.area_size();

            pool.block_count -= 1;
            pool.total_area_size -= area_size as usize;

            pool.total_overhead_bytes -=
                size_of::<JitAllocatorBlock>() + Self::bitvector_size_to_byte_size(area_size) * 2;

            match block.remove() {
                Some(removed) => UnsafeRef::into_raw(removed),
                None => unreachable!("a positioned cursor always removes its block"),
            }
        }
    }

    /// Marks a block as empty, optionally re-filling its memory with the
    /// allocator fill pattern.
    ///
    /// # Safety
    ///
    /// `block` must be a non-null cursor positioned on a live block of `self`'s
    /// tree/list, and `self` must hold the state's exclusive borrow. The block
    /// must not be in use by any allocation.
    unsafe fn wipe_out_block(
        &mut self,
        block: &mut intrusive_collections::linked_list::CursorMut<'_, BlockListAdapter>,
    ) {
        // SAFETY: per the contract the cursor is positioned on a live block; its
        // `pool` pointer stays valid for the block's lifetime, and this runs
        // under the state's exclusive borrow so the fill writes cannot race
        // with an allocation.
        unsafe {
            let b = match block.get() {
                Some(b) => b,
                None => unreachable!("wipe_out_block is only called on a positioned cursor"),
            };
            if (b.flags() & JitAllocatorBlock::FLAG_EMPTY) != 0 {
                return;
            }

            let pool = &mut *b.pool();

            let area_size = b.area_size();
            let granularity = pool.granularity;

            virtual_memory::with_jit_write_access(|| {
                if !self.options.fill_unused_memory {
                    return;
                }
                let rw_ptr = b.rw_ptr();

                let it = BitVectorRangeIterator::from_slice_and_nbitwords(
                    b.stop_bitvector(),
                    pool.bit_word_count_from_area_size(b.area_size()),
                );

                for range in it {
                    let span_ptr = rw_ptr.add(range.start as usize * granularity as usize);
                    let span_size =
                        (range.end as usize - range.start as usize) * granularity as usize;

                    let mut n = 0;
                    while n < span_size {
                        // SAFETY (inside the outer `unsafe` block): `span_ptr`
                        // points into the block's RW mapping, `n` stays below
                        // `span_size` (the span length in bytes), and the span
                        // is granularity-aligned so each 4-byte write is in
                        // bounds and `u32`-aligned.
                        *span_ptr.add(n).cast::<u32>() = self.fill_pattern;
                        n += size_of::<u32>();
                    }

                    let _ = virtual_memory::flush_instruction_cache(span_ptr, span_size);
                }
            });

            let b = match block.get() {
                Some(b) => b,
                None => unreachable!("the cursor still points at the wiped block"),
            };
            b.used_bitvector_mut().fill(0);
            b.stop_bitvector_mut().fill(0);

            b.area_used.set(0);
            b.largest_unused_area.set(area_size);
            b.search_start.set(0);
            b.search_end.set(area_size);
            b.add_flags(JitAllocatorBlock::FLAG_EMPTY);
            b.clear_flags(JitAllocatorBlock::FLAG_DIRTY);
        }
    }

    /// Resets current allocator by emptying all pools and blocks.
    ///
    /// Frees all memory is `ResetPolicy::Hard` is specified or `immediate_release` in [JitAllocatorOptions] is specific.
    ///
    /// # Safety
    ///
    /// - The caller must ensure that no code is currently executing from the memory managed by this allocator.
    /// - The caller must ensure that no references to the memory managed by this allocator are used after calling this function.
    /// - The caller must ensure that no other thread is currently accessing the memory managed by this allocator.
    pub unsafe fn reset(&mut self, reset_policy: ResetPolicy) {
        let pool_count = self.pools.len();

        for pool_id in 0..pool_count {
            // SAFETY: `self.pools` is an owned slice of heap pools that are freed
            // only in `Drop for JitAllocator` (after a final hard reset);
            // `pool_id` is in bounds. Taking `&mut` is exclusive because this
            // method has `&mut self`.
            let pool = unsafe { &mut *self.pools[pool_id] };
            let block_to_keep =
                if reset_policy != ResetPolicy::Hard && !self.options.immediate_release {
                    let mut cursor = pool.blocks.cursor();
                    cursor.move_next();
                    cursor
                        .get()
                        .map(|block| block as *const JitAllocatorBlock as *mut JitAllocatorBlock)
                } else {
                    None
                };

            // SAFETY: every block in `pool.blocks` was published by
            // `insert_block` and is uniquely owned by this list. `remove_block`
            // unlinks and returns each one, after which `delete_block` reclaims
            // it; `block_to_keep` points at a block left in the list, and the
            // caller's contract guarantees no other code or thread is using it.
            unsafe {
                let mut cursor = pool.blocks.cursor_mut();
                cursor.move_next();
                while !cursor.is_null() {
                    let block = match cursor.get() {
                        Some(block) => block as *const JitAllocatorBlock as *mut JitAllocatorBlock,
                        None => unreachable!("a non-null cursor always has a current block"),
                    };
                    if Some(block) != block_to_keep {
                        let block = self.remove_block(&mut cursor);
                        self.delete_block(block);
                    } else {
                        cursor.move_next();
                    }
                }

                if let Some(block) = block_to_keep {
                    // SAFETY: `block_to_keep` is still linked in `pool.blocks`
                    // (it was skipped above), so a cursor can be constructed
                    // from its pointer.
                    let mut cursor = pool.blocks.cursor_mut_from_ptr(&*block);
                    self.wipe_out_block(&mut cursor);
                    pool.cursor = block;
                    pool.empty_block_count = 1;
                    pool.total_area_used = 0;
                } else {
                    pool.reset();
                }
            }
        }

        self.allocation_count = 0;
    }

    /// Allocates `size` bytes in the executable memory region.
    ///
    /// The returned [`Span`] holds two pointers. One points to Read-Execute mapping and another to Read-Write
    /// mapping. All code writes *must* go to the Read-Write mapping.
    pub fn alloc(&mut self, size: usize) -> Result<Span, AsmError> {
        const NO_INDEX: u32 = u32::MAX;

        let size = align_up(size, self.granulariy);

        if size == 0 {
            return Err(AsmError::InvalidArgument);
        }

        if size > u32::MAX as usize / 2 {
            return Err(AsmError::TooLarge);
        }

        // SAFETY: `self.pools` owns live pools; `pool_id` is in bounds; every
        // block pointer reachable from the pools was produced by previous
        // `insert_block` calls under `&mut self`, so it is live.
        unsafe {
            let pool_id = self.size_to_pool_id(size);
            let pool = &mut *self.pools[pool_id];

            let mut area_index = NO_INDEX;
            let area_size = pool.area_size_from_byte_size(size);

            let mut block = pool.blocks.cursor();
            block.move_next();
            if let Some(initial) = block.get().map(|x| x as *const JitAllocatorBlock) {
                loop {
                    let b = match block.get() {
                        Some(b) => b,
                        None => unreachable!("the cursor was positioned on a block"),
                    };

                    if b.area_available() >= area_size
                        && (b.is_dirty() || b.largest_unused_area() >= area_size)
                    {
                        let mut it = BitVectorRangeIterator::<0>::new(
                            b.used_bitvector(),
                            pool.bit_word_count_from_area_size(b.area_size()),
                            b.search_start() as _,
                            b.search_end() as _,
                        );

                        let mut range_start;
                        let mut range_end = b.area_size() as usize;

                        let mut search_start = usize::MAX;
                        let mut largest_area = 0;

                        while let Some(range) = it.next_range(area_size as _) {
                            range_start = range.start as _;
                            range_end = range.end as _;

                            let range_size = range_end - range_start;

                            if range_size >= area_size as usize {
                                area_index = range_start as _;
                                break;
                            }

                            search_start = search_start.min(range_start);
                            largest_area = largest_area.max(range_size);
                        }

                        if area_index != NO_INDEX {
                            break;
                        }

                        if search_start != usize::MAX {
                            let search_end = range_end;

                            b.search_start.set(search_start as _);

                            b.search_end.set(search_end as _);
                            b.largest_unused_area.set(largest_area as _);
                            b.clear_flags(JitAllocatorBlock::FLAG_DIRTY);
                        }
                    }

                    block.move_next();

                    if block.get().map(|x| x as *const _) == Some(initial) {
                        break;
                    }

                    if block.is_null() {
                        break;
                    }
                }
            }

            let mut block = block.get();

            if area_index == NO_INDEX {
                let block_size = self.calculate_ideal_block_size(pool, size);

                {
                    let nblock = self.new_block(pool, block_size)?;

                    area_index = 0;

                    nblock.search_start.set(area_size as _);

                    nblock
                        .largest_unused_area
                        .set(nblock.area_size() - area_size);

                    let nblock = Box::into_raw(nblock);

                    self.insert_block(nblock);

                    block = Some(&*nblock);
                }
            } else {
                let b = match block {
                    Some(b) => b,
                    None => unreachable!("area_index was found in an existing block"),
                };
                if (b.flags() & JitAllocatorBlock::FLAG_EMPTY) != 0 {
                    pool.empty_block_count -= 1;
                    b.clear_flags(JitAllocatorBlock::FLAG_EMPTY);
                }
            }

            self.allocation_count += 1;

            let block = match block {
                Some(block) => block,
                None => unreachable!("a block is selected when area_index is valid"),
            };

            block.mark_allocated_area(area_index, area_index + area_size);

            let offset = pool.byte_size_from_area_size(area_index);

            // SAFETY: `offset` is the byte offset of the freshly marked area
            // inside the block, so it is within `block_size`; both `rx` and `rw`
            // point at the start of a live mapping of at least that size.
            Ok(Span {
                rx: block.rx_ptr().add(offset),
                rw: block.rw_ptr().add(offset),
                size,
                block: block as *const JitAllocatorBlock as *mut u8,
                icache_clean: true,
            })
        }
    }

    /// Releases the memory allocated by `alloc`.
    ///
    /// # Safety
    ///
    /// - `rx_ptr` must have been returned from `alloc` on this allocator.
    /// - `rx_ptr` must not have been passed to `release`/`shrink` before.
    /// - `rx_ptr` must point to the read-execute mapping returned by `alloc`,
    ///   and no pointer into the released area may be used afterwards.
    pub unsafe fn release(&mut self, rx_ptr: *const u8) -> Result<(), AsmError> {
        if rx_ptr.is_null() {
            return Err(AsmError::InvalidArgument);
        }

        let block = self.tree.find(&BlockKey {
            rxptr: rx_ptr,
            block_size: 0,
        });

        let Some(block) = block.get() else {
            return Err(AsmError::InvalidState);
        };

        // SAFETY: `block` was located in the RB tree, so it is live and owned by
        // this state; `block.pool` was set by `new_block` at the pool that owns
        // the block, which outlives it. The tree lookup places `rx_ptr` inside
        // this block, so the offset arithmetic stays inside the mapping and
        // the bitvector probes are in bounds. The fill writes `area_size`
        // bytes of the RW mapping, and the raw pointers are advanced by that
        // allocation's exact offset.
        unsafe {
            let pool = &mut *block.pool;

            let offset = rx_ptr as usize - block.rx_ptr() as usize;
            if offset % pool.granularity as usize != 0 {
                return Err(AsmError::InvalidArgument);
            }

            let area_index = (offset >> pool.granularity_log2 as usize) as u32;
            let is_allocation_start = bit_vector_get_bit(block.used_bitvector(), area_index as _)
                && (area_index == 0
                    || !bit_vector_get_bit(block.used_bitvector(), area_index as usize - 1)
                    || bit_vector_get_bit(block.stop_bitvector(), area_index as usize - 1));
            if !is_allocation_start {
                return Err(AsmError::InvalidArgument);
            }
            let area_end =
                bit_vector_index_of(block.stop_bitvector(), area_index as _, true) as u32 + 1;
            let area_size = area_end - area_index;

            self.allocation_count -= 1;

            block.mark_released_area(area_index, area_end);

            if self.options.fill_unused_memory {
                let span_ptr = block
                    .rw_ptr()
                    .add(area_index as usize * pool.granularity as usize);
                let span_size = area_size as usize * pool.granularity as usize;

                virtual_memory::with_jit_write_access(|| {
                    fill_pattern(span_ptr, self.fill_pattern, span_size);
                });
                let _ = flush_instruction_cache(
                    block
                        .rx_ptr()
                        .add(area_index as usize * pool.granularity as usize),
                    span_size,
                );
            }

            if block.area_used() == 0 {
                if pool.empty_block_count != 0 || self.options.immediate_release {
                    let mut cursor = pool.blocks.cursor_mut_from_ptr(block);
                    let block = self.remove_block(&mut cursor);

                    self.delete_block(block);
                } else {
                    pool.empty_block_count += 1;
                }
            }
        }

        Ok(())
    }
    /// Shrinks the memory allocated by `alloc` and updates `span.size()` to match.
    ///
    /// A `new_size` of zero releases the allocation.
    ///
    /// # Safety
    ///
    /// `span` must describe a live allocation returned by `alloc` on this
    /// allocator; no pointer into the released tail may be used afterwards.
    pub unsafe fn shrink(&mut self, span: &mut Span, new_size: usize) -> Result<(), AsmError> {
        let rx_ptr = span.rx;
        if rx_ptr.is_null() {
            return Err(AsmError::InvalidArgument);
        }

        if new_size == 0 {
            // SAFETY: forwarding the caller's contract unchanged.
            unsafe { self.release(rx_ptr)? };
            span.size = 0;
            return Ok(());
        }

        let Some(block) = self
            .tree
            .find(&BlockKey {
                rxptr: rx_ptr,
                block_size: 0,
            })
            .get()
        else {
            return Err(AsmError::InvalidArgument);
        };

        // SAFETY: `block` was located in the RB tree, so it is live; `block.pool`
        // points at the live owning pool. The bitvector probes are bounded by
        // the allocation start/end checks, and the fill range lies inside the
        // retained allocation's mapping, so the raw pointer arithmetic is in
        // bounds and the flush covers exactly the shrunk tail.
        unsafe {
            let pool = &mut *block.pool;
            let offset = rx_ptr as usize - block.rx_ptr() as usize;
            if offset % pool.granularity as usize != 0 {
                return Err(AsmError::InvalidArgument);
            }
            let area_start = (offset >> pool.granularity_log2 as usize) as u32;

            let is_allocation_start = bit_vector_get_bit(block.used_bitvector(), area_start as _)
                && (area_start == 0
                    || !bit_vector_get_bit(block.used_bitvector(), area_start as usize - 1)
                    || bit_vector_get_bit(block.stop_bitvector(), area_start as usize - 1));
            if !is_allocation_start {
                return Err(AsmError::InvalidArgument);
            }

            let area_end =
                bit_vector_index_of(block.stop_bitvector(), area_start as _, true) as u32 + 1;

            let area_prev_size = area_end - area_start;
            let area_shrunk_size = pool.area_size_from_byte_size(new_size);

            if area_shrunk_size > area_prev_size {
                return Err(AsmError::InvalidState);
            }

            let area_diff = area_prev_size - area_shrunk_size;

            if area_diff != 0 {
                block.mark_shrunk_area(area_start + area_shrunk_size, area_end);

                if self.options.fill_unused_memory {
                    let area_offset =
                        (area_start + area_shrunk_size) as usize * pool.granularity as usize;
                    let span_ptr = block.rw_ptr().add(area_offset);
                    let span_size = area_diff as usize * pool.granularity as usize;

                    virtual_memory::with_jit_write_access(|| {
                        fill_pattern(span_ptr, self.fill_pattern, span_size);
                    });
                    let _ = flush_instruction_cache(block.rx_ptr().add(area_offset), span_size);
                }
            }

            span.size = pool.byte_size_from_area_size(area_shrunk_size);
        }

        Ok(())
    }

    /// Takes a pointer to the start of an allocation and returns a [`Span`]
    /// describing its RX and RW mappings and size.
    pub fn query(&self, rx_ptr: *const u8) -> Result<Span, AsmError> {
        let Some(block) = self
            .tree
            .find(&BlockKey {
                rxptr: rx_ptr,
                block_size: 0,
            })
            .get()
        else {
            return Err(AsmError::InvalidArgument);
        };

        // SAFETY: `block` was located in the RB tree, so it is live; `block.pool`
        // points at its live owning pool. `rx_ptr` lies inside the block because
        // `BlockKey` ordered it there, so the offset is in bounds and the
        // bitvector probes/pointers stay inside the mapping.
        unsafe {
            let pool = &mut *block.pool;
            let offset = rx_ptr as usize - block.rx_ptr() as usize;
            if offset % pool.granularity as usize != 0 {
                return Err(AsmError::InvalidArgument);
            }

            let area_start = (offset >> pool.granularity_log2 as usize) as u32;

            let is_allocation_start = bit_vector_get_bit(block.used_bitvector(), area_start as _)
                && (area_start == 0
                    || !bit_vector_get_bit(block.used_bitvector(), area_start as usize - 1)
                    || bit_vector_get_bit(block.stop_bitvector(), area_start as usize - 1));
            if !is_allocation_start {
                return Err(AsmError::InvalidArgument);
            }

            let area_end =
                bit_vector_index_of(block.stop_bitvector(), area_start as _, true) as u32 + 1;
            let byte_offset = pool.byte_size_from_area_size(area_start);
            let byte_size = pool.byte_size_from_area_size(area_end - area_start);

            Ok(Span {
                rx: block.rx_ptr().add(byte_offset),
                rw: block.rw_ptr().add(byte_offset),
                size: byte_size,
                block: block as *const JitAllocatorBlock as *mut u8,
                icache_clean: true,
            })
        }
    }

    /// Writes through a span and synchronizes the instruction cache.
    ///
    /// Makes JIT memory writable for the duration of `write_func` (MAP_JIT
    /// platforms), then flushes the instruction cache for the whole span.
    ///
    /// # Safety
    ///
    /// `span` must describe a live allocation of this allocator,
    /// `write_func` must only write inside it and leave valid executable code
    /// there, and no thread may execute it while the closure is modifying it.
    pub unsafe fn write(
        &mut self,
        span: &mut Span,
        write_func: impl FnOnce(&mut Span),
    ) -> Result<(), AsmError> {
        if span.size == 0 {
            return Ok(());
        }

        span.icache_clean = false;
        virtual_memory::with_jit_write_access(|| write_func(span));
        // SAFETY: the caller guarantees `span` is a live mapped allocation.
        unsafe { flush_instruction_cache(span.rx, span.size)? };
        span.icache_clean = true;
        Ok(())
    }

    /// Copies `slice` into `span` at `offset` and synchronizes the written
    /// instruction-cache range.
    ///
    /// # Safety
    ///
    /// `span` must describe a live allocation of this allocator, and no thread
    /// may execute the written range while it is being modified. The range is
    /// bounds-checked against `span.size()`.
    pub unsafe fn copy_from_slice(
        &mut self,
        span: &mut Span,
        offset: usize,
        slice: &[u8],
    ) -> Result<(), AsmError> {
        let end = offset
            .checked_add(slice.len())
            .ok_or(AsmError::InvalidArgument)?;
        if end > span.size {
            return Err(AsmError::InvalidArgument);
        }
        if slice.is_empty() {
            return Ok(());
        }

        span.icache_clean = false;
        // SAFETY: the caller guarantees `span` is live and `offset..end` was
        // bounds-checked against its size, so the copy and the flush stay
        // inside its mappings.
        unsafe {
            virtual_memory::with_jit_write_access(|| {
                span.rw
                    .add(offset)
                    .copy_from_nonoverlapping(slice.as_ptr(), slice.len());
            });
            flush_instruction_cache(span.rx.add(offset), slice.len())?;
        }
        span.icache_clean = true;
        Ok(())
    }
}

impl Drop for JitAllocator {
    fn drop(&mut self) {
        // SAFETY: this is the unique owner of `self.pools`; reset removes and
        // deletes every block from every pool (guaranteed to have `&mut self`,
        // so no other user of the mappings can exist), after which each pool
        // `Box` is reclaimed exactly once. Any `Span` still held by the caller
        // dangles after this, as with asmjit.
        unsafe {
            self.reset(ResetPolicy::Hard);
            for pool in &mut self.pools {
                drop(Box::from_raw(*pool));
            }
        }
    }
}

/// Fills `size_in_bytes` of `mem` (rounded down to 4-byte units) with `pattern`.
///
/// # Safety
///
/// `mem` must be valid for writes of `size_in_bytes / 4 * 4` bytes and must be
/// aligned at least to `u32`.
#[inline]
unsafe fn fill_pattern(mem: *mut u8, pattern: u32, size_in_bytes: usize) {
    let n = size_in_bytes / 4;

    let p = mem as *mut u32;

    for i in 0..n {
        // SAFETY: `i < n`, so `p.add(i)` is within the first `n * 4` bytes, which
        // the caller guarantees are writable and aligned for `u32`.
        unsafe {
            p.add(i).write(pattern);
        }
    }
}


/// A region of executable memory returned by [`JitAllocator::alloc`].
///
/// This is a plain handle: copying or
/// dropping it does nothing to the allocation. Release it explicitly with
/// [`JitAllocator::release`], or let the allocator free it on reset or drop.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Span {
    rx: *const u8,
    rw: *mut u8,
    size: usize,
    block: *mut u8,
    icache_clean: bool,
}

impl Span {
    /// Returns a pointer having Read & Execute permissions (references executable memory).
    ///
    /// This pointer is never NULL if the allocation succeeded, it points to an executable memory.
    pub const fn rx(&self) -> *const u8 {
        self.rx
    }
    /// Returns a pointer having Read & Write permissions (references writable memory).
    ///
    /// Depending on the type of the allocation strategy this could either be:
    ///
    ///   - the same address as returned by `rx()` if the allocator uses RWX mapping (pages have all of Read, Write,
    ///     and Execute permissions) or MAP_JIT, which requires changing JIT memory protection manually.
    ///   - a valid pointer, but not the same as `rx` - this would be valid if dual mapping is used.
    ///   - NULL pointer, in case that the allocation strategy doesn't use RWX, MAP_JIT, or dual mapping. In this
    ///     case only [JitAllocator] can copy new code into the executable memory referenced by [Span].
    pub const fn rw(&self) -> *mut u8 {
        self.rw
    }

    pub const fn size(&self) -> usize {
        self.size
    }

    /// Returns the allocator block this span lives in, as an opaque pointer.
    pub const fn block(&self) -> *mut u8 {
        self.block
    }

    pub const fn is_icache_clean(&self) -> bool {
        self.icache_clean
    }

    pub const fn is_directly_writeable(&self) -> bool {
        !self.rw.is_null()
    }
}