VirtualBox

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

Last change on this file since 106326 was 106326, checked in by vboxsync, 6 weeks ago

VMM/IEM: Two small perf tweaks in iemExecMemAllocatorPrune. bugref:10720

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