1 /* -----------------------------------------------------------------------------
3 * (c) The GHC Team, 1998-2008
5 * Storage manager front end
7 * Documentation on the architecture of the Storage Manager can be
8 * found in the online commentary:
10 * http://hackage.haskell.org/trac/ghc/wiki/Commentary/Rts/Storage
12 * ---------------------------------------------------------------------------*/
14 #include "PosixSource.h"
20 #include "BlockAlloc.h"
24 #include "Capability.h"
26 #include "RetainerProfile.h" // for counting memory blocks (memInventory)
37 * All these globals require sm_mutex to access in THREADED_RTS mode.
39 StgClosure *caf_list = NULL;
40 StgClosure *revertible_caf_list = NULL;
43 nat alloc_blocks_lim; /* GC if n_large_blocks in any nursery
48 generation *generations = NULL; /* all the generations */
49 generation *g0 = NULL; /* generation 0, for convenience */
50 generation *oldest_gen = NULL; /* oldest generation, for convenience */
52 nursery *nurseries = NULL; /* array of nurseries, size == n_capabilities */
56 * Storage manager mutex: protects all the above state from
57 * simultaneous access by two STG threads.
62 static void allocNurseries ( void );
65 initGeneration (generation *gen, int g)
69 gen->par_collections = 0;
70 gen->failed_promotions = 0;
75 gen->live_estimate = 0;
76 gen->old_blocks = NULL;
77 gen->n_old_blocks = 0;
78 gen->large_objects = NULL;
79 gen->n_large_blocks = 0;
80 gen->n_new_large_blocks = 0;
81 gen->mut_list = allocBlock();
82 gen->scavenged_large_objects = NULL;
83 gen->n_scavenged_large_blocks = 0;
88 initSpinLock(&gen->sync_large_objects);
90 gen->threads = END_TSO_QUEUE;
91 gen->old_threads = END_TSO_QUEUE;
99 if (generations != NULL) {
100 // multi-init protection
106 /* Sanity check to make sure the LOOKS_LIKE_ macros appear to be
107 * doing something reasonable.
109 /* We use the NOT_NULL variant or gcc warns that the test is always true */
110 ASSERT(LOOKS_LIKE_INFO_PTR_NOT_NULL((StgWord)&stg_BLOCKING_QUEUE_CLEAN_info));
111 ASSERT(LOOKS_LIKE_CLOSURE_PTR(&stg_dummy_ret_closure));
112 ASSERT(!HEAP_ALLOCED(&stg_dummy_ret_closure));
114 if (RtsFlags.GcFlags.maxHeapSize != 0 &&
115 RtsFlags.GcFlags.heapSizeSuggestion >
116 RtsFlags.GcFlags.maxHeapSize) {
117 RtsFlags.GcFlags.maxHeapSize = RtsFlags.GcFlags.heapSizeSuggestion;
120 if (RtsFlags.GcFlags.maxHeapSize != 0 &&
121 RtsFlags.GcFlags.minAllocAreaSize >
122 RtsFlags.GcFlags.maxHeapSize) {
123 errorBelch("maximum heap size (-M) is smaller than minimum alloc area size (-A)");
124 RtsFlags.GcFlags.minAllocAreaSize = RtsFlags.GcFlags.maxHeapSize;
127 initBlockAllocator();
129 #if defined(THREADED_RTS)
130 initMutex(&sm_mutex);
135 /* allocate generation info array */
136 generations = (generation *)stgMallocBytes(RtsFlags.GcFlags.generations
137 * sizeof(struct generation_),
138 "initStorage: gens");
140 /* Initialise all generations */
141 for(g = 0; g < RtsFlags.GcFlags.generations; g++) {
142 initGeneration(&generations[g], g);
145 /* A couple of convenience pointers */
146 g0 = &generations[0];
147 oldest_gen = &generations[RtsFlags.GcFlags.generations-1];
149 nurseries = stgMallocBytes(n_capabilities * sizeof(struct nursery_),
150 "initStorage: nurseries");
152 /* Set up the destination pointers in each younger gen. step */
153 for (g = 0; g < RtsFlags.GcFlags.generations-1; g++) {
154 generations[g].to = &generations[g+1];
156 oldest_gen->to = oldest_gen;
158 /* The oldest generation has one step. */
159 if (RtsFlags.GcFlags.compact || RtsFlags.GcFlags.sweep) {
160 if (RtsFlags.GcFlags.generations == 1) {
161 errorBelch("WARNING: compact/sweep is incompatible with -G1; disabled");
163 oldest_gen->mark = 1;
164 if (RtsFlags.GcFlags.compact)
165 oldest_gen->compact = 1;
169 generations[0].max_blocks = 0;
171 /* The allocation area. Policy: keep the allocation area
172 * small to begin with, even if we have a large suggested heap
173 * size. Reason: we're going to do a major collection first, and we
174 * don't want it to be a big one. This vague idea is borne out by
175 * rigorous experimental evidence.
179 weak_ptr_list = NULL;
180 caf_list = END_OF_STATIC_LIST;
181 revertible_caf_list = END_OF_STATIC_LIST;
183 /* initialise the allocate() interface */
184 alloc_blocks_lim = RtsFlags.GcFlags.minAllocAreaSize;
189 initSpinLock(&gc_alloc_block_sync);
195 // allocate a block for each mut list
196 for (n = 0; n < n_capabilities; n++) {
197 for (g = 1; g < RtsFlags.GcFlags.generations; g++) {
198 capabilities[n].mut_lists[g] = allocBlock();
204 IF_DEBUG(gc, statDescribeGens());
212 stat_exit(calcAllocated());
216 freeStorage (rtsBool free_heap)
218 stgFree(generations);
219 if (free_heap) freeAllMBlocks();
220 #if defined(THREADED_RTS)
221 closeMutex(&sm_mutex);
227 /* -----------------------------------------------------------------------------
230 The entry code for every CAF does the following:
232 - builds a BLACKHOLE in the heap
233 - pushes an update frame pointing to the BLACKHOLE
234 - calls newCaf, below
235 - updates the CAF with a static indirection to the BLACKHOLE
237 Why do we build an BLACKHOLE in the heap rather than just updating
238 the thunk directly? It's so that we only need one kind of update
239 frame - otherwise we'd need a static version of the update frame too.
241 newCaf() does the following:
243 - it puts the CAF on the oldest generation's mutable list.
244 This is so that we treat the CAF as a root when collecting
247 For GHCI, we have additional requirements when dealing with CAFs:
249 - we must *retain* all dynamically-loaded CAFs ever entered,
250 just in case we need them again.
251 - we must be able to *revert* CAFs that have been evaluated, to
252 their pre-evaluated form.
254 To do this, we use an additional CAF list. When newCaf() is
255 called on a dynamically-loaded CAF, we add it to the CAF list
256 instead of the old-generation mutable list, and save away its
257 old info pointer (in caf->saved_info) for later reversion.
259 To revert all the CAFs, we traverse the CAF list and reset the
260 info pointer to caf->saved_info, then throw away the CAF list.
261 (see GC.c:revertCAFs()).
265 -------------------------------------------------------------------------- */
268 newCAF(StgRegTable *reg, StgClosure* caf)
273 // If we are in GHCi _and_ we are using dynamic libraries,
274 // then we can't redirect newCAF calls to newDynCAF (see below),
275 // so we make newCAF behave almost like newDynCAF.
276 // The dynamic libraries might be used by both the interpreted
277 // program and GHCi itself, so they must not be reverted.
278 // This also means that in GHCi with dynamic libraries, CAFs are not
279 // garbage collected. If this turns out to be a problem, we could
280 // do another hack here and do an address range test on caf to figure
281 // out whether it is from a dynamic library.
282 ((StgIndStatic *)caf)->saved_info = (StgInfoTable *)caf->header.info;
284 ACQUIRE_SM_LOCK; // caf_list is global, locked by sm_mutex
285 ((StgIndStatic *)caf)->static_link = caf_list;
291 // Put this CAF on the mutable list for the old generation.
292 ((StgIndStatic *)caf)->saved_info = NULL;
293 if (oldest_gen->no != 0) {
294 recordMutableCap(caf, regTableToCapability(reg), oldest_gen->no);
299 // External API for setting the keepCAFs flag. see #3900.
306 // An alternate version of newCaf which is used for dynamically loaded
307 // object code in GHCi. In this case we want to retain *all* CAFs in
308 // the object code, because they might be demanded at any time from an
309 // expression evaluated on the command line.
310 // Also, GHCi might want to revert CAFs, so we add these to the
311 // revertible_caf_list.
313 // The linker hackily arranges that references to newCaf from dynamic
314 // code end up pointing to newDynCAF.
316 newDynCAF (StgRegTable *reg STG_UNUSED, StgClosure *caf)
320 ((StgIndStatic *)caf)->saved_info = (StgInfoTable *)caf->header.info;
321 ((StgIndStatic *)caf)->static_link = revertible_caf_list;
322 revertible_caf_list = caf;
327 /* -----------------------------------------------------------------------------
329 -------------------------------------------------------------------------- */
332 allocNursery (bdescr *tail, nat blocks)
337 // We allocate the nursery as a single contiguous block and then
338 // divide it into single blocks manually. This way we guarantee
339 // that the nursery blocks are adjacent, so that the processor's
340 // automatic prefetching works across nursery blocks. This is a
341 // tiny optimisation (~0.5%), but it's free.
344 n = stg_min(blocks, BLOCKS_PER_MBLOCK);
348 for (i = 0; i < n; i++) {
349 initBdescr(&bd[i], g0, g0);
355 bd[i].u.back = &bd[i-1];
359 bd[i].link = &bd[i+1];
363 tail->u.back = &bd[i];
367 bd[i].free = bd[i].start;
377 assignNurseriesToCapabilities (void)
381 for (i = 0; i < n_capabilities; i++) {
382 capabilities[i].r.rNursery = &nurseries[i];
383 capabilities[i].r.rCurrentNursery = nurseries[i].blocks;
384 capabilities[i].r.rCurrentAlloc = NULL;
389 allocNurseries( void )
393 for (i = 0; i < n_capabilities; i++) {
394 nurseries[i].blocks =
395 allocNursery(NULL, RtsFlags.GcFlags.minAllocAreaSize);
396 nurseries[i].n_blocks =
397 RtsFlags.GcFlags.minAllocAreaSize;
399 assignNurseriesToCapabilities();
403 resetNurseries( void )
408 for (i = 0; i < n_capabilities; i++) {
409 for (bd = nurseries[i].blocks; bd; bd = bd->link) {
410 bd->free = bd->start;
411 ASSERT(bd->gen_no == 0);
412 ASSERT(bd->gen == g0);
413 IF_DEBUG(sanity,memset(bd->start, 0xaa, BLOCK_SIZE));
416 assignNurseriesToCapabilities();
420 countNurseryBlocks (void)
425 for (i = 0; i < n_capabilities; i++) {
426 blocks += nurseries[i].n_blocks;
432 resizeNursery ( nursery *nursery, nat blocks )
437 nursery_blocks = nursery->n_blocks;
438 if (nursery_blocks == blocks) return;
440 if (nursery_blocks < blocks) {
441 debugTrace(DEBUG_gc, "increasing size of nursery to %d blocks",
443 nursery->blocks = allocNursery(nursery->blocks, blocks-nursery_blocks);
448 debugTrace(DEBUG_gc, "decreasing size of nursery to %d blocks",
451 bd = nursery->blocks;
452 while (nursery_blocks > blocks) {
454 next_bd->u.back = NULL;
455 nursery_blocks -= bd->blocks; // might be a large block
459 nursery->blocks = bd;
460 // might have gone just under, by freeing a large block, so make
461 // up the difference.
462 if (nursery_blocks < blocks) {
463 nursery->blocks = allocNursery(nursery->blocks, blocks-nursery_blocks);
467 nursery->n_blocks = blocks;
468 ASSERT(countBlocks(nursery->blocks) == nursery->n_blocks);
472 // Resize each of the nurseries to the specified size.
475 resizeNurseriesFixed (nat blocks)
478 for (i = 0; i < n_capabilities; i++) {
479 resizeNursery(&nurseries[i], blocks);
484 // Resize the nurseries to the total specified size.
487 resizeNurseries (nat blocks)
489 // If there are multiple nurseries, then we just divide the number
490 // of available blocks between them.
491 resizeNurseriesFixed(blocks / n_capabilities);
495 /* -----------------------------------------------------------------------------
496 move_TSO is called to update the TSO structure after it has been
497 moved from one place to another.
498 -------------------------------------------------------------------------- */
501 move_TSO (StgTSO *src, StgTSO *dest)
505 // relocate the stack pointer...
506 diff = (StgPtr)dest - (StgPtr)src; // In *words*
507 dest->sp = (StgPtr)dest->sp + diff;
510 /* -----------------------------------------------------------------------------
511 split N blocks off the front of the given bdescr, returning the
512 new block group. We add the remainder to the large_blocks list
513 in the same step as the original block.
514 -------------------------------------------------------------------------- */
517 splitLargeBlock (bdescr *bd, nat blocks)
523 ASSERT(countBlocks(bd->gen->large_objects) == bd->gen->n_large_blocks);
525 // subtract the original number of blocks from the counter first
526 bd->gen->n_large_blocks -= bd->blocks;
528 new_bd = splitBlockGroup (bd, blocks);
529 initBdescr(new_bd, bd->gen, bd->gen->to);
530 new_bd->flags = BF_LARGE | (bd->flags & BF_EVACUATED);
531 // if new_bd is in an old generation, we have to set BF_EVACUATED
532 new_bd->free = bd->free;
533 dbl_link_onto(new_bd, &bd->gen->large_objects);
535 ASSERT(new_bd->free <= new_bd->start + new_bd->blocks * BLOCK_SIZE_W);
537 // add the new number of blocks to the counter. Due to the gaps
538 // for block descriptors, new_bd->blocks + bd->blocks might not be
539 // equal to the original bd->blocks, which is why we do it this way.
540 bd->gen->n_large_blocks += bd->blocks + new_bd->blocks;
542 ASSERT(countBlocks(bd->gen->large_objects) == bd->gen->n_large_blocks);
549 /* -----------------------------------------------------------------------------
552 This allocates memory in the current thread - it is intended for
553 use primarily from STG-land where we have a Capability. It is
554 better than allocate() because it doesn't require taking the
555 sm_mutex lock in the common case.
557 Memory is allocated directly from the nursery if possible (but not
558 from the current nursery block, so as not to interfere with
560 -------------------------------------------------------------------------- */
563 allocate (Capability *cap, lnat n)
568 if (n >= LARGE_OBJECT_THRESHOLD/sizeof(W_)) {
569 lnat req_blocks = (lnat)BLOCK_ROUND_UP(n*sizeof(W_)) / BLOCK_SIZE;
571 // Attempting to allocate an object larger than maxHeapSize
572 // should definitely be disallowed. (bug #1791)
573 if (RtsFlags.GcFlags.maxHeapSize > 0 &&
574 req_blocks >= RtsFlags.GcFlags.maxHeapSize) {
576 // heapOverflow() doesn't exit (see #2592), but we aren't
577 // in a position to do a clean shutdown here: we
578 // either have to allocate the memory or exit now.
579 // Allocating the memory would be bad, because the user
580 // has requested that we not exceed maxHeapSize, so we
582 stg_exit(EXIT_HEAPOVERFLOW);
586 bd = allocGroup(req_blocks);
587 dbl_link_onto(bd, &g0->large_objects);
588 g0->n_large_blocks += bd->blocks; // might be larger than req_blocks
589 g0->n_new_large_blocks += bd->blocks;
591 initBdescr(bd, g0, g0);
592 bd->flags = BF_LARGE;
593 bd->free = bd->start + n;
597 /* small allocation (<LARGE_OBJECT_THRESHOLD) */
599 TICK_ALLOC_HEAP_NOCTR(n);
602 bd = cap->r.rCurrentAlloc;
603 if (bd == NULL || bd->free + n > bd->start + BLOCK_SIZE_W) {
605 // The CurrentAlloc block is full, we need to find another
606 // one. First, we try taking the next block from the
608 bd = cap->r.rCurrentNursery->link;
610 if (bd == NULL || bd->free + n > bd->start + BLOCK_SIZE_W) {
611 // The nursery is empty, or the next block is already
612 // full: allocate a fresh block (we can't fail here).
615 cap->r.rNursery->n_blocks++;
617 initBdescr(bd, g0, g0);
619 // If we had to allocate a new block, then we'll GC
620 // pretty quickly now, because MAYBE_GC() will
621 // notice that CurrentNursery->link is NULL.
623 // we have a block in the nursery: take it and put
624 // it at the *front* of the nursery list, and use it
625 // to allocate() from.
626 cap->r.rCurrentNursery->link = bd->link;
627 if (bd->link != NULL) {
628 bd->link->u.back = cap->r.rCurrentNursery;
631 dbl_link_onto(bd, &cap->r.rNursery->blocks);
632 cap->r.rCurrentAlloc = bd;
633 IF_DEBUG(sanity, checkNurserySanity(cap->r.rNursery));
638 IF_DEBUG(sanity, ASSERT(*((StgWord8*)p) == 0xaa));
642 /* ---------------------------------------------------------------------------
643 Allocate a fixed/pinned object.
645 We allocate small pinned objects into a single block, allocating a
646 new block when the current one overflows. The block is chained
647 onto the large_object_list of generation 0.
649 NOTE: The GC can't in general handle pinned objects. This
650 interface is only safe to use for ByteArrays, which have no
651 pointers and don't require scavenging. It works because the
652 block's descriptor has the BF_LARGE flag set, so the block is
653 treated as a large object and chained onto various lists, rather
654 than the individual objects being copied. However, when it comes
655 to scavenge the block, the GC will only scavenge the first object.
656 The reason is that the GC can't linearly scan a block of pinned
657 objects at the moment (doing so would require using the
658 mostly-copying techniques). But since we're restricting ourselves
659 to pinned ByteArrays, not scavenging is ok.
661 This function is called by newPinnedByteArray# which immediately
662 fills the allocated memory with a MutableByteArray#.
663 ------------------------------------------------------------------------- */
666 allocatePinned (Capability *cap, lnat n)
671 // If the request is for a large object, then allocate()
672 // will give us a pinned object anyway.
673 if (n >= LARGE_OBJECT_THRESHOLD/sizeof(W_)) {
674 p = allocate(cap, n);
675 Bdescr(p)->flags |= BF_PINNED;
679 TICK_ALLOC_HEAP_NOCTR(n);
682 bd = cap->pinned_object_block;
684 // If we don't have a block of pinned objects yet, or the current
685 // one isn't large enough to hold the new object, allocate a new one.
686 if (bd == NULL || (bd->free + n) > (bd->start + BLOCK_SIZE_W)) {
688 cap->pinned_object_block = bd = allocBlock();
689 dbl_link_onto(bd, &g0->large_objects);
690 g0->n_large_blocks++;
691 g0->n_new_large_blocks++;
693 initBdescr(bd, g0, g0);
694 bd->flags = BF_PINNED | BF_LARGE;
695 bd->free = bd->start;
703 /* -----------------------------------------------------------------------------
705 -------------------------------------------------------------------------- */
708 This is the write barrier for MUT_VARs, a.k.a. IORefs. A
709 MUT_VAR_CLEAN object is not on the mutable list; a MUT_VAR_DIRTY
710 is. When written to, a MUT_VAR_CLEAN turns into a MUT_VAR_DIRTY
711 and is put on the mutable list.
714 dirty_MUT_VAR(StgRegTable *reg, StgClosure *p)
716 Capability *cap = regTableToCapability(reg);
717 if (p->header.info == &stg_MUT_VAR_CLEAN_info) {
718 p->header.info = &stg_MUT_VAR_DIRTY_info;
719 recordClosureMutated(cap,p);
723 // Setting a TSO's link field with a write barrier.
724 // It is *not* necessary to call this function when
725 // * setting the link field to END_TSO_QUEUE
726 // * putting a TSO on the blackhole_queue
727 // * setting the link field of the currently running TSO, as it
728 // will already be dirty.
730 setTSOLink (Capability *cap, StgTSO *tso, StgTSO *target)
732 if (tso->dirty == 0 && (tso->flags & TSO_LINK_DIRTY) == 0) {
733 tso->flags |= TSO_LINK_DIRTY;
734 recordClosureMutated(cap,(StgClosure*)tso);
740 setTSOPrev (Capability *cap, StgTSO *tso, StgTSO *target)
742 if (tso->dirty == 0 && (tso->flags & TSO_LINK_DIRTY) == 0) {
743 tso->flags |= TSO_LINK_DIRTY;
744 recordClosureMutated(cap,(StgClosure*)tso);
746 tso->block_info.prev = target;
750 dirty_TSO (Capability *cap, StgTSO *tso)
752 if (tso->dirty == 0 && (tso->flags & TSO_LINK_DIRTY) == 0) {
753 recordClosureMutated(cap,(StgClosure*)tso);
759 This is the write barrier for MVARs. An MVAR_CLEAN objects is not
760 on the mutable list; a MVAR_DIRTY is. When written to, a
761 MVAR_CLEAN turns into a MVAR_DIRTY and is put on the mutable list.
762 The check for MVAR_CLEAN is inlined at the call site for speed,
763 this really does make a difference on concurrency-heavy benchmarks
764 such as Chaneneos and cheap-concurrency.
767 dirty_MVAR(StgRegTable *reg, StgClosure *p)
769 recordClosureMutated(regTableToCapability(reg),p);
772 /* -----------------------------------------------------------------------------
774 * -------------------------------------------------------------------------- */
776 /* -----------------------------------------------------------------------------
779 * Approximate how much we've allocated: number of blocks in the
780 * nursery + blocks allocated via allocate() - unused nusery blocks.
781 * This leaves a little slop at the end of each block.
782 * -------------------------------------------------------------------------- */
785 calcAllocated( void )
791 allocated = countNurseryBlocks() * BLOCK_SIZE_W;
793 for (i = 0; i < n_capabilities; i++) {
795 for ( bd = capabilities[i].r.rCurrentNursery->link;
796 bd != NULL; bd = bd->link ) {
797 allocated -= BLOCK_SIZE_W;
799 cap = &capabilities[i];
800 if (cap->r.rCurrentNursery->free <
801 cap->r.rCurrentNursery->start + BLOCK_SIZE_W) {
802 allocated -= (cap->r.rCurrentNursery->start + BLOCK_SIZE_W)
803 - cap->r.rCurrentNursery->free;
805 if (cap->pinned_object_block != NULL) {
806 allocated -= (cap->pinned_object_block->start + BLOCK_SIZE_W) -
807 cap->pinned_object_block->free;
811 allocated += g0->n_new_large_blocks * BLOCK_SIZE_W;
816 /* Approximate the amount of live data in the heap. To be called just
817 * after garbage collection (see GarbageCollect()).
819 lnat calcLiveBlocks (void)
825 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
826 /* approximate amount of live data (doesn't take into account slop
827 * at end of each block).
829 gen = &generations[g];
830 live += gen->n_large_blocks + gen->n_blocks;
835 lnat countOccupied (bdescr *bd)
840 for (; bd != NULL; bd = bd->link) {
841 ASSERT(bd->free <= bd->start + bd->blocks * BLOCK_SIZE_W);
842 words += bd->free - bd->start;
847 // Return an accurate count of the live data in the heap, excluding
849 lnat calcLiveWords (void)
856 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
857 gen = &generations[g];
858 live += gen->n_words + countOccupied(gen->large_objects);
863 /* Approximate the number of blocks that will be needed at the next
864 * garbage collection.
866 * Assume: all data currently live will remain live. Generationss
867 * that will be collected next time will therefore need twice as many
868 * blocks since all the data will be copied.
877 for (g = 0; g < RtsFlags.GcFlags.generations; g++) {
878 gen = &generations[g];
880 // we need at least this much space
881 needed += gen->n_blocks + gen->n_large_blocks;
883 // any additional space needed to collect this gen next time?
884 if (g == 0 || // always collect gen 0
885 (gen->n_blocks + gen->n_large_blocks > gen->max_blocks)) {
886 // we will collect this gen next time
889 needed += gen->n_blocks / BITS_IN(W_);
891 needed += gen->n_blocks / 100;
894 continue; // no additional space needed for compaction
896 needed += gen->n_blocks;
903 /* ----------------------------------------------------------------------------
906 Executable memory must be managed separately from non-executable
907 memory. Most OSs these days require you to jump through hoops to
908 dynamically allocate executable memory, due to various security
911 Here we provide a small memory allocator for executable memory.
912 Memory is managed with a page granularity; we allocate linearly
913 in the page, and when the page is emptied (all objects on the page
914 are free) we free the page again, not forgetting to make it
917 TODO: The inability to handle objects bigger than BLOCK_SIZE_W means that
918 the linker cannot use allocateExec for loading object code files
919 on Windows. Once allocateExec can handle larger objects, the linker
920 should be modified to use allocateExec instead of VirtualAlloc.
921 ------------------------------------------------------------------------- */
923 #if defined(linux_HOST_OS)
925 // On Linux we need to use libffi for allocating executable memory,
926 // because it knows how to work around the restrictions put in place
929 void *allocateExec (nat bytes, void **exec_ret)
933 ret = ffi_closure_alloc (sizeof(void *) + (size_t)bytes, (void**)&exec);
935 if (ret == NULL) return ret;
936 *ret = ret; // save the address of the writable mapping, for freeExec().
937 *exec_ret = exec + 1;
941 // freeExec gets passed the executable address, not the writable address.
942 void freeExec (void *addr)
945 writable = *((void**)addr - 1);
947 ffi_closure_free (writable);
953 void *allocateExec (nat bytes, void **exec_ret)
960 // round up to words.
961 n = (bytes + sizeof(W_) + 1) / sizeof(W_);
963 if (n+1 > BLOCK_SIZE_W) {
964 barf("allocateExec: can't handle large objects");
967 if (exec_block == NULL ||
968 exec_block->free + n + 1 > exec_block->start + BLOCK_SIZE_W) {
970 lnat pagesize = getPageSize();
971 bd = allocGroup(stg_max(1, pagesize / BLOCK_SIZE));
972 debugTrace(DEBUG_gc, "allocate exec block %p", bd->start);
975 bd->link = exec_block;
976 if (exec_block != NULL) {
977 exec_block->u.back = bd;
980 setExecutable(bd->start, bd->blocks * BLOCK_SIZE, rtsTrue);
983 *(exec_block->free) = n; // store the size of this chunk
984 exec_block->gen_no += n; // gen_no stores the number of words allocated
985 ret = exec_block->free + 1;
986 exec_block->free += n + 1;
993 void freeExec (void *addr)
995 StgPtr p = (StgPtr)addr - 1;
996 bdescr *bd = Bdescr((StgPtr)p);
998 if ((bd->flags & BF_EXEC) == 0) {
999 barf("freeExec: not executable");
1002 if (*(StgPtr)p == 0) {
1003 barf("freeExec: already free?");
1008 bd->gen_no -= *(StgPtr)p;
1011 if (bd->gen_no == 0) {
1012 // Free the block if it is empty, but not if it is the block at
1013 // the head of the queue.
1014 if (bd != exec_block) {
1015 debugTrace(DEBUG_gc, "free exec block %p", bd->start);
1016 dbl_link_remove(bd, &exec_block);
1017 setExecutable(bd->start, bd->blocks * BLOCK_SIZE, rtsFalse);
1020 bd->free = bd->start;
1027 #endif /* mingw32_HOST_OS */
1031 // handy function for use in gdb, because Bdescr() is inlined.
1032 extern bdescr *_bdescr( StgPtr p );