VirtualBox

source: vbox/trunk/src/VBox/VMM/VMMAll/IEMAllN8veExecMem.cpp@ 106378

Last change on this file since 106378 was 106378, checked in by vboxsync, 5 weeks ago

VMM/IEM: Fixed assertion in exec mem allocator. bugref:10720

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 88.0 KB
Line 
1/* $Id: IEMAllN8veExecMem.cpp 106378 2024-10-16 13:43:43Z vboxsync $ */
2/** @file
3 * IEM - Native Recompiler, Executable Memory Allocator.
4 */
5
6/*
7 * Copyright (C) 2023-2024 Oracle and/or its affiliates.
8 *
9 * This file is part of VirtualBox base platform packages, as
10 * available from https://www.virtualbox.org.
11 *
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU General Public License
14 * as published by the Free Software Foundation, in version 3 of the
15 * License.
16 *
17 * This program is distributed in the hope that it will be useful, but
18 * WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * General Public License for more details.
21 *
22 * You should have received a copy of the GNU General Public License
23 * along with this program; if not, see <https://www.gnu.org/licenses>.
24 *
25 * SPDX-License-Identifier: GPL-3.0-only
26 */
27
28
29/*********************************************************************************************************************************
30* Header Files *
31*********************************************************************************************************************************/
32#define LOG_GROUP LOG_GROUP_IEM_RE_NATIVE
33#define IEM_WITH_OPAQUE_DECODER_STATE
34#define VMM_INCLUDED_SRC_include_IEMMc_h /* block IEMMc.h inclusion. */
35#include <VBox/vmm/iem.h>
36#include <VBox/vmm/cpum.h>
37#include "IEMInternal.h"
38#include <VBox/vmm/vmcc.h>
39#include <VBox/log.h>
40#include <VBox/err.h>
41#include <VBox/param.h>
42#include <iprt/assert.h>
43#include <iprt/mem.h>
44#include <iprt/string.h>
45#if defined(RT_ARCH_AMD64)
46# include <iprt/x86.h>
47#elif defined(RT_ARCH_ARM64)
48# include <iprt/armv8.h>
49#endif
50
51#ifdef RT_OS_WINDOWS
52# include <iprt/formats/pecoff.h> /* this is incomaptible with windows.h, thus: */
53extern "C" DECLIMPORT(uint8_t) __cdecl RtlAddFunctionTable(void *pvFunctionTable, uint32_t cEntries, uintptr_t uBaseAddress);
54extern "C" DECLIMPORT(uint8_t) __cdecl RtlDelFunctionTable(void *pvFunctionTable);
55#else
56# include <iprt/formats/dwarf.h>
57# if defined(RT_OS_DARWIN)
58# include <libkern/OSCacheControl.h>
59# include <mach/mach.h>
60# include <mach/mach_vm.h>
61# define IEMNATIVE_USE_LIBUNWIND
62extern "C" void __register_frame(const void *pvFde);
63extern "C" void __deregister_frame(const void *pvFde);
64# else
65# ifdef DEBUG_bird /** @todo not thread safe yet */
66# define IEMNATIVE_USE_GDB_JIT
67# endif
68# ifdef IEMNATIVE_USE_GDB_JIT
69# include <iprt/critsect.h>
70# include <iprt/once.h>
71# include <iprt/formats/elf64.h>
72# endif
73extern "C" void __register_frame_info(void *pvBegin, void *pvObj); /* found no header for these two */
74extern "C" void *__deregister_frame_info(void *pvBegin); /* (returns pvObj from __register_frame_info call) */
75# endif
76#endif
77
78#include "IEMN8veRecompiler.h"
79
80
81/*********************************************************************************************************************************
82* Executable Memory Allocator *
83*********************************************************************************************************************************/
84/** The chunk sub-allocation unit size in bytes. */
85#define IEMEXECMEM_ALT_SUB_ALLOC_UNIT_SIZE 256
86/** The chunk sub-allocation unit size as a shift factor. */
87#define IEMEXECMEM_ALT_SUB_ALLOC_UNIT_SHIFT 8
88/** Enables adding a header to the sub-allocator allocations.
89 * This is useful for freeing up executable memory among other things. */
90#define IEMEXECMEM_ALT_SUB_WITH_ALLOC_HEADER
91/** Use alternative pruning. */
92#define IEMEXECMEM_ALT_SUB_WITH_ALT_PRUNING
93
94
95#if defined(IN_RING3) && !defined(RT_OS_WINDOWS)
96# ifdef IEMNATIVE_USE_GDB_JIT
97# define IEMNATIVE_USE_GDB_JIT_ET_DYN
98
99/** GDB JIT: Code entry. */
100typedef struct GDBJITCODEENTRY
101{
102 struct GDBJITCODEENTRY *pNext;
103 struct GDBJITCODEENTRY *pPrev;
104 uint8_t *pbSymFile;
105 uint64_t cbSymFile;
106} GDBJITCODEENTRY;
107
108/** GDB JIT: Actions. */
109typedef enum GDBJITACTIONS : uint32_t
110{
111 kGdbJitaction_NoAction = 0, kGdbJitaction_Register, kGdbJitaction_Unregister
112} GDBJITACTIONS;
113
114/** GDB JIT: Descriptor. */
115typedef struct GDBJITDESCRIPTOR
116{
117 uint32_t uVersion;
118 GDBJITACTIONS enmAction;
119 GDBJITCODEENTRY *pRelevant;
120 GDBJITCODEENTRY *pHead;
121 /** Our addition: */
122 GDBJITCODEENTRY *pTail;
123} GDBJITDESCRIPTOR;
124
125/** GDB JIT: Our simple symbol file data. */
126typedef struct GDBJITSYMFILE
127{
128 Elf64_Ehdr EHdr;
129# ifndef IEMNATIVE_USE_GDB_JIT_ET_DYN
130 Elf64_Shdr aShdrs[5];
131# else
132 Elf64_Shdr aShdrs[7];
133 Elf64_Phdr aPhdrs[2];
134# endif
135 /** The dwarf ehframe data for the chunk. */
136 uint8_t abEhFrame[512];
137 char szzStrTab[128];
138 Elf64_Sym aSymbols[3];
139# ifdef IEMNATIVE_USE_GDB_JIT_ET_DYN
140 Elf64_Sym aDynSyms[2];
141 Elf64_Dyn aDyn[6];
142# endif
143} GDBJITSYMFILE;
144
145extern "C" GDBJITDESCRIPTOR __jit_debug_descriptor;
146extern "C" DECLEXPORT(void) __jit_debug_register_code(void);
147
148/** Init once for g_IemNativeGdbJitLock. */
149static RTONCE g_IemNativeGdbJitOnce = RTONCE_INITIALIZER;
150/** Init once for the critical section. */
151static RTCRITSECT g_IemNativeGdbJitLock;
152
153/** GDB reads the info here. */
154GDBJITDESCRIPTOR __jit_debug_descriptor = { 1, kGdbJitaction_NoAction, NULL, NULL };
155
156/** GDB sets a breakpoint on this and checks __jit_debug_descriptor when hit. */
157DECL_NO_INLINE(RT_NOTHING, DECLEXPORT(void)) __jit_debug_register_code(void)
158{
159 ASMNopPause();
160}
161
162/** @callback_method_impl{FNRTONCE} */
163static DECLCALLBACK(int32_t) iemNativeGdbJitInitOnce(void *pvUser)
164{
165 RT_NOREF(pvUser);
166 return RTCritSectInit(&g_IemNativeGdbJitLock);
167}
168
169
170# endif /* IEMNATIVE_USE_GDB_JIT */
171
172/**
173 * Per-chunk unwind info for non-windows hosts.
174 */
175typedef struct IEMEXECMEMCHUNKEHFRAME
176{
177# ifdef IEMNATIVE_USE_LIBUNWIND
178 /** The offset of the FDA into abEhFrame. */
179 uintptr_t offFda;
180# else
181 /** 'struct object' storage area. */
182 uint8_t abObject[1024];
183# endif
184# ifdef IEMNATIVE_USE_GDB_JIT
185# if 0
186 /** The GDB JIT 'symbol file' data. */
187 GDBJITSYMFILE GdbJitSymFile;
188# endif
189 /** The GDB JIT list entry. */
190 GDBJITCODEENTRY GdbJitEntry;
191# endif
192 /** The dwarf ehframe data for the chunk. */
193 uint8_t abEhFrame[512];
194} IEMEXECMEMCHUNKEHFRAME;
195/** Pointer to per-chunk info info for non-windows hosts. */
196typedef IEMEXECMEMCHUNKEHFRAME *PIEMEXECMEMCHUNKEHFRAME;
197#endif
198
199
200/**
201 * An chunk of executable memory.
202 */
203typedef struct IEMEXECMEMCHUNK
204{
205 /** Number of free items in this chunk. */
206 uint32_t cFreeUnits;
207 /** Hint were to start searching for free space in the allocation bitmap. */
208 uint32_t idxFreeHint;
209 /** Pointer to the readable/writeable view of the memory chunk. */
210 void *pvChunkRw;
211 /** Pointer to the readable/executable view of the memory chunk. */
212 void *pvChunkRx;
213 /** Pointer to the context structure detailing the per chunk common code. */
214 PCIEMNATIVEPERCHUNKCTX pCtx;
215#ifdef IN_RING3
216 /**
217 * Pointer to the unwind information.
218 *
219 * This is used during C++ throw and longjmp (windows and probably most other
220 * platforms). Some debuggers (windbg) makes use of it as well.
221 *
222 * Windows: This is allocated from hHeap on windows because (at least for
223 * AMD64) the UNWIND_INFO structure address in the
224 * RUNTIME_FUNCTION entry is an RVA and the chunk is the "image".
225 *
226 * Others: Allocated from the regular heap to avoid unnecessary executable data
227 * structures. This points to an IEMEXECMEMCHUNKEHFRAME structure. */
228 void *pvUnwindInfo;
229#elif defined(IN_RING0)
230 /** Allocation handle. */
231 RTR0MEMOBJ hMemObj;
232#endif
233} IEMEXECMEMCHUNK;
234/** Pointer to a memory chunk. */
235typedef IEMEXECMEMCHUNK *PIEMEXECMEMCHUNK;
236
237
238/**
239 * Executable memory allocator for the native recompiler.
240 */
241typedef struct IEMEXECMEMALLOCATOR
242{
243 /** Magic value (IEMEXECMEMALLOCATOR_MAGIC). */
244 uint32_t uMagic;
245
246 /** The chunk size. */
247 uint32_t cbChunk;
248 /** The maximum number of chunks. */
249 uint32_t cMaxChunks;
250 /** The current number of chunks. */
251 uint32_t cChunks;
252 /** Hint where to start looking for available memory. */
253 uint32_t idxChunkHint;
254 /** Statistics: Current number of allocations. */
255 uint32_t cAllocations;
256
257 /** The total amount of memory available. */
258 uint64_t cbTotal;
259 /** Total amount of free memory. */
260 uint64_t cbFree;
261 /** Total amount of memory allocated. */
262 uint64_t cbAllocated;
263
264 /** Pointer to the allocation bitmaps for all the chunks (follows aChunks).
265 *
266 * Since the chunk size is a power of two and the minimum chunk size is a lot
267 * higher than the IEMEXECMEM_ALT_SUB_ALLOC_UNIT_SIZE, each chunk will always
268 * require a whole number of uint64_t elements in the allocation bitmap. So,
269 * for sake of simplicity, they are allocated as one continous chunk for
270 * simplicity/laziness. */
271 uint64_t *pbmAlloc;
272 /** Number of units (IEMEXECMEM_ALT_SUB_ALLOC_UNIT_SIZE) per chunk. */
273 uint32_t cUnitsPerChunk;
274 /** Number of bitmap elements per chunk (for quickly locating the bitmap
275 * portion corresponding to an chunk). */
276 uint32_t cBitmapElementsPerChunk;
277
278 /** Number of times we fruitlessly scanned a chunk for free space. */
279 uint64_t cFruitlessChunkScans;
280
281#ifdef IEMEXECMEM_ALT_SUB_WITH_ALT_PRUNING
282 /** The next chunk to prune in. */
283 uint32_t idxChunkPrune;
284 /** Where in chunk offset to start pruning at. */
285 uint32_t offChunkPrune;
286 /** Profiling the pruning code. */
287 STAMPROFILE StatPruneProf;
288 /** Number of bytes recovered by the pruning. */
289 STAMPROFILE StatPruneRecovered;
290#endif
291
292#ifdef VBOX_WITH_STATISTICS
293 STAMPROFILE StatAlloc;
294 /** Total amount of memory not being usable currently due to IEMEXECMEM_ALT_SUB_ALLOC_UNIT_SIZE. */
295 uint64_t cbUnusable;
296 /** Allocation size distribution (in alloc units; 0 is the slop bucket). */
297 STAMCOUNTER aStatSizes[16];
298#endif
299
300#if defined(IN_RING3) && !defined(RT_OS_WINDOWS)
301 /** Pointer to the array of unwind info running parallel to aChunks (same
302 * allocation as this structure, located after the bitmaps).
303 * (For Windows, the structures must reside in 32-bit RVA distance to the
304 * actual chunk, so they are allocated off the chunk.) */
305 PIEMEXECMEMCHUNKEHFRAME paEhFrames;
306#endif
307
308 /** The allocation chunks. */
309 RT_FLEXIBLE_ARRAY_EXTENSION
310 IEMEXECMEMCHUNK aChunks[RT_FLEXIBLE_ARRAY];
311} IEMEXECMEMALLOCATOR;
312/** Pointer to an executable memory allocator. */
313typedef IEMEXECMEMALLOCATOR *PIEMEXECMEMALLOCATOR;
314
315/** Magic value for IEMEXECMEMALLOCATOR::uMagic (Scott Frederick Turow). */
316#define IEMEXECMEMALLOCATOR_MAGIC UINT32_C(0x19490412)
317
318
319#ifdef IEMEXECMEM_ALT_SUB_WITH_ALLOC_HEADER
320/**
321 * Allocation header.
322 */
323typedef struct IEMEXECMEMALLOCHDR
324{
325 union
326 {
327 struct
328 {
329 /** Magic value / eyecatcher (IEMEXECMEMALLOCHDR_MAGIC). */
330 uint32_t uMagic;
331 /** The allocation chunk (for speeding up freeing). */
332 uint32_t idxChunk;
333 };
334 /** Combined magic and chunk index, for the pruning scanner code. */
335 uint64_t u64MagicAndChunkIdx;
336 };
337 /** Pointer to the translation block the allocation belongs to.
338 * This is the whole point of the header. */
339 PIEMTB pTb;
340} IEMEXECMEMALLOCHDR;
341/** Pointer to an allocation header. */
342typedef IEMEXECMEMALLOCHDR *PIEMEXECMEMALLOCHDR;
343/** Magic value for IEMEXECMEMALLOCHDR ('ExeM'). */
344# define IEMEXECMEMALLOCHDR_MAGIC UINT32_C(0x4d657845)
345#endif
346
347
348static int iemExecMemAllocatorGrow(PVMCPUCC pVCpu, PIEMEXECMEMALLOCATOR pExecMemAllocator);
349
350
351#ifdef IEMEXECMEM_ALT_SUB_WITH_ALT_PRUNING
352/**
353 * Frees up executable memory when we're out space.
354 *
355 * This is an alternative to iemTbAllocatorFreeupNativeSpace() that frees up
356 * space in a more linear fashion from the allocator's point of view. It may
357 * also defragment if implemented & enabled
358 */
359static void iemExecMemAllocatorPrune(PVMCPU pVCpu, PIEMEXECMEMALLOCATOR pExecMemAllocator)
360{
361# ifndef IEMEXECMEM_ALT_SUB_WITH_ALLOC_HEADER
362# error "IEMEXECMEM_ALT_SUB_WITH_ALT_PRUNING requires IEMEXECMEM_ALT_SUB_WITH_ALLOC_HEADER"
363# endif
364 STAM_REL_PROFILE_START(&pExecMemAllocator->StatPruneProf, a);
365
366 /*
367 * Before we can start, we must process delayed frees.
368 */
369#if 1
370 PIEMTBALLOCATOR const pTbAllocator = iemTbAllocatorFreeBulkStart(pVCpu);
371#else
372 iemTbAllocatorProcessDelayedFrees(pVCpu, pVCpu->iem.s.pTbAllocatorR3);
373#endif
374
375 AssertCompile(RT_IS_POWER_OF_TWO(IEMEXECMEM_ALT_SUB_ALLOC_UNIT_SIZE));
376
377 uint32_t const cbChunk = pExecMemAllocator->cbChunk;
378 AssertReturnVoid(RT_IS_POWER_OF_TWO(cbChunk));
379 AssertReturnVoid(cbChunk >= _1M && cbChunk <= _256M); /* see iemExecMemAllocatorInit */
380
381 uint32_t const cChunks = pExecMemAllocator->cChunks;
382 AssertReturnVoid(cChunks == pExecMemAllocator->cMaxChunks);
383 AssertReturnVoid(cChunks >= 1);
384
385 Assert(!pVCpu->iem.s.pCurTbR3);
386
387 /*
388 * Decide how much to prune. The chunk is is a multiple of two, so we'll be
389 * scanning a multiple of two here as well.
390 */
391 uint32_t cbToPrune = cbChunk;
392
393 /* Never more than 25%. */
394 if (cChunks < 4)
395 cbToPrune /= cChunks == 1 ? 4 : 2;
396
397 /* Upper limit. In a debug build a 4MB limit averages out at ~0.6ms per call. */
398 if (cbToPrune > _4M)
399 cbToPrune = _4M;
400
401 /*
402 * Adjust the pruning chunk and offset accordingly.
403 */
404 uint32_t idxChunk = pExecMemAllocator->idxChunkPrune;
405 uint32_t offChunk = pExecMemAllocator->offChunkPrune;
406 offChunk &= ~(uint32_t)(IEMEXECMEM_ALT_SUB_ALLOC_UNIT_SIZE - 1U);
407 if (offChunk >= cbChunk)
408 {
409 offChunk = 0;
410 idxChunk += 1;
411 }
412 if (idxChunk >= cChunks)
413 {
414 offChunk = 0;
415 idxChunk = 0;
416 }
417
418 uint32_t const offPruneEnd = RT_MIN(offChunk + cbToPrune, cbChunk);
419
420 /*
421 * Do the pruning. The current approach is the sever kind.
422 *
423 * This is memory bound, as we must load both the allocation header and the
424 * associated TB and then modify them. So, the CPU isn't all that unitilized
425 * here. Try apply some prefetching to speed it up a tiny bit.
426 */
427 uint64_t cbPruned = 0;
428 uint64_t const u64MagicAndChunkIdx = RT_MAKE_U64(IEMEXECMEMALLOCHDR_MAGIC, idxChunk);
429 uint8_t * const pbChunk = (uint8_t *)pExecMemAllocator->aChunks[idxChunk].pvChunkRx;
430 while (offChunk < offPruneEnd)
431 {
432 PIEMEXECMEMALLOCHDR pHdr = (PIEMEXECMEMALLOCHDR)&pbChunk[offChunk];
433
434 /* Is this the start of an allocation block for a TB? (We typically
435 have one allocation at the start of each chunk for the unwind info
436 where pTb is NULL.) */
437 PIEMTB pTb;
438 if ( pHdr->u64MagicAndChunkIdx == u64MagicAndChunkIdx
439 && RT_LIKELY((pTb = pHdr->pTb) != NULL))
440 {
441 AssertPtr(pTb);
442
443 uint32_t const cbBlock = RT_ALIGN_32(pTb->Native.cInstructions * sizeof(IEMNATIVEINSTR) + sizeof(*pHdr),
444 IEMEXECMEM_ALT_SUB_ALLOC_UNIT_SIZE);
445
446 /* Prefetch the next header before freeing the current one and its TB. */
447 /** @todo Iff the block size was part of the header in some way, this could be
448 * a tiny bit faster. */
449 offChunk += cbBlock;
450#if defined(_MSC_VER) && defined(RT_ARCH_AMD64)
451 _mm_prefetch((char *)&pbChunk[offChunk], _MM_HINT_T0);
452#elif defined(_MSC_VER) && defined(RT_ARCH_ARM64)
453 __prefetch(&pbChunk[offChunk]);
454#else
455 __builtin_prefetch(&pbChunk[offChunk], 1 /*rw*/);
456#endif
457 /* Some paranoia first, though. */
458 AssertBreakStmt(offChunk <= cbChunk, offChunk -= cbBlock - IEMEXECMEM_ALT_SUB_ALLOC_UNIT_SIZE);
459 cbPruned += cbBlock;
460
461#if 1
462 iemTbAllocatorFreeBulk(pVCpu, pTbAllocator, pTb);
463#else
464 iemTbAllocatorFree(pVCpu, pTb);
465#endif
466 }
467 else
468 offChunk += IEMEXECMEM_ALT_SUB_ALLOC_UNIT_SIZE;
469 }
470 STAM_REL_PROFILE_ADD_PERIOD(&pExecMemAllocator->StatPruneRecovered, cbPruned);
471
472 pVCpu->iem.s.ppTbLookupEntryR3 = &pVCpu->iem.s.pTbLookupEntryDummyR3;
473
474 /*
475 * Save the current pruning point.
476 */
477 pExecMemAllocator->offChunkPrune = offChunk;
478 pExecMemAllocator->idxChunkPrune = idxChunk;
479
480 /* Set the hint to the start of the pruned region. */
481 pExecMemAllocator->idxChunkHint = idxChunk;
482 pExecMemAllocator->aChunks[idxChunk].idxFreeHint = offChunk / IEMEXECMEM_ALT_SUB_ALLOC_UNIT_SIZE;
483
484 STAM_REL_PROFILE_STOP(&pExecMemAllocator->StatPruneProf, a);
485}
486#endif /* IEMEXECMEM_ALT_SUB_WITH_ALT_PRUNING */
487
488
489#if defined(VBOX_STRICT) || 0
490/**
491 * The old bitmap scanner code, for comparison and assertions.
492 */
493static uint32_t iemExecMemAllocatorFindReqFreeUnitsOld(uint64_t *pbmAlloc, uint32_t cToScan, uint32_t cReqUnits)
494{
495 /** @todo This can probably be done more efficiently for non-x86 systems. */
496 int iBit = ASMBitFirstClear(pbmAlloc, cToScan);
497 while (iBit >= 0 && (uint32_t)iBit <= cToScan - cReqUnits)
498 {
499 uint32_t idxAddBit = 1;
500 while (idxAddBit < cReqUnits && !ASMBitTest(pbmAlloc, (uint32_t)iBit + idxAddBit))
501 idxAddBit++;
502 if (idxAddBit >= cReqUnits)
503 return (uint32_t)iBit;
504 iBit = ASMBitNextClear(pbmAlloc, cToScan, iBit + idxAddBit - 1);
505 }
506 return UINT32_MAX;
507}
508#endif
509
510
511/**
512 * Bitmap scanner code that looks for a bunch of @a cReqUnits zero bits.
513 *
514 * Booting win11 with a r165098 release build the average native TB size is
515 * around 9 units (of 256 bytes). So, it is unlikely we need to scan any
516 * subsequent words once we hit a patch of zeros, thus @a a_fBig.
517 *
518 * @todo This needs more tweaking. While it *is* faster the the old code,
519 * it doens't seem like it's all that much. :/
520 */
521template<const bool a_fBig>
522static uint32_t iemExecMemAllocatorFindReqFreeUnits(uint64_t *pbmAlloc, uint32_t c64WordsToScan, uint32_t cReqUnits)
523{
524 /*
525 * Scan the (section of the) allocation bitmap in 64-bit words.
526 */
527 unsigned cPrevLeadingZeros = 0;
528 for (uint32_t off = 0; off < c64WordsToScan; off++)
529 {
530 uint64_t uWord = pbmAlloc[off];
531 if (uWord == UINT64_MAX)
532 {
533 /*
534 * Getting thru patches of UINT64_MAX is a frequent problem when the allocator
535 * fills up, so it's definitely worth optimizing.
536 *
537 * The complicated code below is a bit faster on arm. Reducing the per TB cost
538 * from 4255ns to 4106ns (best run out of 10). On win/amd64 there isn't an
539 * obvious gain here, at least not with the data currently being profiled.
540 */
541#if 1
542 off++;
543 uint32_t cQuads = (c64WordsToScan - off) / 4;
544
545 /* Align. */
546 if (cQuads > 1)
547 switch (((uintptr_t)&pbmAlloc[off] / sizeof(uint64_t)) & 3)
548 {
549 case 0:
550 break;
551 case 1:
552 {
553 uWord = pbmAlloc[off];
554 uint64_t uWord1 = pbmAlloc[off + 1];
555 uint64_t uWord2 = pbmAlloc[off + 2];
556 if ((uWord & uWord1 & uWord2) == UINT64_MAX)
557 {
558 off += 3;
559 cQuads = (c64WordsToScan - off) / 4;
560 }
561 else if (uWord == UINT64_MAX)
562 {
563 if (uWord1 != UINT64_MAX)
564 {
565 uWord = uWord1;
566 off += 1;
567 }
568 else
569 {
570 uWord = uWord2;
571 off += 2;
572 }
573 }
574 break;
575 }
576 case 2:
577 {
578 uWord = pbmAlloc[off];
579 uint64_t uWord1 = pbmAlloc[off + 1];
580 if ((uWord & uWord1) == UINT64_MAX)
581 {
582 off += 2;
583 cQuads = (c64WordsToScan - off) / 4;
584 }
585 else if (uWord == UINT64_MAX)
586 {
587 uWord = uWord1;
588 off += 1;
589 }
590 break;
591 }
592 case 3:
593 uWord = pbmAlloc[off];
594 if (uWord == UINT64_MAX)
595 {
596 off++;
597 cQuads = (c64WordsToScan - off) / 4;
598 }
599 break;
600 }
601 if (uWord == UINT64_MAX)
602 {
603 /* Looping over 32 bytes at a time. */
604 for (;;)
605 {
606 if (cQuads-- > 0)
607 {
608 uWord = pbmAlloc[off + 0];
609 uint64_t uWord1 = pbmAlloc[off + 1];
610 uint64_t uWord2 = pbmAlloc[off + 2];
611 uint64_t uWord3 = pbmAlloc[off + 3];
612 if ((uWord & uWord1 & uWord2 & uWord3) == UINT64_MAX)
613 off += 4;
614 else
615 {
616 if (uWord != UINT64_MAX)
617 { }
618 else if (uWord1 != UINT64_MAX)
619 {
620 uWord = uWord1;
621 off += 1;
622 }
623 else if (uWord2 != UINT64_MAX)
624 {
625 uWord = uWord2;
626 off += 2;
627 }
628 else
629 {
630 uWord = uWord3;
631 off += 3;
632 }
633 break;
634 }
635 }
636 else
637 {
638 if (off < c64WordsToScan)
639 {
640 uWord = pbmAlloc[off];
641 if (uWord != UINT64_MAX)
642 break;
643 off++;
644 if (off < c64WordsToScan)
645 {
646 uWord = pbmAlloc[off];
647 if (uWord != UINT64_MAX)
648 break;
649 off++;
650 if (off < c64WordsToScan)
651 {
652 uWord = pbmAlloc[off];
653 if (uWord != UINT64_MAX)
654 break;
655 Assert(off + 1 == c64WordsToScan);
656 }
657 }
658 }
659 return UINT32_MAX;
660 }
661 }
662 }
663#else
664 do
665 {
666 off++;
667 if (off < c64WordsToScan)
668 uWord = pbmAlloc[off];
669 else
670 return UINT32_MAX;
671 } while (uWord == UINT64_MAX);
672#endif
673 cPrevLeadingZeros = 0;
674 }
675
676 /*
677 * If we get down here, we have a word that isn't UINT64_MAX.
678 */
679 if (uWord != 0)
680 {
681 /*
682 * Fend of large request we cannot satisfy before the first set bit.
683 */
684 if (!a_fBig || cReqUnits < 64 + cPrevLeadingZeros)
685 {
686#ifdef __GNUC__
687 unsigned cZerosInWord = __builtin_popcountl(~uWord);
688#elif defined(_MSC_VER) && defined(RT_ARCH_AMD64)
689 unsigned cZerosInWord = __popcnt64(~uWord);
690#elif defined(_MSC_VER) && defined(RT_ARCH_ARM64)
691 unsigned cZerosInWord = _CountOneBits64(~uWord);
692#else
693# pragma message("need popcount intrinsic or something...")
694 unsigned cZerosInWord = 0;
695 for (uint64_t uTmp = ~uWords; uTmp; cZerosInWord++)
696 uTmp &= uTmp - 1; /* Clears the least significant bit set. */
697#endif
698 if (cZerosInWord + cPrevLeadingZeros >= cReqUnits)
699 {
700 /* Check if we've got a patch of zeros at the trailing end
701 when joined with the previous word: */
702#ifdef __GNUC__
703 unsigned cTrailingZeros = __builtin_ctzl(uWord);
704#else
705 unsigned cTrailingZeros = ASMBitFirstSetU64(uWord) - 1;
706#endif
707 if (cPrevLeadingZeros + cTrailingZeros >= cReqUnits)
708 return off * 64 - cPrevLeadingZeros;
709
710 /*
711 * Try leading zeros before we get on with the tedious stuff.
712 */
713#ifdef __GNUC__
714 cPrevLeadingZeros = __builtin_clzl(uWord);
715#else
716 cPrevLeadingZeros = 64 - ASMBitLastSetU64(uWord);
717#endif
718 if (cPrevLeadingZeros >= cReqUnits)
719 return (off + 1) * 64 - cPrevLeadingZeros;
720
721 /*
722 * Check the popcount again sans leading & trailing before looking
723 * inside the word.
724 */
725 cZerosInWord -= cPrevLeadingZeros + cTrailingZeros;
726 if (cZerosInWord >= cReqUnits)
727 {
728 /* 1; 64 - 0 - 1 = 63; */
729 unsigned const iBitLast = 64 - cPrevLeadingZeros - cReqUnits; /** @todo boundrary */
730 unsigned iBit = cTrailingZeros;
731 uWord >>= cTrailingZeros;
732 do
733 {
734 Assert(uWord & 1);
735#ifdef __GNUC__
736 unsigned iZeroBit = __builtin_ctzl(~uWord);
737#else
738 unsigned iZeroBit = ASMBitFirstSetU64(~uWord) - 1;
739#endif
740 iBit += iZeroBit;
741 uWord >>= iZeroBit;
742 Assert(iBit <= iBitLast);
743 Assert((uWord & 1) == 0);
744#ifdef __GNUC__
745 unsigned cZeros = __builtin_ctzl(uWord);
746#else
747 unsigned cZeros = ASMBitFirstSetU64(uWord) - 1;
748#endif
749 if (cZeros >= cReqUnits)
750 return off * 64 + iBit;
751
752 cZerosInWord -= cZeros; /* (may underflow as we will count shifted in zeros) */
753 iBit += cZeros;
754 uWord >>= cZeros;
755 } while ((int)cZerosInWord >= (int)cReqUnits && iBit < iBitLast);
756 }
757 continue; /* we've already calculated cPrevLeadingZeros */
758 }
759 }
760
761 /* Update the leading (MSB) zero count. */
762#ifdef __GNUC__
763 cPrevLeadingZeros = __builtin_clzl(uWord);
764#else
765 cPrevLeadingZeros = 64 - ASMBitLastSetU64(uWord);
766#endif
767 }
768 /*
769 * uWord == 0
770 */
771 else
772 {
773 if RT_CONSTEXPR_IF(!a_fBig)
774 return off * 64 - cPrevLeadingZeros;
775 else /* keep else */
776 {
777 if (cPrevLeadingZeros + 64 >= cReqUnits)
778 return off * 64 - cPrevLeadingZeros;
779 for (uint32_t off2 = off + 1;; off2++)
780 {
781 if (off2 < c64WordsToScan)
782 {
783 uWord = pbmAlloc[off2];
784 if (uWord == UINT64_MAX)
785 {
786 cPrevLeadingZeros = 0;
787 break;
788 }
789 if (uWord == 0)
790 {
791 if (cPrevLeadingZeros + (off2 - off + 1) * 64 >= cReqUnits)
792 return off * 64 - cPrevLeadingZeros;
793 }
794 else
795 {
796#ifdef __GNUC__
797 unsigned cTrailingZeros = __builtin_ctzl(uWord);
798#else
799 unsigned cTrailingZeros = ASMBitFirstSetU64(uWord) - 1;
800#endif
801 if (cPrevLeadingZeros + (off2 - off) * 64 + cTrailingZeros >= cReqUnits)
802 return off * 64 - cPrevLeadingZeros;
803#ifdef __GNUC__
804 cPrevLeadingZeros = __builtin_clzl(uWord);
805#else
806 cPrevLeadingZeros = 64 - ASMBitLastSetU64(uWord);
807#endif
808 break;
809 }
810 }
811 else
812 return UINT32_MAX;
813 }
814 }
815 }
816 }
817 return UINT32_MAX;
818}
819
820
821/**
822 * Try allocate a block of @a cReqUnits in the chunk @a idxChunk.
823 */
824static void *
825iemExecMemAllocatorAllocInChunkInt(PIEMEXECMEMALLOCATOR pExecMemAllocator, uint64_t *pbmAlloc, uint32_t idxFirst,
826 uint32_t cToScan, uint32_t cReqUnits, uint32_t idxChunk, PIEMTB pTb,
827 void **ppvExec, PCIEMNATIVEPERCHUNKCTX *ppChunkCtx)
828{
829 /*
830 * Shift the bitmap to the idxFirst bit so we can use ASMBitFirstClear.
831 */
832 Assert(!(cToScan & 63));
833 Assert(!(idxFirst & 63));
834 Assert(cToScan + idxFirst <= pExecMemAllocator->cUnitsPerChunk);
835 pbmAlloc += idxFirst / 64;
836 cToScan += idxFirst & 63;
837 Assert(!(cToScan & 63));
838
839#if 1
840 uint32_t const iBit = cReqUnits < 64
841 ? iemExecMemAllocatorFindReqFreeUnits<false>(pbmAlloc, cToScan / 64, cReqUnits)
842 : iemExecMemAllocatorFindReqFreeUnits<true>( pbmAlloc, cToScan / 64, cReqUnits);
843# ifdef VBOX_STRICT
844 uint32_t const iBitOld = iemExecMemAllocatorFindReqFreeUnitsOld(pbmAlloc, cToScan, cReqUnits);
845 AssertMsg( iBit == iBitOld
846 || (iBit / 64) == (iBitOld / 64), /* New algorithm will return trailing hit before middle. */
847 ("iBit=%#x (%#018RX64); iBitOld=%#x (%#018RX64); cReqUnits=%#x\n",
848 iBit, iBit != UINT32_MAX ? pbmAlloc[iBit / 64] : 0,
849 iBitOld, iBitOld != UINT32_MAX ? pbmAlloc[iBitOld / 64] : 0, cReqUnits));
850# endif
851#else
852 uint32_t const iBit = iemExecMemAllocatorFindReqFreeUnitsOld(pbmAlloc, cToScan, cReqUnits);
853#endif
854 if (iBit != UINT32_MAX)
855 {
856 ASMBitSetRange(pbmAlloc, (uint32_t)iBit, (uint32_t)iBit + cReqUnits);
857
858 PIEMEXECMEMCHUNK const pChunk = &pExecMemAllocator->aChunks[idxChunk];
859 pChunk->cFreeUnits -= cReqUnits;
860 pChunk->idxFreeHint = (uint32_t)iBit + cReqUnits;
861
862 pExecMemAllocator->cAllocations += 1;
863 uint32_t const cbReq = cReqUnits << IEMEXECMEM_ALT_SUB_ALLOC_UNIT_SHIFT;
864 pExecMemAllocator->cbAllocated += cbReq;
865 pExecMemAllocator->cbFree -= cbReq;
866 pExecMemAllocator->idxChunkHint = idxChunk;
867
868 void * const pvMemRw = (uint8_t *)pChunk->pvChunkRw
869 + ((idxFirst + (uint32_t)iBit) << IEMEXECMEM_ALT_SUB_ALLOC_UNIT_SHIFT);
870
871 if (ppChunkCtx)
872 *ppChunkCtx = pChunk->pCtx;
873
874 /*
875 * Initialize the header and return.
876 */
877# ifdef IEMEXECMEM_ALT_SUB_WITH_ALLOC_HEADER
878 PIEMEXECMEMALLOCHDR const pHdr = (PIEMEXECMEMALLOCHDR)pvMemRw;
879 pHdr->uMagic = IEMEXECMEMALLOCHDR_MAGIC;
880 pHdr->idxChunk = idxChunk;
881 pHdr->pTb = pTb;
882
883 if (ppvExec)
884 *ppvExec = (uint8_t *)pChunk->pvChunkRx
885 + ((idxFirst + (uint32_t)iBit) << IEMEXECMEM_ALT_SUB_ALLOC_UNIT_SHIFT)
886 + sizeof(*pHdr);
887
888 return pHdr + 1;
889#else
890 if (ppvExec)
891 *ppvExec = (uint8_t *)pChunk->pvChunkRx
892 + ((idxFirst + (uint32_t)iBit) << IEMEXECMEM_ALT_SUB_ALLOC_UNIT_SHIFT);
893
894 RT_NOREF(pTb);
895 return pvMem;
896#endif
897 }
898
899 return NULL;
900}
901
902
903/**
904 * Converts requested number of bytes into a unit count.
905 */
906DECL_FORCE_INLINE(uint32_t) iemExecMemAllocBytesToUnits(uint32_t cbReq)
907{
908#ifdef IEMEXECMEM_ALT_SUB_WITH_ALLOC_HEADER
909 return (cbReq + sizeof(IEMEXECMEMALLOCHDR) + IEMEXECMEM_ALT_SUB_ALLOC_UNIT_SIZE - 1)
910#else
911 return (cbReq + IEMEXECMEM_ALT_SUB_ALLOC_UNIT_SIZE - 1)
912#endif
913 >> IEMEXECMEM_ALT_SUB_ALLOC_UNIT_SHIFT;
914}
915
916
917DECL_FORCE_INLINE(PIEMNATIVEINSTR)
918iemExecMemAllocatorAllocUnitsInChunkInner(PIEMEXECMEMALLOCATOR pExecMemAllocator, uint32_t idxChunk, uint32_t cReqUnits,
919 PIEMTB pTb, PIEMNATIVEINSTR *ppaExec, PCIEMNATIVEPERCHUNKCTX *ppChunkCtx)
920{
921 uint64_t * const pbmAlloc = &pExecMemAllocator->pbmAlloc[pExecMemAllocator->cBitmapElementsPerChunk * idxChunk];
922 uint32_t const idxHint = pExecMemAllocator->aChunks[idxChunk].idxFreeHint & ~(uint32_t)63;
923 if (idxHint + cReqUnits <= pExecMemAllocator->cUnitsPerChunk)
924 {
925 void *pvRet = iemExecMemAllocatorAllocInChunkInt(pExecMemAllocator, pbmAlloc, idxHint,
926 pExecMemAllocator->cUnitsPerChunk - idxHint,
927 cReqUnits, idxChunk, pTb, (void **)ppaExec, ppChunkCtx);
928 if (pvRet)
929 return (PIEMNATIVEINSTR)pvRet;
930 }
931 void *pvRet = iemExecMemAllocatorAllocInChunkInt(pExecMemAllocator, pbmAlloc, 0,
932 RT_MIN(pExecMemAllocator->cUnitsPerChunk,
933 RT_ALIGN_32(idxHint + cReqUnits, 64*4)),
934 cReqUnits, idxChunk, pTb, (void **)ppaExec, ppChunkCtx);
935 if (pvRet)
936 return (PIEMNATIVEINSTR)pvRet;
937
938 pExecMemAllocator->cFruitlessChunkScans += 1;
939 return NULL;
940}
941
942
943DECLINLINE(PIEMNATIVEINSTR)
944iemExecMemAllocatorAllocBytesInChunk(PIEMEXECMEMALLOCATOR pExecMemAllocator, uint32_t idxChunk, uint32_t cbReq,
945 PIEMNATIVEINSTR *ppaExec)
946{
947 uint32_t const cReqUnits = iemExecMemAllocBytesToUnits(cbReq);
948 if (cReqUnits <= pExecMemAllocator->aChunks[idxChunk].cFreeUnits)
949 return iemExecMemAllocatorAllocUnitsInChunkInner(pExecMemAllocator, idxChunk, cReqUnits, NULL /*pTb*/,
950 ppaExec, NULL /*ppChunkCtx*/);
951 return NULL;
952}
953
954
955/**
956 * Allocates @a cbReq bytes of executable memory.
957 *
958 * @returns Pointer to the readable/writeable memory, NULL if out of memory or other problem
959 * encountered.
960 * @param pVCpu The cross context virtual CPU structure of the
961 * calling thread.
962 * @param cbReq How many bytes are required.
963 * @param pTb The translation block that will be using the allocation.
964 * @param ppaExec Where to return the pointer to executable view of
965 * the allocated memory, optional.
966 * @param ppChunkCtx Where to return the per chunk attached context
967 * if available, optional.
968 */
969DECLHIDDEN(PIEMNATIVEINSTR) iemExecMemAllocatorAlloc(PVMCPU pVCpu, uint32_t cbReq, PIEMTB pTb,
970 PIEMNATIVEINSTR *ppaExec, PCIEMNATIVEPERCHUNKCTX *ppChunkCtx) RT_NOEXCEPT
971{
972 PIEMEXECMEMALLOCATOR pExecMemAllocator = pVCpu->iem.s.pExecMemAllocatorR3;
973 AssertReturn(pExecMemAllocator && pExecMemAllocator->uMagic == IEMEXECMEMALLOCATOR_MAGIC, NULL);
974 AssertMsgReturn(cbReq > 32 && cbReq < _512K, ("%#x\n", cbReq), NULL);
975 STAM_PROFILE_START(&pExecMemAllocator->StatAlloc, a);
976
977 uint32_t const cReqUnits = iemExecMemAllocBytesToUnits(cbReq);
978 STAM_COUNTER_INC(&pExecMemAllocator->aStatSizes[cReqUnits < RT_ELEMENTS(pExecMemAllocator->aStatSizes) ? cReqUnits : 0]);
979 for (unsigned iIteration = 0;; iIteration++)
980 {
981 if ( cbReq * 2 <= pExecMemAllocator->cbFree
982 || (cReqUnits == 1 || pExecMemAllocator->cbFree >= IEMEXECMEM_ALT_SUB_ALLOC_UNIT_SIZE) )
983 {
984 uint32_t const cChunks = pExecMemAllocator->cChunks;
985 uint32_t const idxChunkHint = pExecMemAllocator->idxChunkHint < cChunks ? pExecMemAllocator->idxChunkHint : 0;
986
987 /*
988 * We do two passes here, the first pass we skip chunks with fewer than cReqUnits * 16,
989 * the 2nd pass we skip chunks. The second pass checks the one skipped in the first pass.
990 */
991 for (uint32_t cMinFreePass = cReqUnits == 1 ? cReqUnits : cReqUnits * 16, cMaxFreePass = UINT32_MAX;;)
992 {
993 for (uint32_t idxChunk = idxChunkHint; idxChunk < cChunks; idxChunk++)
994 if ( pExecMemAllocator->aChunks[idxChunk].cFreeUnits >= cMinFreePass
995 && pExecMemAllocator->aChunks[idxChunk].cFreeUnits <= cMaxFreePass)
996 {
997 PIEMNATIVEINSTR const pRet = iemExecMemAllocatorAllocUnitsInChunkInner(pExecMemAllocator, idxChunk,
998 cReqUnits, pTb, ppaExec, ppChunkCtx);
999 if (pRet)
1000 {
1001 STAM_PROFILE_STOP(&pExecMemAllocator->StatAlloc, a);
1002#ifdef VBOX_WITH_STATISTICS
1003 pExecMemAllocator->cbUnusable += (cReqUnits << IEMEXECMEM_ALT_SUB_ALLOC_UNIT_SHIFT) - cbReq;
1004#endif
1005 return pRet;
1006 }
1007 }
1008 for (uint32_t idxChunk = 0; idxChunk < idxChunkHint; idxChunk++)
1009 if ( pExecMemAllocator->aChunks[idxChunk].cFreeUnits >= cMinFreePass
1010 && pExecMemAllocator->aChunks[idxChunk].cFreeUnits <= cMaxFreePass)
1011 {
1012 PIEMNATIVEINSTR const pRet = iemExecMemAllocatorAllocUnitsInChunkInner(pExecMemAllocator, idxChunk,
1013 cReqUnits, pTb, ppaExec, ppChunkCtx);
1014 if (pRet)
1015 {
1016 STAM_PROFILE_STOP(&pExecMemAllocator->StatAlloc, a);
1017#ifdef VBOX_WITH_STATISTICS
1018 pExecMemAllocator->cbUnusable += (cReqUnits << IEMEXECMEM_ALT_SUB_ALLOC_UNIT_SHIFT) - cbReq;
1019#endif
1020 return pRet;
1021 }
1022 }
1023 if (cMinFreePass <= cReqUnits * 2)
1024 break;
1025 cMaxFreePass = cMinFreePass - 1;
1026 cMinFreePass = cReqUnits * 2;
1027 }
1028 }
1029
1030 /*
1031 * Can we grow it with another chunk?
1032 */
1033 if (pExecMemAllocator->cChunks < pExecMemAllocator->cMaxChunks)
1034 {
1035 int rc = iemExecMemAllocatorGrow(pVCpu, pExecMemAllocator);
1036 AssertLogRelRCReturn(rc, NULL);
1037
1038 uint32_t const idxChunk = pExecMemAllocator->cChunks - 1;
1039 PIEMNATIVEINSTR const pRet = iemExecMemAllocatorAllocUnitsInChunkInner(pExecMemAllocator, idxChunk, cReqUnits, pTb,
1040 ppaExec, ppChunkCtx);
1041 if (pRet)
1042 {
1043 STAM_PROFILE_STOP(&pExecMemAllocator->StatAlloc, a);
1044#ifdef VBOX_WITH_STATISTICS
1045 pExecMemAllocator->cbUnusable += (cReqUnits << IEMEXECMEM_ALT_SUB_ALLOC_UNIT_SHIFT) - cbReq;
1046#endif
1047 return pRet;
1048 }
1049 AssertFailed();
1050 }
1051
1052 /*
1053 * Try prune native TBs once.
1054 */
1055 if (iIteration == 0)
1056 {
1057#ifdef IEMEXECMEM_ALT_SUB_WITH_ALT_PRUNING
1058 iemExecMemAllocatorPrune(pVCpu, pExecMemAllocator);
1059#else
1060 /* No header included in the instruction count here. */
1061 uint32_t const cNeededInstrs = RT_ALIGN_32(cbReq, IEMEXECMEM_ALT_SUB_ALLOC_UNIT_SIZE) / sizeof(IEMNATIVEINSTR);
1062 iemTbAllocatorFreeupNativeSpace(pVCpu, cNeededInstrs);
1063#endif
1064 }
1065 else
1066 {
1067 STAM_REL_COUNTER_INC(&pVCpu->iem.s.StatNativeExecMemInstrBufAllocFailed);
1068 STAM_PROFILE_STOP(&pExecMemAllocator->StatAlloc, a);
1069 return NULL;
1070 }
1071 }
1072}
1073
1074
1075/** This is a hook to ensure the instruction cache is properly flushed before the code in the memory
1076 * given by @a pv and @a cb is executed */
1077DECLHIDDEN(void) iemExecMemAllocatorReadyForUse(PVMCPUCC pVCpu, void *pv, size_t cb) RT_NOEXCEPT
1078{
1079#ifdef RT_OS_DARWIN
1080 /*
1081 * We need to synchronize the stuff we wrote to the data cache with the
1082 * instruction cache, since these aren't coherent on arm (or at least not
1083 * on Apple Mn CPUs).
1084 *
1085 * Note! Since we don't any share JIT'ed code with the other CPUs, we don't
1086 * really care whether the dcache is fully flushed back to memory. It
1087 * only needs to hit the level 2 cache, which the level 1 instruction
1088 * and data caches seems to be sharing. In ARM terms, we need to reach
1089 * a point of unification (PoU), rather than a point of coherhency (PoC).
1090 *
1091 * https://developer.apple.com/documentation/apple-silicon/porting-just-in-time-compilers-to-apple-silicon
1092 *
1093 * https://developer.arm.com/documentation/den0013/d/Caches/Point-of-coherency-and-unification
1094 *
1095 * Experimenting with the approach used by sys_icache_invalidate() and
1096 * tweaking it a little, could let us shave off a bit of effort. The thing
1097 * that slows the apple code down on an M2 (runing Sonoma 13.4), seems to
1098 * the 'DSB ISH' instructions performed every 20 icache line flushes.
1099 * Skipping these saves ~100ns or more per TB when profiling the native
1100 * recompiler on the TBs from a win11 full boot-desktop-shutdow sequence.
1101 * Thus we will leave DCACHE_ICACHE_SYNC_WITH_WITH_IVAU_DSB undefined if we
1102 * can.
1103 *
1104 * There appears not to be much difference between DSB options 'ISH',
1105 * 'ISHST', 'NSH' and 'NSHST'. The latter is theoretically all we need, so
1106 * we'll use that one.
1107 *
1108 * See https://developer.arm.com/documentation/100941/0101/Barriers for
1109 * details on the barrier options.
1110 *
1111 * Note! The CFG value "/IEM/HostICacheInvalidationViaHostAPI" can be used
1112 * to disabling the experimental code should it misbehave.
1113 */
1114 uint8_t const fHostICacheInvalidation = pVCpu->iem.s.fHostICacheInvalidation;
1115 if (!(fHostICacheInvalidation & IEMNATIVE_ICACHE_F_USE_HOST_API))
1116 {
1117# define DCACHE_ICACHE_SYNC_DSB_OPTION "nshst"
1118/*# define DCACHE_ICACHE_SYNC_WITH_WITH_IVAU_DSB*/
1119
1120 /* Skipping this is fine, but doesn't impact perf much. */
1121 __asm__ __volatile__("dsb " DCACHE_ICACHE_SYNC_DSB_OPTION);
1122
1123 /* Invalidate the icache for the range [pv,pv+cb). */
1124# ifdef DCACHE_ICACHE_SYNC_WITH_WITH_IVAU_DSB
1125 size_t const cIvauDsbEvery= 20;
1126 unsigned cDsb = cIvauDsbEvery;
1127# endif
1128 size_t const cbCacheLine = 64;
1129 size_t cbInvalidate = cb + ((uintptr_t)pv & (cbCacheLine - 1)) ;
1130 size_t cCacheLines = RT_ALIGN_Z(cbInvalidate, cbCacheLine) / cbCacheLine;
1131 uintptr_t uPtr = (uintptr_t)pv & ~(uintptr_t)(cbCacheLine - 1);
1132 for (;; uPtr += cbCacheLine)
1133 {
1134 __asm__ /*__volatile__*/("ic ivau, %0" : : "r" (uPtr));
1135 cCacheLines -= 1;
1136 if (!cCacheLines)
1137 break;
1138# ifdef DCACHE_ICACHE_SYNC_WITH_WITH_IVAU_DSB
1139 cDsb -= 1;
1140 if (cDsb != 0)
1141 { /* likely */ }
1142 else
1143 {
1144 __asm__ __volatile__("dsb " DCACHE_ICACHE_SYNC_DSB_OPTION);
1145 cDsb = cIvauDsbEvery;
1146 }
1147# endif
1148 }
1149
1150 /*
1151 * The DSB here is non-optional it seems.
1152 *
1153 * The following ISB can be omitted on M2 without any obvious sideeffects,
1154 * it produces better number in the above mention profiling scenario.
1155 * This could be related to the kHasICDSB flag in cpu_capabilities.h,
1156 * but it doesn't look like that flag is set here (M2, Sonoma 13.4).
1157 *
1158 * I've made the inclusion of the ISH barrier as configurable and with
1159 * a default of skipping it.
1160 */
1161 if (!(fHostICacheInvalidation & IEMNATIVE_ICACHE_F_END_WITH_ISH))
1162 __asm__ __volatile__("dsb " DCACHE_ICACHE_SYNC_DSB_OPTION
1163 ::: "memory");
1164 else
1165 __asm__ __volatile__("dsb " DCACHE_ICACHE_SYNC_DSB_OPTION "\n\t"
1166 "isb"
1167 ::: "memory");
1168 }
1169 else
1170 sys_icache_invalidate(pv, cb);
1171
1172#elif defined(RT_OS_LINUX) && defined(RT_ARCH_ARM64)
1173 RT_NOREF(pVCpu);
1174
1175 /* There is __builtin___clear_cache() but it flushes both the instruction and data cache, so do it manually. */
1176 static uint32_t s_u32CtrEl0 = 0;
1177 if (!s_u32CtrEl0)
1178 asm volatile ("mrs %0, ctr_el0":"=r" (s_u32CtrEl0));
1179 uintptr_t cbICacheLine = (uintptr_t)4 << (s_u32CtrEl0 & 0xf);
1180
1181 uintptr_t pb = (uintptr_t)pv & ~(cbICacheLine - 1);
1182 for (; pb < (uintptr_t)pv + cb; pb += cbICacheLine)
1183 asm volatile ("ic ivau, %0" : : "r" (pb) : "memory");
1184
1185 asm volatile ("dsb ish\n\t isb\n\t" : : : "memory");
1186
1187#else
1188 RT_NOREF(pVCpu, pv, cb);
1189#endif
1190}
1191
1192
1193/**
1194 * Frees executable memory.
1195 */
1196DECLHIDDEN(void) iemExecMemAllocatorFree(PVMCPU pVCpu, void *pv, size_t cb) RT_NOEXCEPT
1197{
1198 PIEMEXECMEMALLOCATOR pExecMemAllocator = pVCpu->iem.s.pExecMemAllocatorR3;
1199 Assert(pExecMemAllocator && pExecMemAllocator->uMagic == IEMEXECMEMALLOCATOR_MAGIC);
1200 AssertPtr(pv);
1201#ifdef VBOX_WITH_STATISTICS
1202 size_t const cbOrig = cb;
1203#endif
1204#ifndef IEMEXECMEM_ALT_SUB_WITH_ALLOC_HEADER
1205 Assert(!((uintptr_t)pv & (IEMEXECMEM_ALT_SUB_ALLOC_UNIT_SIZE - 1)));
1206
1207 /* Align the size as we did when allocating the block. */
1208 cb = RT_ALIGN_Z(cb, IEMEXECMEM_ALT_SUB_ALLOC_UNIT_SIZE);
1209
1210#else
1211 PIEMEXECMEMALLOCHDR pHdr = (PIEMEXECMEMALLOCHDR)pv - 1;
1212 Assert(!((uintptr_t)pHdr & (IEMEXECMEM_ALT_SUB_ALLOC_UNIT_SIZE - 1)));
1213 AssertReturnVoid(pHdr->uMagic == IEMEXECMEMALLOCHDR_MAGIC);
1214 uint32_t const idxChunk = pHdr->idxChunk;
1215 AssertReturnVoid(idxChunk < pExecMemAllocator->cChunks);
1216 pv = pHdr;
1217
1218 /* Adjust and align the size to cover the whole allocation area. */
1219 cb = RT_ALIGN_Z(cb + sizeof(*pHdr), IEMEXECMEM_ALT_SUB_ALLOC_UNIT_SIZE);
1220#endif
1221
1222 /* Free it / assert sanity. */
1223 bool fFound = false;
1224 uint32_t const cbChunk = pExecMemAllocator->cbChunk;
1225#ifndef IEMEXECMEM_ALT_SUB_WITH_ALLOC_HEADER
1226 uint32_t const cChunks = pExecMemAllocator->cChunks;
1227 for (uint32_t idxChunk = 0; idxChunk < cChunks; idxChunk++)
1228#endif
1229 {
1230 uintptr_t const offChunk = (uintptr_t)pv - (uintptr_t)pExecMemAllocator->aChunks[idxChunk].pvChunkRx;
1231 fFound = offChunk < cbChunk;
1232 if (fFound)
1233 {
1234 uint32_t const idxFirst = (uint32_t)offChunk >> IEMEXECMEM_ALT_SUB_ALLOC_UNIT_SHIFT;
1235 uint32_t const cReqUnits = (uint32_t)cb >> IEMEXECMEM_ALT_SUB_ALLOC_UNIT_SHIFT;
1236
1237 /* Check that it's valid and free it. */
1238 uint64_t * const pbmAlloc = &pExecMemAllocator->pbmAlloc[pExecMemAllocator->cBitmapElementsPerChunk * idxChunk];
1239 AssertReturnVoid(ASMBitTest(pbmAlloc, idxFirst));
1240 for (uint32_t i = 1; i < cReqUnits; i++)
1241 AssertReturnVoid(ASMBitTest(pbmAlloc, idxFirst + i));
1242 ASMBitClearRange(pbmAlloc, idxFirst, idxFirst + cReqUnits);
1243
1244 /* Invalidate the header using the writeable memory view. */
1245 pHdr = (PIEMEXECMEMALLOCHDR)((uintptr_t)pExecMemAllocator->aChunks[idxChunk].pvChunkRw + offChunk);
1246#ifdef IEMEXECMEM_ALT_SUB_WITH_ALLOC_HEADER
1247 pHdr->uMagic = 0;
1248 pHdr->idxChunk = 0;
1249 pHdr->pTb = NULL;
1250#endif
1251 pExecMemAllocator->aChunks[idxChunk].cFreeUnits += cReqUnits;
1252 pExecMemAllocator->aChunks[idxChunk].idxFreeHint = idxFirst;
1253
1254 /* Update the stats. */
1255 pExecMemAllocator->cbAllocated -= cb;
1256 pExecMemAllocator->cbFree += cb;
1257 pExecMemAllocator->cAllocations -= 1;
1258#ifdef VBOX_WITH_STATISTICS
1259 pExecMemAllocator->cbUnusable -= (cReqUnits << IEMEXECMEM_ALT_SUB_ALLOC_UNIT_SHIFT) - cbOrig;
1260#endif
1261 return;
1262 }
1263 }
1264 AssertFailed();
1265}
1266
1267
1268/**
1269 * Interface used by iemNativeRecompileAttachExecMemChunkCtx and unwind info
1270 * generators.
1271 */
1272DECLHIDDEN(PIEMNATIVEINSTR)
1273iemExecMemAllocatorAllocFromChunk(PVMCPU pVCpu, uint32_t idxChunk, uint32_t cbReq, PIEMNATIVEINSTR *ppaExec)
1274{
1275 PIEMEXECMEMALLOCATOR pExecMemAllocator = pVCpu->iem.s.pExecMemAllocatorR3;
1276 AssertReturn(idxChunk < pExecMemAllocator->cChunks, NULL);
1277 Assert(cbReq < _1M);
1278 return iemExecMemAllocatorAllocBytesInChunk(pExecMemAllocator, idxChunk, cbReq, ppaExec);
1279}
1280
1281
1282/**
1283 * For getting the per-chunk context detailing common code for a TB.
1284 *
1285 * This is for use by the disassembler.
1286 */
1287DECLHIDDEN(PCIEMNATIVEPERCHUNKCTX) iemExecMemGetTbChunkCtx(PVMCPU pVCpu, PCIEMTB pTb)
1288{
1289 PIEMEXECMEMALLOCATOR pExecMemAllocator = pVCpu->iem.s.pExecMemAllocatorR3;
1290 if ((pTb->fFlags & IEMTB_F_TYPE_MASK) == IEMTB_F_TYPE_NATIVE)
1291 {
1292 uintptr_t const uAddress = (uintptr_t)pTb->Native.paInstructions;
1293 uint32_t const cbChunk = pExecMemAllocator->cbChunk;
1294 uint32_t idxChunk = pExecMemAllocator->cChunks;
1295 while (idxChunk-- > 0)
1296 if (uAddress - (uintptr_t)pExecMemAllocator->aChunks[idxChunk].pvChunkRx < cbChunk)
1297 return pExecMemAllocator->aChunks[idxChunk].pCtx;
1298 }
1299 return NULL;
1300}
1301
1302
1303#ifdef IN_RING3
1304# ifdef RT_OS_WINDOWS
1305
1306/**
1307 * Initializes the unwind info structures for windows hosts.
1308 */
1309static int
1310iemExecMemAllocatorInitAndRegisterUnwindInfoForChunk(PVMCPUCC pVCpu, PIEMEXECMEMALLOCATOR pExecMemAllocator,
1311 void *pvChunk, uint32_t idxChunk)
1312{
1313 RT_NOREF(pVCpu);
1314
1315 /*
1316 * The AMD64 unwind opcodes.
1317 *
1318 * This is a program that starts with RSP after a RET instruction that
1319 * ends up in recompiled code, and the operations we describe here will
1320 * restore all non-volatile registers and bring RSP back to where our
1321 * RET address is. This means it's reverse order from what happens in
1322 * the prologue.
1323 *
1324 * Note! Using a frame register approach here both because we have one
1325 * and but mainly because the UWOP_ALLOC_LARGE argument values
1326 * would be a pain to write initializers for. On the positive
1327 * side, we're impervious to changes in the the stack variable
1328 * area can can deal with dynamic stack allocations if necessary.
1329 */
1330 static const IMAGE_UNWIND_CODE s_aOpcodes[] =
1331 {
1332 { { 16, IMAGE_AMD64_UWOP_SET_FPREG, 0 } }, /* RSP = RBP - FrameOffset * 10 (0x60) */
1333 { { 16, IMAGE_AMD64_UWOP_ALLOC_SMALL, 0 } }, /* RSP += 8; */
1334 { { 14, IMAGE_AMD64_UWOP_PUSH_NONVOL, X86_GREG_x15 } }, /* R15 = [RSP]; RSP += 8; */
1335 { { 12, IMAGE_AMD64_UWOP_PUSH_NONVOL, X86_GREG_x14 } }, /* R14 = [RSP]; RSP += 8; */
1336 { { 10, IMAGE_AMD64_UWOP_PUSH_NONVOL, X86_GREG_x13 } }, /* R13 = [RSP]; RSP += 8; */
1337 { { 8, IMAGE_AMD64_UWOP_PUSH_NONVOL, X86_GREG_x12 } }, /* R12 = [RSP]; RSP += 8; */
1338 { { 7, IMAGE_AMD64_UWOP_PUSH_NONVOL, X86_GREG_xDI } }, /* RDI = [RSP]; RSP += 8; */
1339 { { 6, IMAGE_AMD64_UWOP_PUSH_NONVOL, X86_GREG_xSI } }, /* RSI = [RSP]; RSP += 8; */
1340 { { 5, IMAGE_AMD64_UWOP_PUSH_NONVOL, X86_GREG_xBX } }, /* RBX = [RSP]; RSP += 8; */
1341 { { 4, IMAGE_AMD64_UWOP_PUSH_NONVOL, X86_GREG_xBP } }, /* RBP = [RSP]; RSP += 8; */
1342 };
1343 union
1344 {
1345 IMAGE_UNWIND_INFO Info;
1346 uint8_t abPadding[RT_UOFFSETOF(IMAGE_UNWIND_INFO, aOpcodes) + 16];
1347 } s_UnwindInfo =
1348 {
1349 {
1350 /* .Version = */ 1,
1351 /* .Flags = */ 0,
1352 /* .SizeOfProlog = */ 16, /* whatever */
1353 /* .CountOfCodes = */ RT_ELEMENTS(s_aOpcodes),
1354 /* .FrameRegister = */ X86_GREG_xBP,
1355 /* .FrameOffset = */ (-IEMNATIVE_FP_OFF_LAST_PUSH + 8) / 16 /* we're off by one slot. sigh. */,
1356 }
1357 };
1358 AssertCompile(-IEMNATIVE_FP_OFF_LAST_PUSH < 240 && -IEMNATIVE_FP_OFF_LAST_PUSH > 0);
1359 AssertCompile((-IEMNATIVE_FP_OFF_LAST_PUSH & 0xf) == 8);
1360
1361 /*
1362 * Calc how much space we need and allocate it off the exec heap.
1363 */
1364 unsigned const cFunctionEntries = 1;
1365 unsigned const cbUnwindInfo = sizeof(s_aOpcodes) + RT_UOFFSETOF(IMAGE_UNWIND_INFO, aOpcodes);
1366 unsigned const cbNeeded = sizeof(IMAGE_RUNTIME_FUNCTION_ENTRY) * cFunctionEntries + cbUnwindInfo;
1367 PIMAGE_RUNTIME_FUNCTION_ENTRY const paFunctions
1368 = (PIMAGE_RUNTIME_FUNCTION_ENTRY)iemExecMemAllocatorAllocBytesInChunk(pExecMemAllocator, idxChunk, cbNeeded, NULL);
1369 AssertReturn(paFunctions, VERR_INTERNAL_ERROR_5);
1370 pExecMemAllocator->aChunks[idxChunk].pvUnwindInfo = paFunctions;
1371
1372 /*
1373 * Initialize the structures.
1374 */
1375 PIMAGE_UNWIND_INFO const pInfo = (PIMAGE_UNWIND_INFO)&paFunctions[cFunctionEntries];
1376
1377 paFunctions[0].BeginAddress = 0;
1378 paFunctions[0].EndAddress = pExecMemAllocator->cbChunk;
1379 paFunctions[0].UnwindInfoAddress = (uint32_t)((uintptr_t)pInfo - (uintptr_t)pvChunk);
1380
1381 memcpy(pInfo, &s_UnwindInfo, RT_UOFFSETOF(IMAGE_UNWIND_INFO, aOpcodes));
1382 memcpy(&pInfo->aOpcodes[0], s_aOpcodes, sizeof(s_aOpcodes));
1383
1384 /*
1385 * Register it.
1386 */
1387 uint8_t fRet = RtlAddFunctionTable(paFunctions, cFunctionEntries, (uintptr_t)pvChunk);
1388 AssertReturn(fRet, VERR_INTERNAL_ERROR_3); /* Nothing to clean up on failure, since its within the chunk itself. */
1389
1390 return VINF_SUCCESS;
1391}
1392
1393
1394# else /* !RT_OS_WINDOWS */
1395
1396/**
1397 * Emits a LEB128 encoded value between -0x2000 and 0x2000 (both exclusive).
1398 */
1399DECLINLINE(RTPTRUNION) iemDwarfPutLeb128(RTPTRUNION Ptr, int32_t iValue)
1400{
1401 if (iValue >= 64)
1402 {
1403 Assert(iValue < 0x2000);
1404 *Ptr.pb++ = ((uint8_t)iValue & 0x7f) | 0x80;
1405 *Ptr.pb++ = (uint8_t)(iValue >> 7) & 0x3f;
1406 }
1407 else if (iValue >= 0)
1408 *Ptr.pb++ = (uint8_t)iValue;
1409 else if (iValue > -64)
1410 *Ptr.pb++ = ((uint8_t)iValue & 0x3f) | 0x40;
1411 else
1412 {
1413 Assert(iValue > -0x2000);
1414 *Ptr.pb++ = ((uint8_t)iValue & 0x7f) | 0x80;
1415 *Ptr.pb++ = ((uint8_t)(iValue >> 7) & 0x3f) | 0x40;
1416 }
1417 return Ptr;
1418}
1419
1420
1421/**
1422 * Emits an ULEB128 encoded value (up to 64-bit wide).
1423 */
1424DECLINLINE(RTPTRUNION) iemDwarfPutUleb128(RTPTRUNION Ptr, uint64_t uValue)
1425{
1426 while (uValue >= 0x80)
1427 {
1428 *Ptr.pb++ = ((uint8_t)uValue & 0x7f) | 0x80;
1429 uValue >>= 7;
1430 }
1431 *Ptr.pb++ = (uint8_t)uValue;
1432 return Ptr;
1433}
1434
1435
1436/**
1437 * Emits a CFA rule as register @a uReg + offset @a off.
1438 */
1439DECLINLINE(RTPTRUNION) iemDwarfPutCfaDefCfa(RTPTRUNION Ptr, uint32_t uReg, uint32_t off)
1440{
1441 *Ptr.pb++ = DW_CFA_def_cfa;
1442 Ptr = iemDwarfPutUleb128(Ptr, uReg);
1443 Ptr = iemDwarfPutUleb128(Ptr, off);
1444 return Ptr;
1445}
1446
1447
1448/**
1449 * Emits a register (@a uReg) save location:
1450 * CFA + @a off * data_alignment_factor
1451 */
1452DECLINLINE(RTPTRUNION) iemDwarfPutCfaOffset(RTPTRUNION Ptr, uint32_t uReg, uint32_t off)
1453{
1454 if (uReg < 0x40)
1455 *Ptr.pb++ = DW_CFA_offset | uReg;
1456 else
1457 {
1458 *Ptr.pb++ = DW_CFA_offset_extended;
1459 Ptr = iemDwarfPutUleb128(Ptr, uReg);
1460 }
1461 Ptr = iemDwarfPutUleb128(Ptr, off);
1462 return Ptr;
1463}
1464
1465
1466# if 0 /* unused */
1467/**
1468 * Emits a register (@a uReg) save location, using signed offset:
1469 * CFA + @a offSigned * data_alignment_factor
1470 */
1471DECLINLINE(RTPTRUNION) iemDwarfPutCfaSignedOffset(RTPTRUNION Ptr, uint32_t uReg, int32_t offSigned)
1472{
1473 *Ptr.pb++ = DW_CFA_offset_extended_sf;
1474 Ptr = iemDwarfPutUleb128(Ptr, uReg);
1475 Ptr = iemDwarfPutLeb128(Ptr, offSigned);
1476 return Ptr;
1477}
1478# endif
1479
1480
1481/**
1482 * Initializes the unwind info section for non-windows hosts.
1483 */
1484static int
1485iemExecMemAllocatorInitAndRegisterUnwindInfoForChunk(PVMCPUCC pVCpu, PIEMEXECMEMALLOCATOR pExecMemAllocator,
1486 void *pvChunk, uint32_t idxChunk)
1487{
1488 PIEMEXECMEMCHUNKEHFRAME const pEhFrame = &pExecMemAllocator->paEhFrames[idxChunk];
1489 pExecMemAllocator->aChunks[idxChunk].pvUnwindInfo = pEhFrame; /* not necessary, but whatever */
1490
1491 RTPTRUNION Ptr = { pEhFrame->abEhFrame };
1492
1493 /*
1494 * Generate the CIE first.
1495 */
1496# ifdef IEMNATIVE_USE_LIBUNWIND /* libunwind (llvm, darwin) only supports v1 and v3. */
1497 uint8_t const iDwarfVer = 3;
1498# else
1499 uint8_t const iDwarfVer = 4;
1500# endif
1501 RTPTRUNION const PtrCie = Ptr;
1502 *Ptr.pu32++ = 123; /* The CIE length will be determined later. */
1503 *Ptr.pu32++ = 0 /*UINT32_MAX*/; /* I'm a CIE in .eh_frame speak. */
1504 *Ptr.pb++ = iDwarfVer; /* DwARF version */
1505 *Ptr.pb++ = 0; /* Augmentation. */
1506 if (iDwarfVer >= 4)
1507 {
1508 *Ptr.pb++ = sizeof(uintptr_t); /* Address size. */
1509 *Ptr.pb++ = 0; /* Segment selector size. */
1510 }
1511# ifdef RT_ARCH_AMD64
1512 Ptr = iemDwarfPutLeb128(Ptr, 1); /* Code alignment factor (LEB128 = 1). */
1513# else
1514 Ptr = iemDwarfPutLeb128(Ptr, 4); /* Code alignment factor (LEB128 = 4). */
1515# endif
1516 Ptr = iemDwarfPutLeb128(Ptr, -8); /* Data alignment factor (LEB128 = -8). */
1517# ifdef RT_ARCH_AMD64
1518 Ptr = iemDwarfPutUleb128(Ptr, DWREG_AMD64_RA); /* Return address column (ULEB128) */
1519# elif defined(RT_ARCH_ARM64)
1520 Ptr = iemDwarfPutUleb128(Ptr, DWREG_ARM64_LR); /* Return address column (ULEB128) */
1521# else
1522# error "port me"
1523# endif
1524 /* Initial instructions: */
1525# ifdef RT_ARCH_AMD64
1526 Ptr = iemDwarfPutCfaDefCfa(Ptr, DWREG_AMD64_RBP, 16); /* CFA = RBP + 0x10 - first stack parameter */
1527 Ptr = iemDwarfPutCfaOffset(Ptr, DWREG_AMD64_RA, 1); /* Ret RIP = [CFA + 1*-8] */
1528 Ptr = iemDwarfPutCfaOffset(Ptr, DWREG_AMD64_RBP, 2); /* RBP = [CFA + 2*-8] */
1529 Ptr = iemDwarfPutCfaOffset(Ptr, DWREG_AMD64_RBX, 3); /* RBX = [CFA + 3*-8] */
1530 Ptr = iemDwarfPutCfaOffset(Ptr, DWREG_AMD64_R12, 4); /* R12 = [CFA + 4*-8] */
1531 Ptr = iemDwarfPutCfaOffset(Ptr, DWREG_AMD64_R13, 5); /* R13 = [CFA + 5*-8] */
1532 Ptr = iemDwarfPutCfaOffset(Ptr, DWREG_AMD64_R14, 6); /* R14 = [CFA + 6*-8] */
1533 Ptr = iemDwarfPutCfaOffset(Ptr, DWREG_AMD64_R15, 7); /* R15 = [CFA + 7*-8] */
1534# elif defined(RT_ARCH_ARM64)
1535# if 1
1536 Ptr = iemDwarfPutCfaDefCfa(Ptr, DWREG_ARM64_BP, 16); /* CFA = BP + 0x10 - first stack parameter */
1537# else
1538 Ptr = iemDwarfPutCfaDefCfa(Ptr, DWREG_ARM64_SP, IEMNATIVE_FRAME_VAR_SIZE + IEMNATIVE_FRAME_SAVE_REG_SIZE);
1539# endif
1540 Ptr = iemDwarfPutCfaOffset(Ptr, DWREG_ARM64_LR, 1); /* Ret PC = [CFA + 1*-8] */
1541 Ptr = iemDwarfPutCfaOffset(Ptr, DWREG_ARM64_BP, 2); /* Ret BP = [CFA + 2*-8] */
1542 Ptr = iemDwarfPutCfaOffset(Ptr, DWREG_ARM64_X28, 3); /* X28 = [CFA + 3*-8] */
1543 Ptr = iemDwarfPutCfaOffset(Ptr, DWREG_ARM64_X27, 4); /* X27 = [CFA + 4*-8] */
1544 Ptr = iemDwarfPutCfaOffset(Ptr, DWREG_ARM64_X26, 5); /* X26 = [CFA + 5*-8] */
1545 Ptr = iemDwarfPutCfaOffset(Ptr, DWREG_ARM64_X25, 6); /* X25 = [CFA + 6*-8] */
1546 Ptr = iemDwarfPutCfaOffset(Ptr, DWREG_ARM64_X24, 7); /* X24 = [CFA + 7*-8] */
1547 Ptr = iemDwarfPutCfaOffset(Ptr, DWREG_ARM64_X23, 8); /* X23 = [CFA + 8*-8] */
1548 Ptr = iemDwarfPutCfaOffset(Ptr, DWREG_ARM64_X22, 9); /* X22 = [CFA + 9*-8] */
1549 Ptr = iemDwarfPutCfaOffset(Ptr, DWREG_ARM64_X21, 10); /* X21 = [CFA +10*-8] */
1550 Ptr = iemDwarfPutCfaOffset(Ptr, DWREG_ARM64_X20, 11); /* X20 = [CFA +11*-8] */
1551 Ptr = iemDwarfPutCfaOffset(Ptr, DWREG_ARM64_X19, 12); /* X19 = [CFA +12*-8] */
1552 AssertCompile(IEMNATIVE_FRAME_SAVE_REG_SIZE / 8 == 12);
1553 /** @todo we we need to do something about clearing DWREG_ARM64_RA_SIGN_STATE or something? */
1554# else
1555# error "port me"
1556# endif
1557 while ((Ptr.u - PtrCie.u) & 3)
1558 *Ptr.pb++ = DW_CFA_nop;
1559 /* Finalize the CIE size. */
1560 *PtrCie.pu32 = Ptr.u - PtrCie.u - sizeof(uint32_t);
1561
1562 /*
1563 * Generate an FDE for the whole chunk area.
1564 */
1565# ifdef IEMNATIVE_USE_LIBUNWIND
1566 pEhFrame->offFda = Ptr.u - (uintptr_t)&pEhFrame->abEhFrame[0];
1567# endif
1568 RTPTRUNION const PtrFde = Ptr;
1569 *Ptr.pu32++ = 123; /* The CIE length will be determined later. */
1570 *Ptr.pu32 = Ptr.u - PtrCie.u; /* Negated self relative CIE address. */
1571 Ptr.pu32++;
1572 *Ptr.pu64++ = (uintptr_t)pvChunk; /* Absolute start PC of this FDE. */
1573 *Ptr.pu64++ = pExecMemAllocator->cbChunk; /* PC range length for this PDE. */
1574# if 0 /* not requried for recent libunwind.dylib nor recent libgcc/glib. */
1575 *Ptr.pb++ = DW_CFA_nop;
1576# endif
1577 while ((Ptr.u - PtrFde.u) & 3)
1578 *Ptr.pb++ = DW_CFA_nop;
1579 /* Finalize the FDE size. */
1580 *PtrFde.pu32 = Ptr.u - PtrFde.u - sizeof(uint32_t);
1581
1582 /* Terminator entry. */
1583 *Ptr.pu32++ = 0;
1584 *Ptr.pu32++ = 0; /* just to be sure... */
1585 Assert(Ptr.u - (uintptr_t)&pEhFrame->abEhFrame[0] <= sizeof(pEhFrame->abEhFrame));
1586
1587 /*
1588 * Register it.
1589 */
1590# ifdef IEMNATIVE_USE_LIBUNWIND
1591 __register_frame(&pEhFrame->abEhFrame[pEhFrame->offFda]);
1592# else
1593 memset(pEhFrame->abObject, 0xf6, sizeof(pEhFrame->abObject)); /* color the memory to better spot usage */
1594 __register_frame_info(pEhFrame->abEhFrame, pEhFrame->abObject);
1595# endif
1596
1597# ifdef IEMNATIVE_USE_GDB_JIT
1598 /*
1599 * Now for telling GDB about this (experimental).
1600 *
1601 * This seems to work best with ET_DYN.
1602 */
1603 GDBJITSYMFILE * const pSymFile = (GDBJITSYMFILE *)iemExecMemAllocatorAllocBytesInChunk(pExecMemAllocator, idxChunk,
1604 sizeof(GDBJITSYMFILE), NULL);
1605 AssertReturn(pSymFile, VERR_INTERNAL_ERROR_5);
1606 unsigned const offSymFileInChunk = (uintptr_t)pSymFile - (uintptr_t)pvChunk;
1607
1608 RT_ZERO(*pSymFile);
1609
1610 /*
1611 * The ELF header:
1612 */
1613 pSymFile->EHdr.e_ident[0] = ELFMAG0;
1614 pSymFile->EHdr.e_ident[1] = ELFMAG1;
1615 pSymFile->EHdr.e_ident[2] = ELFMAG2;
1616 pSymFile->EHdr.e_ident[3] = ELFMAG3;
1617 pSymFile->EHdr.e_ident[EI_VERSION] = EV_CURRENT;
1618 pSymFile->EHdr.e_ident[EI_CLASS] = ELFCLASS64;
1619 pSymFile->EHdr.e_ident[EI_DATA] = ELFDATA2LSB;
1620 pSymFile->EHdr.e_ident[EI_OSABI] = ELFOSABI_NONE;
1621# ifdef IEMNATIVE_USE_GDB_JIT_ET_DYN
1622 pSymFile->EHdr.e_type = ET_DYN;
1623# else
1624 pSymFile->EHdr.e_type = ET_REL;
1625# endif
1626# ifdef RT_ARCH_AMD64
1627 pSymFile->EHdr.e_machine = EM_AMD64;
1628# elif defined(RT_ARCH_ARM64)
1629 pSymFile->EHdr.e_machine = EM_AARCH64;
1630# else
1631# error "port me"
1632# endif
1633 pSymFile->EHdr.e_version = 1; /*?*/
1634 pSymFile->EHdr.e_entry = 0;
1635# if defined(IEMNATIVE_USE_GDB_JIT_ET_DYN)
1636 pSymFile->EHdr.e_phoff = RT_UOFFSETOF(GDBJITSYMFILE, aPhdrs);
1637# else
1638 pSymFile->EHdr.e_phoff = 0;
1639# endif
1640 pSymFile->EHdr.e_shoff = sizeof(pSymFile->EHdr);
1641 pSymFile->EHdr.e_flags = 0;
1642 pSymFile->EHdr.e_ehsize = sizeof(pSymFile->EHdr);
1643# if defined(IEMNATIVE_USE_GDB_JIT_ET_DYN)
1644 pSymFile->EHdr.e_phentsize = sizeof(pSymFile->aPhdrs[0]);
1645 pSymFile->EHdr.e_phnum = RT_ELEMENTS(pSymFile->aPhdrs);
1646# else
1647 pSymFile->EHdr.e_phentsize = 0;
1648 pSymFile->EHdr.e_phnum = 0;
1649# endif
1650 pSymFile->EHdr.e_shentsize = sizeof(pSymFile->aShdrs[0]);
1651 pSymFile->EHdr.e_shnum = RT_ELEMENTS(pSymFile->aShdrs);
1652 pSymFile->EHdr.e_shstrndx = 0; /* set later */
1653
1654 uint32_t offStrTab = 0;
1655#define APPEND_STR(a_szStr) do { \
1656 memcpy(&pSymFile->szzStrTab[offStrTab], a_szStr, sizeof(a_szStr)); \
1657 offStrTab += sizeof(a_szStr); \
1658 Assert(offStrTab < sizeof(pSymFile->szzStrTab)); \
1659 } while (0)
1660#define APPEND_STR_FMT(a_szStr, ...) do { \
1661 offStrTab += RTStrPrintf(&pSymFile->szzStrTab[offStrTab], sizeof(pSymFile->szzStrTab) - offStrTab, a_szStr, __VA_ARGS__); \
1662 offStrTab++; \
1663 Assert(offStrTab < sizeof(pSymFile->szzStrTab)); \
1664 } while (0)
1665
1666 /*
1667 * Section headers.
1668 */
1669 /* Section header #0: NULL */
1670 unsigned i = 0;
1671 APPEND_STR("");
1672 RT_ZERO(pSymFile->aShdrs[i]);
1673 i++;
1674
1675 /* Section header: .eh_frame */
1676 pSymFile->aShdrs[i].sh_name = offStrTab;
1677 APPEND_STR(".eh_frame");
1678 pSymFile->aShdrs[i].sh_type = SHT_PROGBITS;
1679 pSymFile->aShdrs[i].sh_flags = SHF_ALLOC | SHF_EXECINSTR;
1680# if defined(IEMNATIVE_USE_GDB_JIT_ET_DYN) || defined(IEMNATIVE_USE_GDB_JIT_ELF_RVAS)
1681 pSymFile->aShdrs[i].sh_offset
1682 = pSymFile->aShdrs[i].sh_addr = RT_UOFFSETOF(GDBJITSYMFILE, abEhFrame);
1683# else
1684 pSymFile->aShdrs[i].sh_addr = (uintptr_t)&pSymFile->abEhFrame[0];
1685 pSymFile->aShdrs[i].sh_offset = 0;
1686# endif
1687
1688 pSymFile->aShdrs[i].sh_size = sizeof(pEhFrame->abEhFrame);
1689 pSymFile->aShdrs[i].sh_link = 0;
1690 pSymFile->aShdrs[i].sh_info = 0;
1691 pSymFile->aShdrs[i].sh_addralign = 1;
1692 pSymFile->aShdrs[i].sh_entsize = 0;
1693 memcpy(pSymFile->abEhFrame, pEhFrame->abEhFrame, sizeof(pEhFrame->abEhFrame));
1694 i++;
1695
1696 /* Section header: .shstrtab */
1697 unsigned const iShStrTab = i;
1698 pSymFile->EHdr.e_shstrndx = iShStrTab;
1699 pSymFile->aShdrs[i].sh_name = offStrTab;
1700 APPEND_STR(".shstrtab");
1701 pSymFile->aShdrs[i].sh_type = SHT_STRTAB;
1702 pSymFile->aShdrs[i].sh_flags = SHF_ALLOC;
1703# if defined(IEMNATIVE_USE_GDB_JIT_ET_DYN) || defined(IEMNATIVE_USE_GDB_JIT_ELF_RVAS)
1704 pSymFile->aShdrs[i].sh_offset
1705 = pSymFile->aShdrs[i].sh_addr = RT_UOFFSETOF(GDBJITSYMFILE, szzStrTab);
1706# else
1707 pSymFile->aShdrs[i].sh_addr = (uintptr_t)&pSymFile->szzStrTab[0];
1708 pSymFile->aShdrs[i].sh_offset = 0;
1709# endif
1710 pSymFile->aShdrs[i].sh_size = sizeof(pSymFile->szzStrTab);
1711 pSymFile->aShdrs[i].sh_link = 0;
1712 pSymFile->aShdrs[i].sh_info = 0;
1713 pSymFile->aShdrs[i].sh_addralign = 1;
1714 pSymFile->aShdrs[i].sh_entsize = 0;
1715 i++;
1716
1717 /* Section header: .symbols */
1718 pSymFile->aShdrs[i].sh_name = offStrTab;
1719 APPEND_STR(".symtab");
1720 pSymFile->aShdrs[i].sh_type = SHT_SYMTAB;
1721 pSymFile->aShdrs[i].sh_flags = SHF_ALLOC;
1722 pSymFile->aShdrs[i].sh_offset
1723 = pSymFile->aShdrs[i].sh_addr = RT_UOFFSETOF(GDBJITSYMFILE, aSymbols);
1724 pSymFile->aShdrs[i].sh_size = sizeof(pSymFile->aSymbols);
1725 pSymFile->aShdrs[i].sh_link = iShStrTab;
1726 pSymFile->aShdrs[i].sh_info = RT_ELEMENTS(pSymFile->aSymbols);
1727 pSymFile->aShdrs[i].sh_addralign = sizeof(pSymFile->aSymbols[0].st_value);
1728 pSymFile->aShdrs[i].sh_entsize = sizeof(pSymFile->aSymbols[0]);
1729 i++;
1730
1731# if defined(IEMNATIVE_USE_GDB_JIT_ET_DYN)
1732 /* Section header: .symbols */
1733 pSymFile->aShdrs[i].sh_name = offStrTab;
1734 APPEND_STR(".dynsym");
1735 pSymFile->aShdrs[i].sh_type = SHT_DYNSYM;
1736 pSymFile->aShdrs[i].sh_flags = SHF_ALLOC;
1737 pSymFile->aShdrs[i].sh_offset
1738 = pSymFile->aShdrs[i].sh_addr = RT_UOFFSETOF(GDBJITSYMFILE, aDynSyms);
1739 pSymFile->aShdrs[i].sh_size = sizeof(pSymFile->aDynSyms);
1740 pSymFile->aShdrs[i].sh_link = iShStrTab;
1741 pSymFile->aShdrs[i].sh_info = RT_ELEMENTS(pSymFile->aDynSyms);
1742 pSymFile->aShdrs[i].sh_addralign = sizeof(pSymFile->aDynSyms[0].st_value);
1743 pSymFile->aShdrs[i].sh_entsize = sizeof(pSymFile->aDynSyms[0]);
1744 i++;
1745# endif
1746
1747# if defined(IEMNATIVE_USE_GDB_JIT_ET_DYN)
1748 /* Section header: .dynamic */
1749 pSymFile->aShdrs[i].sh_name = offStrTab;
1750 APPEND_STR(".dynamic");
1751 pSymFile->aShdrs[i].sh_type = SHT_DYNAMIC;
1752 pSymFile->aShdrs[i].sh_flags = SHF_ALLOC;
1753 pSymFile->aShdrs[i].sh_offset
1754 = pSymFile->aShdrs[i].sh_addr = RT_UOFFSETOF(GDBJITSYMFILE, aDyn);
1755 pSymFile->aShdrs[i].sh_size = sizeof(pSymFile->aDyn);
1756 pSymFile->aShdrs[i].sh_link = iShStrTab;
1757 pSymFile->aShdrs[i].sh_info = 0;
1758 pSymFile->aShdrs[i].sh_addralign = 1;
1759 pSymFile->aShdrs[i].sh_entsize = sizeof(pSymFile->aDyn[0]);
1760 i++;
1761# endif
1762
1763 /* Section header: .text */
1764 unsigned const iShText = i;
1765 pSymFile->aShdrs[i].sh_name = offStrTab;
1766 APPEND_STR(".text");
1767 pSymFile->aShdrs[i].sh_type = SHT_PROGBITS;
1768 pSymFile->aShdrs[i].sh_flags = SHF_ALLOC | SHF_EXECINSTR;
1769# if defined(IEMNATIVE_USE_GDB_JIT_ET_DYN) || defined(IEMNATIVE_USE_GDB_JIT_ELF_RVAS)
1770 pSymFile->aShdrs[i].sh_offset
1771 = pSymFile->aShdrs[i].sh_addr = sizeof(GDBJITSYMFILE);
1772# else
1773 pSymFile->aShdrs[i].sh_addr = (uintptr_t)(pSymFile + 1);
1774 pSymFile->aShdrs[i].sh_offset = 0;
1775# endif
1776 pSymFile->aShdrs[i].sh_size = pExecMemAllocator->cbChunk - offSymFileInChunk - sizeof(GDBJITSYMFILE);
1777 pSymFile->aShdrs[i].sh_link = 0;
1778 pSymFile->aShdrs[i].sh_info = 0;
1779 pSymFile->aShdrs[i].sh_addralign = 1;
1780 pSymFile->aShdrs[i].sh_entsize = 0;
1781 i++;
1782
1783 Assert(i == RT_ELEMENTS(pSymFile->aShdrs));
1784
1785# if defined(IEMNATIVE_USE_GDB_JIT_ET_DYN)
1786 /*
1787 * The program headers:
1788 */
1789 /* Everything in a single LOAD segment: */
1790 i = 0;
1791 pSymFile->aPhdrs[i].p_type = PT_LOAD;
1792 pSymFile->aPhdrs[i].p_flags = PF_X | PF_R;
1793 pSymFile->aPhdrs[i].p_offset
1794 = pSymFile->aPhdrs[i].p_vaddr
1795 = pSymFile->aPhdrs[i].p_paddr = 0;
1796 pSymFile->aPhdrs[i].p_filesz /* Size of segment in file. */
1797 = pSymFile->aPhdrs[i].p_memsz = pExecMemAllocator->cbChunk - offSymFileInChunk;
1798 pSymFile->aPhdrs[i].p_align = HOST_PAGE_SIZE;
1799 i++;
1800 /* The .dynamic segment. */
1801 pSymFile->aPhdrs[i].p_type = PT_DYNAMIC;
1802 pSymFile->aPhdrs[i].p_flags = PF_R;
1803 pSymFile->aPhdrs[i].p_offset
1804 = pSymFile->aPhdrs[i].p_vaddr
1805 = pSymFile->aPhdrs[i].p_paddr = RT_UOFFSETOF(GDBJITSYMFILE, aDyn);
1806 pSymFile->aPhdrs[i].p_filesz /* Size of segment in file. */
1807 = pSymFile->aPhdrs[i].p_memsz = sizeof(pSymFile->aDyn);
1808 pSymFile->aPhdrs[i].p_align = sizeof(pSymFile->aDyn[0].d_tag);
1809 i++;
1810
1811 Assert(i == RT_ELEMENTS(pSymFile->aPhdrs));
1812
1813 /*
1814 * The dynamic section:
1815 */
1816 i = 0;
1817 pSymFile->aDyn[i].d_tag = DT_SONAME;
1818 pSymFile->aDyn[i].d_un.d_val = offStrTab;
1819 APPEND_STR_FMT("iem-exec-chunk-%u-%u", pVCpu->idCpu, idxChunk);
1820 i++;
1821 pSymFile->aDyn[i].d_tag = DT_STRTAB;
1822 pSymFile->aDyn[i].d_un.d_ptr = RT_UOFFSETOF(GDBJITSYMFILE, szzStrTab);
1823 i++;
1824 pSymFile->aDyn[i].d_tag = DT_STRSZ;
1825 pSymFile->aDyn[i].d_un.d_val = sizeof(pSymFile->szzStrTab);
1826 i++;
1827 pSymFile->aDyn[i].d_tag = DT_SYMTAB;
1828 pSymFile->aDyn[i].d_un.d_ptr = RT_UOFFSETOF(GDBJITSYMFILE, aDynSyms);
1829 i++;
1830 pSymFile->aDyn[i].d_tag = DT_SYMENT;
1831 pSymFile->aDyn[i].d_un.d_val = sizeof(pSymFile->aDynSyms[0]);
1832 i++;
1833 pSymFile->aDyn[i].d_tag = DT_NULL;
1834 i++;
1835 Assert(i == RT_ELEMENTS(pSymFile->aDyn));
1836# endif /* IEMNATIVE_USE_GDB_JIT_ET_DYN */
1837
1838 /*
1839 * Symbol tables:
1840 */
1841 /** @todo gdb doesn't seem to really like this ... */
1842 i = 0;
1843 pSymFile->aSymbols[i].st_name = 0;
1844 pSymFile->aSymbols[i].st_shndx = SHN_UNDEF;
1845 pSymFile->aSymbols[i].st_value = 0;
1846 pSymFile->aSymbols[i].st_size = 0;
1847 pSymFile->aSymbols[i].st_info = ELF64_ST_INFO(STB_LOCAL, STT_NOTYPE);
1848 pSymFile->aSymbols[i].st_other = 0 /* STV_DEFAULT */;
1849# ifdef IEMNATIVE_USE_GDB_JIT_ET_DYN
1850 pSymFile->aDynSyms[0] = pSymFile->aSymbols[i];
1851# endif
1852 i++;
1853
1854 pSymFile->aSymbols[i].st_name = 0;
1855 pSymFile->aSymbols[i].st_shndx = SHN_ABS;
1856 pSymFile->aSymbols[i].st_value = 0;
1857 pSymFile->aSymbols[i].st_size = 0;
1858 pSymFile->aSymbols[i].st_info = ELF64_ST_INFO(STB_LOCAL, STT_FILE);
1859 pSymFile->aSymbols[i].st_other = 0 /* STV_DEFAULT */;
1860 i++;
1861
1862 pSymFile->aSymbols[i].st_name = offStrTab;
1863 APPEND_STR_FMT("iem_exec_chunk_%u_%u", pVCpu->idCpu, idxChunk);
1864# if 0
1865 pSymFile->aSymbols[i].st_shndx = iShText;
1866 pSymFile->aSymbols[i].st_value = 0;
1867# else
1868 pSymFile->aSymbols[i].st_shndx = SHN_ABS;
1869 pSymFile->aSymbols[i].st_value = (uintptr_t)(pSymFile + 1);
1870# endif
1871 pSymFile->aSymbols[i].st_size = pSymFile->aShdrs[iShText].sh_size;
1872 pSymFile->aSymbols[i].st_info = ELF64_ST_INFO(STB_GLOBAL, STT_FUNC);
1873 pSymFile->aSymbols[i].st_other = 0 /* STV_DEFAULT */;
1874# ifdef IEMNATIVE_USE_GDB_JIT_ET_DYN
1875 pSymFile->aDynSyms[1] = pSymFile->aSymbols[i];
1876 pSymFile->aDynSyms[1].st_value = (uintptr_t)(pSymFile + 1);
1877# endif
1878 i++;
1879
1880 Assert(i == RT_ELEMENTS(pSymFile->aSymbols));
1881 Assert(offStrTab < sizeof(pSymFile->szzStrTab));
1882
1883 /*
1884 * The GDB JIT entry and informing GDB.
1885 */
1886 pEhFrame->GdbJitEntry.pbSymFile = (uint8_t *)pSymFile;
1887# if 1
1888 pEhFrame->GdbJitEntry.cbSymFile = pExecMemAllocator->cbChunk - ((uintptr_t)pSymFile - (uintptr_t)pvChunk);
1889# else
1890 pEhFrame->GdbJitEntry.cbSymFile = sizeof(GDBJITSYMFILE);
1891# endif
1892
1893 RTOnce(&g_IemNativeGdbJitOnce, iemNativeGdbJitInitOnce, NULL);
1894 RTCritSectEnter(&g_IemNativeGdbJitLock);
1895 pEhFrame->GdbJitEntry.pNext = NULL;
1896 pEhFrame->GdbJitEntry.pPrev = __jit_debug_descriptor.pTail;
1897 if (__jit_debug_descriptor.pTail)
1898 __jit_debug_descriptor.pTail->pNext = &pEhFrame->GdbJitEntry;
1899 else
1900 __jit_debug_descriptor.pHead = &pEhFrame->GdbJitEntry;
1901 __jit_debug_descriptor.pTail = &pEhFrame->GdbJitEntry;
1902 __jit_debug_descriptor.pRelevant = &pEhFrame->GdbJitEntry;
1903
1904 /* Notify GDB: */
1905 __jit_debug_descriptor.enmAction = kGdbJitaction_Register;
1906 __jit_debug_register_code();
1907 __jit_debug_descriptor.enmAction = kGdbJitaction_NoAction;
1908 RTCritSectLeave(&g_IemNativeGdbJitLock);
1909
1910# else /* !IEMNATIVE_USE_GDB_JIT */
1911 RT_NOREF(pVCpu);
1912# endif /* !IEMNATIVE_USE_GDB_JIT */
1913
1914 return VINF_SUCCESS;
1915}
1916
1917# endif /* !RT_OS_WINDOWS */
1918#endif /* IN_RING3 */
1919
1920
1921/**
1922 * Adds another chunk to the executable memory allocator.
1923 *
1924 * This is used by the init code for the initial allocation and later by the
1925 * regular allocator function when it's out of memory.
1926 */
1927static int iemExecMemAllocatorGrow(PVMCPUCC pVCpu, PIEMEXECMEMALLOCATOR pExecMemAllocator)
1928{
1929 /* Check that we've room for growth. */
1930 uint32_t const idxChunk = pExecMemAllocator->cChunks;
1931 AssertLogRelReturn(idxChunk < pExecMemAllocator->cMaxChunks, VERR_OUT_OF_RESOURCES);
1932
1933 /* Allocate a chunk. */
1934#ifdef RT_OS_DARWIN
1935 void *pvChunk = RTMemPageAllocEx(pExecMemAllocator->cbChunk, 0);
1936#else
1937 void *pvChunk = RTMemPageAllocEx(pExecMemAllocator->cbChunk, RTMEMPAGEALLOC_F_EXECUTABLE);
1938#endif
1939 AssertLogRelReturn(pvChunk, VERR_NO_EXEC_MEMORY);
1940
1941#ifdef RT_OS_DARWIN
1942 /*
1943 * Because it is impossible to have a RWX memory allocation on macOS try to remap the memory
1944 * chunk readable/executable somewhere else so we can save us the hassle of switching between
1945 * protections when exeuctable memory is allocated.
1946 */
1947 int rc = VERR_NO_EXEC_MEMORY;
1948 mach_port_t hPortTask = mach_task_self();
1949 mach_vm_address_t AddrChunk = (mach_vm_address_t)pvChunk;
1950 mach_vm_address_t AddrRemapped = 0;
1951 vm_prot_t ProtCur = 0;
1952 vm_prot_t ProtMax = 0;
1953 kern_return_t krc = mach_vm_remap(hPortTask, &AddrRemapped, pExecMemAllocator->cbChunk, 0,
1954 VM_FLAGS_ANYWHERE | VM_FLAGS_RETURN_DATA_ADDR,
1955 hPortTask, AddrChunk, FALSE, &ProtCur, &ProtMax,
1956 VM_INHERIT_NONE);
1957 if (krc == KERN_SUCCESS)
1958 {
1959 krc = mach_vm_protect(mach_task_self(), AddrRemapped, pExecMemAllocator->cbChunk, FALSE, VM_PROT_READ | VM_PROT_EXECUTE);
1960 if (krc == KERN_SUCCESS)
1961 rc = VINF_SUCCESS;
1962 else
1963 {
1964 AssertLogRelMsgFailed(("mach_vm_protect -> %d (%#x)\n", krc, krc));
1965 krc = mach_vm_deallocate(hPortTask, AddrRemapped, pExecMemAllocator->cbChunk);
1966 Assert(krc == KERN_SUCCESS);
1967 }
1968 }
1969 else
1970 AssertLogRelMsgFailed(("mach_vm_remap -> %d (%#x)\n", krc, krc));
1971 if (RT_FAILURE(rc))
1972 {
1973 RTMemPageFree(pvChunk, pExecMemAllocator->cbChunk);
1974 return rc;
1975 }
1976
1977 void *pvChunkRx = (void *)AddrRemapped;
1978#else
1979 int rc = VINF_SUCCESS;
1980 void *pvChunkRx = pvChunk;
1981#endif
1982
1983 /*
1984 * Add the chunk.
1985 *
1986 * This must be done before the unwind init so windows can allocate
1987 * memory from the chunk when using the alternative sub-allocator.
1988 */
1989 pExecMemAllocator->aChunks[idxChunk].pvChunkRw = pvChunk;
1990 pExecMemAllocator->aChunks[idxChunk].pvChunkRx = pvChunkRx;
1991#ifdef IN_RING3
1992 pExecMemAllocator->aChunks[idxChunk].pvUnwindInfo = NULL;
1993#endif
1994 pExecMemAllocator->aChunks[idxChunk].cFreeUnits = pExecMemAllocator->cUnitsPerChunk;
1995 pExecMemAllocator->aChunks[idxChunk].idxFreeHint = 0;
1996 memset(&pExecMemAllocator->pbmAlloc[pExecMemAllocator->cBitmapElementsPerChunk * idxChunk],
1997 0, sizeof(pExecMemAllocator->pbmAlloc[0]) * pExecMemAllocator->cBitmapElementsPerChunk);
1998
1999 pExecMemAllocator->cChunks = idxChunk + 1;
2000 pExecMemAllocator->idxChunkHint = idxChunk;
2001
2002 pExecMemAllocator->cbTotal += pExecMemAllocator->cbChunk;
2003 pExecMemAllocator->cbFree += pExecMemAllocator->cbChunk;
2004
2005 /* If there is a chunk context init callback call it. */
2006 rc = iemNativeRecompileAttachExecMemChunkCtx(pVCpu, idxChunk, &pExecMemAllocator->aChunks[idxChunk].pCtx);
2007#ifdef IN_RING3
2008 /*
2009 * Initialize the unwind information (this cannot really fail atm).
2010 * (This sets pvUnwindInfo.)
2011 */
2012 if (RT_SUCCESS(rc))
2013 rc = iemExecMemAllocatorInitAndRegisterUnwindInfoForChunk(pVCpu, pExecMemAllocator, pvChunkRx, idxChunk);
2014#endif
2015 if (RT_SUCCESS(rc))
2016 { /* likely */ }
2017 else
2018 {
2019 /* Just in case the impossible happens, undo the above up: */
2020 pExecMemAllocator->cbTotal -= pExecMemAllocator->cbChunk;
2021 pExecMemAllocator->cbFree -= pExecMemAllocator->aChunks[idxChunk].cFreeUnits << IEMEXECMEM_ALT_SUB_ALLOC_UNIT_SHIFT;
2022 pExecMemAllocator->cChunks = idxChunk;
2023 memset(&pExecMemAllocator->pbmAlloc[pExecMemAllocator->cBitmapElementsPerChunk * idxChunk],
2024 0xff, sizeof(pExecMemAllocator->pbmAlloc[0]) * pExecMemAllocator->cBitmapElementsPerChunk);
2025 pExecMemAllocator->aChunks[idxChunk].pvChunkRw = NULL;
2026 pExecMemAllocator->aChunks[idxChunk].cFreeUnits = 0;
2027
2028# ifdef RT_OS_DARWIN
2029 krc = mach_vm_deallocate(mach_task_self(), (mach_vm_address_t)pExecMemAllocator->aChunks[idxChunk].pvChunkRx,
2030 pExecMemAllocator->cbChunk);
2031 Assert(krc == KERN_SUCCESS);
2032# endif
2033
2034 RTMemPageFree(pvChunk, pExecMemAllocator->cbChunk);
2035 return rc;
2036 }
2037
2038 return VINF_SUCCESS;
2039}
2040
2041
2042/**
2043 * Initializes the executable memory allocator for native recompilation on the
2044 * calling EMT.
2045 *
2046 * @returns VBox status code.
2047 * @param pVCpu The cross context virtual CPU structure of the calling
2048 * thread.
2049 * @param cbMax The max size of the allocator.
2050 * @param cbInitial The initial allocator size.
2051 * @param cbChunk The chunk size, 0 or UINT32_MAX for default (@a cbMax
2052 * dependent).
2053 */
2054int iemExecMemAllocatorInit(PVMCPU pVCpu, uint64_t cbMax, uint64_t cbInitial, uint32_t cbChunk) RT_NOEXCEPT
2055{
2056 /*
2057 * Validate input.
2058 */
2059 AssertLogRelMsgReturn(cbMax >= _1M && cbMax <= _4G+_4G, ("cbMax=%RU64 (%RX64)\n", cbMax, cbMax), VERR_OUT_OF_RANGE);
2060 AssertReturn(cbInitial <= cbMax, VERR_OUT_OF_RANGE);
2061 AssertLogRelMsgReturn( cbChunk != UINT32_MAX
2062 || cbChunk == 0
2063 || ( RT_IS_POWER_OF_TWO(cbChunk)
2064 && cbChunk >= _1M
2065 && cbChunk <= _256M
2066 && cbChunk <= cbMax),
2067 ("cbChunk=%RU32 (%RX32) cbMax=%RU64\n", cbChunk, cbChunk, cbMax),
2068 VERR_OUT_OF_RANGE);
2069
2070 /*
2071 * Adjust/figure out the chunk size.
2072 */
2073 if (cbChunk == 0 || cbChunk == UINT32_MAX)
2074 {
2075 if (cbMax >= _256M)
2076 cbChunk = _64M;
2077 else
2078 {
2079 if (cbMax < _16M)
2080 cbChunk = cbMax >= _4M ? _4M : (uint32_t)cbMax;
2081 else
2082 cbChunk = (uint32_t)cbMax / 4;
2083 if (!RT_IS_POWER_OF_TWO(cbChunk))
2084 cbChunk = RT_BIT_32(ASMBitLastSetU32(cbChunk));
2085 }
2086 }
2087#if defined(RT_OS_AMD64)
2088 Assert(cbChunk <= _2G);
2089#elif defined(RT_OS_ARM64)
2090 if (cbChunk > _128M)
2091 cbChunk = _128M; /* Max relative branch distance is +/-2^(25+2) = +/-0x8000000 (134 217 728). */
2092#endif
2093
2094 if (cbChunk > cbMax)
2095 cbMax = cbChunk;
2096 else
2097 cbMax = (cbMax - 1 + cbChunk) / cbChunk * cbChunk;
2098 uint32_t const cMaxChunks = (uint32_t)(cbMax / cbChunk);
2099 AssertLogRelReturn((uint64_t)cMaxChunks * cbChunk == cbMax, VERR_INTERNAL_ERROR_3);
2100
2101 /*
2102 * Allocate and initialize the allocatore instance.
2103 */
2104 size_t const offBitmaps = RT_ALIGN_Z(RT_UOFFSETOF_DYN(IEMEXECMEMALLOCATOR, aChunks[cMaxChunks]), RT_CACHELINE_SIZE);
2105 size_t const cbBitmaps = (size_t)(cbChunk >> (IEMEXECMEM_ALT_SUB_ALLOC_UNIT_SHIFT + 3)) * cMaxChunks;
2106 size_t cbNeeded = offBitmaps + cbBitmaps;
2107 AssertCompile(IEMEXECMEM_ALT_SUB_ALLOC_UNIT_SHIFT <= 10);
2108 Assert(cbChunk > RT_BIT_32(IEMEXECMEM_ALT_SUB_ALLOC_UNIT_SHIFT + 3));
2109#if defined(IN_RING3) && !defined(RT_OS_WINDOWS)
2110 size_t const offEhFrames = RT_ALIGN_Z(cbNeeded, RT_CACHELINE_SIZE);
2111 cbNeeded += sizeof(IEMEXECMEMCHUNKEHFRAME) * cMaxChunks;
2112#endif
2113 PIEMEXECMEMALLOCATOR pExecMemAllocator = (PIEMEXECMEMALLOCATOR)RTMemAllocZ(cbNeeded);
2114 AssertLogRelMsgReturn(pExecMemAllocator, ("cbNeeded=%zx cMaxChunks=%#x cbChunk=%#x\n", cbNeeded, cMaxChunks, cbChunk),
2115 VERR_NO_MEMORY);
2116 pExecMemAllocator->uMagic = IEMEXECMEMALLOCATOR_MAGIC;
2117 pExecMemAllocator->cbChunk = cbChunk;
2118 pExecMemAllocator->cMaxChunks = cMaxChunks;
2119 pExecMemAllocator->cChunks = 0;
2120 pExecMemAllocator->idxChunkHint = 0;
2121 pExecMemAllocator->cAllocations = 0;
2122 pExecMemAllocator->cbTotal = 0;
2123 pExecMemAllocator->cbFree = 0;
2124 pExecMemAllocator->cbAllocated = 0;
2125#ifdef VBOX_WITH_STATISTICS
2126 pExecMemAllocator->cbUnusable = 0;
2127#endif
2128 pExecMemAllocator->pbmAlloc = (uint64_t *)((uintptr_t)pExecMemAllocator + offBitmaps);
2129 pExecMemAllocator->cUnitsPerChunk = cbChunk >> IEMEXECMEM_ALT_SUB_ALLOC_UNIT_SHIFT;
2130 pExecMemAllocator->cBitmapElementsPerChunk = cbChunk >> (IEMEXECMEM_ALT_SUB_ALLOC_UNIT_SHIFT + 6);
2131 memset(pExecMemAllocator->pbmAlloc, 0xff, cbBitmaps); /* Mark everything as allocated. Clear when chunks are added. */
2132#if defined(IN_RING3) && !defined(RT_OS_WINDOWS)
2133 pExecMemAllocator->paEhFrames = (PIEMEXECMEMCHUNKEHFRAME)((uintptr_t)pExecMemAllocator + offEhFrames);
2134#endif
2135 for (uint32_t i = 0; i < cMaxChunks; i++)
2136 {
2137 pExecMemAllocator->aChunks[i].cFreeUnits = 0;
2138 pExecMemAllocator->aChunks[i].idxFreeHint = 0;
2139 pExecMemAllocator->aChunks[i].pvChunkRw = NULL;
2140#ifdef IN_RING0
2141 pExecMemAllocator->aChunks[i].hMemObj = NIL_RTR0MEMOBJ;
2142#else
2143 pExecMemAllocator->aChunks[i].pvUnwindInfo = NULL;
2144#endif
2145 }
2146 pVCpu->iem.s.pExecMemAllocatorR3 = pExecMemAllocator;
2147
2148 /*
2149 * Do the initial allocations.
2150 */
2151 while (cbInitial < (uint64_t)pExecMemAllocator->cChunks * pExecMemAllocator->cbChunk)
2152 {
2153 int rc = iemExecMemAllocatorGrow(pVCpu, pExecMemAllocator);
2154 AssertLogRelRCReturn(rc, rc);
2155 }
2156
2157 pExecMemAllocator->idxChunkHint = 0;
2158
2159 /*
2160 * Register statistics.
2161 */
2162 PUVM const pUVM = pVCpu->pUVCpu->pUVM;
2163 STAMR3RegisterFU(pUVM, &pExecMemAllocator->cAllocations, STAMTYPE_U32, STAMVISIBILITY_ALWAYS, STAMUNIT_BYTES,
2164 "Current number of allocations", "/IEM/CPU%u/re/ExecMem/cAllocations", pVCpu->idCpu);
2165 STAMR3RegisterFU(pUVM, &pExecMemAllocator->cChunks, STAMTYPE_U32, STAMVISIBILITY_ALWAYS, STAMUNIT_COUNT,
2166 "Currently allocated chunks", "/IEM/CPU%u/re/ExecMem/cChunks", pVCpu->idCpu);
2167 STAMR3RegisterFU(pUVM, &pExecMemAllocator->cMaxChunks, STAMTYPE_U32, STAMVISIBILITY_ALWAYS, STAMUNIT_COUNT,
2168 "Maximum number of chunks", "/IEM/CPU%u/re/ExecMem/cMaxChunks", pVCpu->idCpu);
2169 STAMR3RegisterFU(pUVM, &pExecMemAllocator->cbChunk, STAMTYPE_U32, STAMVISIBILITY_ALWAYS, STAMUNIT_BYTES,
2170 "Allocation chunk size", "/IEM/CPU%u/re/ExecMem/cbChunk", pVCpu->idCpu);
2171 STAMR3RegisterFU(pUVM, &pExecMemAllocator->cbAllocated, STAMTYPE_U64, STAMVISIBILITY_ALWAYS, STAMUNIT_BYTES,
2172 "Number of bytes current allocated", "/IEM/CPU%u/re/ExecMem/cbAllocated", pVCpu->idCpu);
2173 STAMR3RegisterFU(pUVM, &pExecMemAllocator->cbFree, STAMTYPE_U64, STAMVISIBILITY_ALWAYS, STAMUNIT_BYTES,
2174 "Number of bytes current free", "/IEM/CPU%u/re/ExecMem/cbFree", pVCpu->idCpu);
2175 STAMR3RegisterFU(pUVM, &pExecMemAllocator->cbTotal, STAMTYPE_U64, STAMVISIBILITY_ALWAYS, STAMUNIT_BYTES,
2176 "Total number of byte", "/IEM/CPU%u/re/ExecMem/cbTotal", pVCpu->idCpu);
2177#ifdef VBOX_WITH_STATISTICS
2178 STAMR3RegisterFU(pUVM, &pExecMemAllocator->cbUnusable, STAMTYPE_U64, STAMVISIBILITY_ALWAYS, STAMUNIT_BYTES,
2179 "Total number of bytes being unusable", "/IEM/CPU%u/re/ExecMem/cbUnusable", pVCpu->idCpu);
2180 STAMR3RegisterFU(pUVM, &pExecMemAllocator->StatAlloc, STAMTYPE_PROFILE, STAMVISIBILITY_ALWAYS, STAMUNIT_TICKS_PER_CALL,
2181 "Profiling the allocator", "/IEM/CPU%u/re/ExecMem/ProfAlloc", pVCpu->idCpu);
2182 for (unsigned i = 1; i < RT_ELEMENTS(pExecMemAllocator->aStatSizes); i++)
2183 STAMR3RegisterFU(pUVM, &pExecMemAllocator->aStatSizes[i], STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_COUNT,
2184 "Number of allocations of this number of allocation units",
2185 "/IEM/CPU%u/re/ExecMem/aSize%02u", pVCpu->idCpu, i);
2186 STAMR3RegisterFU(pUVM, &pExecMemAllocator->aStatSizes[0], STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_COUNT,
2187 "Number of allocations 16 units or larger", "/IEM/CPU%u/re/ExecMem/aSize16OrLarger", pVCpu->idCpu);
2188#endif
2189#ifdef IEMEXECMEM_ALT_SUB_WITH_ALT_PRUNING
2190 STAMR3RegisterFU(pUVM, &pExecMemAllocator->StatPruneProf, STAMTYPE_PROFILE, STAMVISIBILITY_ALWAYS, STAMUNIT_TICKS_PER_CALL,
2191 "Pruning executable memory (alt)", "/IEM/CPU%u/re/ExecMem/Pruning", pVCpu->idCpu);
2192 STAMR3RegisterFU(pUVM, &pExecMemAllocator->StatPruneRecovered, STAMTYPE_PROFILE, STAMVISIBILITY_ALWAYS, STAMUNIT_BYTES_PER_CALL,
2193 "Bytes recovered while pruning", "/IEM/CPU%u/re/ExecMem/PruningRecovered", pVCpu->idCpu);
2194#endif
2195 STAMR3RegisterFU(pUVM, &pExecMemAllocator->cFruitlessChunkScans, STAMTYPE_U64_RESET, STAMVISIBILITY_ALWAYS, STAMUNIT_COUNT,
2196 "Chunks fruitlessly scanned for free space", "/IEM/CPU%u/re/ExecMem/FruitlessChunkScans", pVCpu->idCpu);
2197
2198 return VINF_SUCCESS;
2199}
2200
Note: See TracBrowser for help on using the repository browser.

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette