1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
5 // See malloc.h for overview.
7 // TODO(rsc): double-check stats.
17 #include "interface.h"
21 // Map gccgo field names to gc field names.
22 // Eface aka __go_empty_interface.
23 #define type __type_descriptor
24 // Type aka __go_type_descriptor
26 #define string __reflection
27 #define KindPtr GO_PTR
28 #define KindNoPointers GO_NO_POINTERS
30 // GCCGO SPECIFIC CHANGE
32 // There is a long comment in runtime_mallocinit about where to put the heap
33 // on a 64-bit system. It makes assumptions that are not valid on linux/arm64
34 // -- it assumes user space can choose the lower 47 bits of a pointer, but on
35 // linux/arm64 we can only choose the lower 39 bits. This means the heap is
36 // roughly a quarter of the available address space and we cannot choose a bit
37 // pattern that all pointers will have -- luckily the GC is mostly precise
38 // these days so this doesn't matter all that much. The kernel (as of 3.13)
39 // will allocate address space starting either down from 0x7fffffffff or up
40 // from 0x2000000000, so we put the heap roughly in the middle of these two
41 // addresses to minimize the chance that a non-heap allocation will get in the
44 // This all means that there isn't much point in trying 256 different
45 // locations for the heap on such systems.
47 #define HeapBase(i) ((void*)(uintptr)(0x40ULL<<32))
48 #define HeapBaseOptions 1
50 #define HeapBase(i) ((void*)(uintptr)(i<<40|0x00c0ULL<<32))
51 #define HeapBaseOptions 0x80
53 // END GCCGO SPECIFIC CHANGE
55 // Mark mheap as 'no pointers', it does not contain interesting pointers but occupies ~45K.
59 int32 runtime_checking;
61 extern MStats mstats; // defined in zruntime_def_$GOOS_$GOARCH.go
63 extern volatile intgo runtime_MemProfileRate
64 __asm__ (GOSYM_PREFIX "runtime.MemProfileRate");
66 static MSpan* largealloc(uint32, uintptr*);
67 static void profilealloc(void *v, uintptr size);
68 static void settype(MSpan *s, void *v, uintptr typ);
70 // Allocate an object of at least size bytes.
71 // Small objects are allocated from the per-thread cache's free lists.
72 // Large objects (> 32 kB) are allocated straight from the heap.
73 // If the block will be freed with runtime_free(), typ must be 0.
75 runtime_mallocgc(uintptr size, uintptr typ, uint32 flag)
80 uintptr tinysize, size1;
90 // All 0-length allocations use this pointer.
91 // The language does not require the allocations to
92 // have distinct values.
93 return &runtime_zerobase;
99 // We should not be called in between __go_set_closure and the
100 // actual function call, but cope with it if we are.
101 closure = g->closure;
104 if(m->mcache == nil && g->ncgo > 0) {
105 // For gccgo this case can occur when a cgo or SWIG function
106 // has an interface return type and the function
107 // returns a non-pointer, so memory allocation occurs
108 // after syscall.Cgocall but before syscall.CgocallDone.
109 // We treat it as a callback.
110 runtime_exitsyscall();
113 flag |= FlagNoInvokeGC;
116 if(runtime_gcwaiting() && g != m->g0 && m->locks == 0 && !(flag & FlagNoInvokeGC)) {
121 runtime_throw("malloc/free - deadlock");
122 // Disable preemption during settype.
123 // We can not use m->mallocing for this, because settype calls mallocgc.
127 if(DebugTypeAtBlockEnd)
128 size += sizeof(uintptr);
131 if(!runtime_debug.efence && size <= MaxSmallSize) {
132 if((flag&(FlagNoScan|FlagNoGC)) == FlagNoScan && size < TinySize) {
135 // Tiny allocator combines several tiny allocation requests
136 // into a single memory block. The resulting memory block
137 // is freed when all subobjects are unreachable. The subobjects
138 // must be FlagNoScan (don't have pointers), this ensures that
139 // the amount of potentially wasted memory is bounded.
141 // Size of the memory block used for combining (TinySize) is tunable.
142 // Current setting is 16 bytes, which relates to 2x worst case memory
143 // wastage (when all but one subobjects are unreachable).
144 // 8 bytes would result in no wastage at all, but provides less
145 // opportunities for combining.
146 // 32 bytes provides more opportunities for combining,
147 // but can lead to 4x worst case wastage.
148 // The best case winning is 8x regardless of block size.
150 // Objects obtained from tiny allocator must not be freed explicitly.
151 // So when an object will be freed explicitly, we ensure that
152 // its size >= TinySize.
154 // SetFinalizer has a special case for objects potentially coming
155 // from tiny allocator, it such case it allows to set finalizers
156 // for an inner byte of a memory block.
158 // The main targets of tiny allocator are small strings and
159 // standalone escaping variables. On a json benchmark
160 // the allocator reduces number of allocations by ~12% and
161 // reduces heap size by ~20%.
163 tinysize = c->tinysize;
164 if(size <= tinysize) {
166 // Align tiny pointer for required (conservative) alignment.
168 tiny = (byte*)ROUND((uintptr)tiny, 8);
169 else if((size&3) == 0)
170 tiny = (byte*)ROUND((uintptr)tiny, 4);
171 else if((size&1) == 0)
172 tiny = (byte*)ROUND((uintptr)tiny, 2);
173 size1 = size + (tiny - c->tiny);
174 if(size1 <= tinysize) {
175 // The object fits into existing tiny block.
178 c->tinysize -= size1;
182 runtime_entersyscall();
183 g->closure = closure;
187 // Allocate a new TinySize block.
188 s = c->alloc[TinySizeClass];
189 if(s->freelist == nil)
190 s = runtime_MCache_Refill(c, TinySizeClass);
195 if(next != nil) // prefetching nil leads to a DTLB miss
199 // See if we need to replace the existing tiny block with the new one
200 // based on amount of remaining free space.
201 if(TinySize-size > tinysize) {
202 c->tiny = (byte*)v + size;
203 c->tinysize = TinySize - size;
208 // Allocate from mcache free lists.
209 // Inlined version of SizeToClass().
211 sizeclass = runtime_size_to_class8[(size+7)>>3];
213 sizeclass = runtime_size_to_class128[(size-1024+127) >> 7];
214 size = runtime_class_to_size[sizeclass];
215 s = c->alloc[sizeclass];
216 if(s->freelist == nil)
217 s = runtime_MCache_Refill(c, sizeclass);
222 if(next != nil) // prefetching nil leads to a DTLB miss
224 if(!(flag & FlagNoZero)) {
226 // block is zeroed iff second word is zero ...
227 if(size > 2*sizeof(uintptr) && ((uintptr*)v)[1] != 0)
228 runtime_memclr((byte*)v, size);
231 c->local_cachealloc += size;
233 // Allocate directly from heap.
234 s = largealloc(flag, &size);
235 v = (void*)(s->start << PageShift);
240 else if(!(flag & FlagNoScan))
243 if(DebugTypeAtBlockEnd)
244 *(uintptr*)((uintptr)v+size-sizeof(uintptr)) = typ;
247 // TODO: save type even if FlagNoScan? Potentially expensive but might help
248 // heap profiling/tracing.
249 if(UseSpanType && !(flag & FlagNoScan) && typ != 0)
253 runtime_racemalloc(v, size);
255 if(runtime_debug.allocfreetrace)
256 runtime_tracealloc(v, size, typ);
258 if(!(flag & FlagNoProfiling) && (rate = runtime_MemProfileRate) > 0) {
259 if(size < (uintptr)rate && size < (uintptr)(uint32)c->next_sample)
260 c->next_sample -= size;
262 profilealloc(v, size);
267 if(!(flag & FlagNoInvokeGC) && mstats.heap_alloc >= mstats.next_gc)
271 runtime_entersyscall();
273 g->closure = closure;
279 largealloc(uint32 flag, uintptr *sizep)
281 uintptr npages, size;
285 // Allocate directly from heap.
287 if(size + PageSize < size)
288 runtime_throw("out of memory");
289 npages = size >> PageShift;
290 if((size & PageMask) != 0)
292 s = runtime_MHeap_Alloc(&runtime_mheap, npages, 0, 1, !(flag & FlagNoZero));
294 runtime_throw("out of memory");
295 s->limit = (byte*)(s->start<<PageShift) + size;
296 *sizep = npages<<PageShift;
297 v = (void*)(s->start << PageShift);
298 // setup for mark sweep
299 runtime_markspan(v, 0, 0, true);
304 profilealloc(void *v, uintptr size)
310 c = runtime_m()->mcache;
311 rate = runtime_MemProfileRate;
313 // pick next profile time
314 // If you change this, also change allocmcache.
315 if(rate > 0x3fffffff) // make 2*rate not overflow
317 next = runtime_fastrand1() % (2*rate);
318 // Subtract the "remainder" of the current allocation.
319 // Otherwise objects that are close in size to sampling rate
320 // will be under-sampled, because we consistently discard this remainder.
321 next -= (size - c->next_sample);
324 c->next_sample = next;
326 runtime_MProf_Malloc(v, size);
330 __go_alloc(uintptr size)
332 return runtime_mallocgc(size, 0, FlagNoInvokeGC);
335 // Free the object whose base pointer is v.
348 // If you change this also change mgc0.c:/^sweep,
349 // which has a copy of the guts of free.
353 runtime_throw("malloc/free - deadlock");
356 if(!runtime_mlookup(v, nil, nil, &s)) {
357 runtime_printf("free %p: not an allocated block\n", v);
358 runtime_throw("free runtime_mlookup");
361 sizeclass = s->sizeclass;
362 // Objects that are smaller than TinySize can be allocated using tiny alloc,
363 // if then such object is combined with an object with finalizer, we will crash.
365 runtime_throw("freeing too small block");
367 if(runtime_debug.allocfreetrace)
368 runtime_tracefree(v, size);
370 // Ensure that the span is swept.
371 // If we free into an unswept span, we will corrupt GC bitmaps.
372 runtime_MSpan_EnsureSwept(s);
374 if(s->specials != nil)
375 runtime_freeallspecials(s, v, size);
381 // Must mark v freed before calling unmarkspan and MHeap_Free:
382 // they might coalesce v into other spans and change the bitmap further.
383 runtime_markfreed(v);
384 runtime_unmarkspan(v, 1<<PageShift);
385 // NOTE(rsc,dvyukov): The original implementation of efence
386 // in CL 22060046 used SysFree instead of SysFault, so that
387 // the operating system would eventually give the memory
388 // back to us again, so that an efence program could run
389 // longer without running out of memory. Unfortunately,
390 // calling SysFree here without any kind of adjustment of the
391 // heap data structures means that when the memory does
392 // come back to us, we have the wrong metadata for it, either in
393 // the MSpan structures or in the garbage collection bitmap.
394 // Using SysFault here means that the program will run out of
395 // memory fairly quickly in efence mode, but at least it won't
396 // have mysterious crashes due to confused memory reuse.
397 // It should be possible to switch back to SysFree if we also
398 // implement and then call some kind of MHeap_DeleteSpan.
399 if(runtime_debug.efence)
400 runtime_SysFault((void*)(s->start<<PageShift), size);
402 runtime_MHeap_Free(&runtime_mheap, s, 1);
403 c->local_nlargefree++;
404 c->local_largefree += size;
407 if(size > 2*sizeof(uintptr))
408 ((uintptr*)v)[1] = (uintptr)0xfeedfeedfeedfeedll; // mark as "needs to be zeroed"
409 else if(size > sizeof(uintptr))
410 ((uintptr*)v)[1] = 0;
411 // Must mark v freed before calling MCache_Free:
412 // it might coalesce v and other blocks into a bigger span
413 // and change the bitmap further.
414 c->local_nsmallfree[sizeclass]++;
415 c->local_cachealloc -= size;
416 if(c->alloc[sizeclass] == s) {
417 // We own the span, so we can just add v to the freelist
418 runtime_markfreed(v);
419 ((MLink*)v)->next = s->freelist;
423 // Someone else owns this span. Add to free queue.
424 runtime_MCache_Free(c, v, sizeclass, size);
431 runtime_mlookup(void *v, byte **base, uintptr *size, MSpan **sp)
440 m->mcache->local_nlookup++;
441 if (sizeof(void*) == 4 && m->mcache->local_nlookup >= (1<<30)) {
442 // purge cache stats to prevent overflow
443 runtime_lock(&runtime_mheap);
444 runtime_purgecachedstats(m->mcache);
445 runtime_unlock(&runtime_mheap);
448 s = runtime_MHeap_LookupMaybe(&runtime_mheap, v);
452 runtime_checkfreed(v, 1);
460 p = (byte*)((uintptr)s->start<<PageShift);
461 if(s->sizeclass == 0) {
466 *size = s->npages<<PageShift;
472 i = ((byte*)v - p)/n;
482 runtime_purgecachedstats(MCache *c)
487 // Protected by either heap or GC lock.
489 mstats.heap_alloc += c->local_cachealloc;
490 c->local_cachealloc = 0;
491 mstats.nlookup += c->local_nlookup;
492 c->local_nlookup = 0;
493 h->largefree += c->local_largefree;
494 c->local_largefree = 0;
495 h->nlargefree += c->local_nlargefree;
496 c->local_nlargefree = 0;
497 for(i=0; i<(int32)nelem(c->local_nsmallfree); i++) {
498 h->nsmallfree[i] += c->local_nsmallfree[i];
499 c->local_nsmallfree[i] = 0;
503 extern uintptr runtime_sizeof_C_MStats
504 __asm__ (GOSYM_PREFIX "runtime.Sizeof_C_MStats");
506 // Size of the trailing by_size array differs between Go and C,
507 // NumSizeClasses was changed, but we can not change Go struct because of backward compatibility.
508 // sizeof_C_MStats is what C thinks about size of Go struct.
510 // Initialized in mallocinit because it's defined in go/runtime/mem.go.
512 #define MaxArena32 (2U<<30)
515 runtime_mallocinit(void)
518 uintptr arena_size, bitmap_size, spans_size, p_size;
524 runtime_sizeof_C_MStats = sizeof(MStats) - (NumSizeClasses - 61) * sizeof(mstats.by_size[0]);
542 if(runtime_class_to_size[TinySizeClass] != TinySize)
543 runtime_throw("bad TinySizeClass");
545 // limit = runtime_memlimit();
546 // See https://code.google.com/p/go/issues/detail?id=5049
547 // TODO(rsc): Fix after 1.1.
550 // Set up the allocation arena, a contiguous area of memory where
551 // allocated data will be found. The arena begins with a bitmap large
552 // enough to hold 4 bits per allocated word.
553 if(sizeof(void*) == 8 && (limit == 0 || limit > (1<<30))) {
554 // On a 64-bit machine, allocate from a single contiguous reservation.
555 // 128 GB (MaxMem) should be big enough for now.
557 // The code will work with the reservation at any address, but ask
558 // SysReserve to use 0x0000XXc000000000 if possible (XX=00...7f).
559 // Allocating a 128 GB region takes away 37 bits, and the amd64
560 // doesn't let us choose the top 17 bits, so that leaves the 11 bits
561 // in the middle of 0x00c0 for us to choose. Choosing 0x00c0 means
562 // that the valid memory addresses will begin 0x00c0, 0x00c1, ..., 0x00df.
563 // In little-endian, that's c0 00, c1 00, ..., df 00. None of those are valid
564 // UTF-8 sequences, and they are otherwise as far away from
565 // ff (likely a common byte) as possible. If that fails, we try other 0xXXc0
566 // addresses. An earlier attempt to use 0x11f8 caused out of memory errors
567 // on OS X during thread allocations. 0x00c0 causes conflicts with
568 // AddressSanitizer which reserves all memory up to 0x0100.
569 // These choices are both for debuggability and to reduce the
570 // odds of the conservative garbage collector not collecting memory
571 // because some non-pointer block of memory had a bit pattern
572 // that matched a memory address.
574 // Actually we reserve 136 GB (because the bitmap ends up being 8 GB)
575 // but it hardly matters: e0 00 is not valid UTF-8 either.
577 // If this fails we fall back to the 32 bit memory mechanism
579 bitmap_size = arena_size / (sizeof(void*)*8/4);
580 spans_size = arena_size / PageSize * sizeof(runtime_mheap.spans[0]);
581 spans_size = ROUND(spans_size, PageSize);
582 for(i = 0; i < HeapBaseOptions; i++) {
584 p_size = bitmap_size + spans_size + arena_size + PageSize;
585 p = runtime_SysReserve(p, p_size, &reserved);
591 // On a 32-bit machine, we can't typically get away
592 // with a giant virtual address space reservation.
593 // Instead we map the memory information bitmap
594 // immediately after the data segment, large enough
595 // to handle another 2GB of mappings (256 MB),
596 // along with a reservation for another 512 MB of memory.
597 // When that gets used up, we'll start asking the kernel
598 // for any memory anywhere and hope it's in the 2GB
599 // following the bitmap (presumably the executable begins
600 // near the bottom of memory, so we'll have to use up
601 // most of memory before the kernel resorts to giving out
602 // memory before the beginning of the text segment).
604 // Alternatively we could reserve 512 MB bitmap, enough
605 // for 4GB of mappings, and then accept any memory the
606 // kernel threw at us, but normally that's a waste of 512 MB
607 // of address space, which is probably too much in a 32-bit world.
608 bitmap_size = MaxArena32 / (sizeof(void*)*8/4);
609 arena_size = 512<<20;
610 spans_size = MaxArena32 / PageSize * sizeof(runtime_mheap.spans[0]);
611 if(limit > 0 && arena_size+bitmap_size+spans_size > limit) {
612 bitmap_size = (limit / 9) & ~((1<<PageShift) - 1);
613 arena_size = bitmap_size * 8;
614 spans_size = arena_size / PageSize * sizeof(runtime_mheap.spans[0]);
616 spans_size = ROUND(spans_size, PageSize);
618 // SysReserve treats the address we ask for, end, as a hint,
619 // not as an absolute requirement. If we ask for the end
620 // of the data segment but the operating system requires
621 // a little more space before we can start allocating, it will
622 // give out a slightly higher pointer. Except QEMU, which
623 // is buggy, as usual: it won't adjust the pointer upward.
624 // So adjust it upward a little bit ourselves: 1/4 MB to get
625 // away from the running binary image and then round up
627 p = (byte*)ROUND((uintptr)_end + (1<<18), 1<<20);
628 p_size = bitmap_size + spans_size + arena_size + PageSize;
629 p = runtime_SysReserve(p, p_size, &reserved);
631 runtime_throw("runtime: cannot reserve arena virtual address space");
634 // PageSize can be larger than OS definition of page size,
635 // so SysReserve can give us a PageSize-unaligned pointer.
636 // To overcome this we ask for PageSize more and round up the pointer.
637 p1 = (byte*)ROUND((uintptr)p, PageSize);
639 runtime_mheap.spans = (MSpan**)p1;
640 runtime_mheap.bitmap = p1 + spans_size;
641 runtime_mheap.arena_start = p1 + spans_size + bitmap_size;
642 runtime_mheap.arena_used = runtime_mheap.arena_start;
643 runtime_mheap.arena_end = p + p_size;
644 runtime_mheap.arena_reserved = reserved;
646 if(((uintptr)runtime_mheap.arena_start & (PageSize-1)) != 0)
647 runtime_throw("misrounded allocation in mallocinit");
649 // Initialize the rest of the allocator.
650 runtime_MHeap_Init(&runtime_mheap);
651 runtime_m()->mcache = runtime_allocmcache();
654 runtime_free(runtime_malloc(TinySize));
658 runtime_MHeap_SysAlloc(MHeap *h, uintptr n)
665 if(n > (uintptr)(h->arena_end - h->arena_used)) {
666 // We are in 32-bit mode, maybe we didn't use all possible address space yet.
667 // Reserve some more space.
670 p_size = ROUND(n + PageSize, 256<<20);
671 new_end = h->arena_end + p_size;
672 if(new_end <= h->arena_start + MaxArena32) {
673 // TODO: It would be bad if part of the arena
674 // is reserved and part is not.
675 p = runtime_SysReserve(h->arena_end, p_size, &reserved);
676 if(p == h->arena_end) {
677 h->arena_end = new_end;
678 h->arena_reserved = reserved;
680 else if(p+p_size <= h->arena_start + MaxArena32) {
681 // Keep everything page-aligned.
682 // Our pages are bigger than hardware pages.
683 h->arena_end = p+p_size;
684 h->arena_used = p + (-(uintptr)p&(PageSize-1));
685 h->arena_reserved = reserved;
689 runtime_SysFree(p, p_size, &stat);
693 if(n <= (uintptr)(h->arena_end - h->arena_used)) {
694 // Keep taking from our reservation.
696 runtime_SysMap(p, n, h->arena_reserved, &mstats.heap_sys);
698 runtime_MHeap_MapBits(h);
699 runtime_MHeap_MapSpans(h);
701 runtime_racemapshadow(p, n);
703 if(((uintptr)p & (PageSize-1)) != 0)
704 runtime_throw("misrounded allocation in MHeap_SysAlloc");
708 // If using 64-bit, our reservation is all we have.
709 if((uintptr)(h->arena_end - h->arena_start) >= MaxArena32)
712 // On 32-bit, once the reservation is gone we can
713 // try to get memory at a location chosen by the OS
714 // and hope that it is in the range we allocated bitmap for.
715 p_size = ROUND(n, PageSize) + PageSize;
716 p = runtime_SysAlloc(p_size, &mstats.heap_sys);
720 if(p < h->arena_start || (uintptr)(p+p_size - h->arena_start) >= MaxArena32) {
721 runtime_printf("runtime: memory allocated by OS (%p) not in usable range [%p,%p)\n",
722 p, h->arena_start, h->arena_start+MaxArena32);
723 runtime_SysFree(p, p_size, &mstats.heap_sys);
728 p += -(uintptr)p & (PageSize-1);
729 if(p+n > h->arena_used) {
731 if(p_end > h->arena_end)
732 h->arena_end = p_end;
733 runtime_MHeap_MapBits(h);
734 runtime_MHeap_MapSpans(h);
736 runtime_racemapshadow(p, n);
739 if(((uintptr)p & (PageSize-1)) != 0)
740 runtime_throw("misrounded allocation in MHeap_SysAlloc");
753 PersistentAllocChunk = 256<<10,
754 PersistentAllocMaxBlock = 64<<10, // VM reservation granularity is 64K on windows
757 // Wrapper around SysAlloc that can allocate small chunks.
758 // There is no associated free operation.
759 // Intended for things like function/type/debug-related persistent data.
760 // If align is 0, uses default align (currently 8).
762 runtime_persistentalloc(uintptr size, uintptr align, uint64 *stat)
768 runtime_throw("persistentalloc: align is not a power of 2");
770 runtime_throw("persistentalloc: align is too large");
773 if(size >= PersistentAllocMaxBlock)
774 return runtime_SysAlloc(size, stat);
775 runtime_lock(&persistent);
776 persistent.pos = (byte*)ROUND((uintptr)persistent.pos, align);
777 if(persistent.pos + size > persistent.end) {
778 persistent.pos = runtime_SysAlloc(PersistentAllocChunk, &mstats.other_sys);
779 if(persistent.pos == nil) {
780 runtime_unlock(&persistent);
781 runtime_throw("runtime: cannot allocate memory");
783 persistent.end = persistent.pos + PersistentAllocChunk;
786 persistent.pos += size;
787 runtime_unlock(&persistent);
788 if(stat != &mstats.other_sys) {
789 // reaccount the allocation against provided stat
790 runtime_xadd64(stat, size);
791 runtime_xadd64(&mstats.other_sys, -(uint64)size);
797 settype(MSpan *s, void *v, uintptr typ)
799 uintptr size, ofs, j, t;
800 uintptr ntypes, nbytes2, nbytes3;
804 if(s->sizeclass == 0) {
805 s->types.compression = MTypes_Single;
810 ofs = ((uintptr)v - (s->start<<PageShift)) / size;
812 switch(s->types.compression) {
814 ntypes = (s->npages << PageShift) / size;
815 nbytes3 = 8*sizeof(uintptr) + 1*ntypes;
816 data3 = runtime_mallocgc(nbytes3, 0, FlagNoProfiling|FlagNoScan|FlagNoInvokeGC);
817 s->types.compression = MTypes_Bytes;
818 s->types.data = (uintptr)data3;
819 ((uintptr*)data3)[1] = typ;
820 data3[8*sizeof(uintptr) + ofs] = 1;
824 ((uintptr*)s->types.data)[ofs] = typ;
828 data3 = (byte*)s->types.data;
830 if(((uintptr*)data3)[j] == typ) {
833 if(((uintptr*)data3)[j] == 0) {
834 ((uintptr*)data3)[j] = typ;
839 data3[8*sizeof(uintptr) + ofs] = j;
841 ntypes = (s->npages << PageShift) / size;
842 nbytes2 = ntypes * sizeof(uintptr);
843 data2 = runtime_mallocgc(nbytes2, 0, FlagNoProfiling|FlagNoScan|FlagNoInvokeGC);
844 s->types.compression = MTypes_Words;
845 s->types.data = (uintptr)data2;
847 // Move the contents of data3 to data2. Then deallocate data3.
848 for(j=0; j<ntypes; j++) {
849 t = data3[8*sizeof(uintptr) + j];
850 t = ((uintptr*)data3)[t];
860 runtime_gettype(void *v)
866 s = runtime_MHeap_LookupMaybe(&runtime_mheap, v);
869 switch(s->types.compression) {
876 ofs = (uintptr)v - (s->start<<PageShift);
877 t = ((uintptr*)s->types.data)[ofs/s->elemsize];
880 ofs = (uintptr)v - (s->start<<PageShift);
881 data = (byte*)s->types.data;
882 t = data[8*sizeof(uintptr) + ofs/s->elemsize];
883 t = ((uintptr*)data)[t];
886 runtime_throw("runtime_gettype: invalid compression kind");
889 runtime_printf("%p -> %d,%X\n", v, (int32)s->types.compression, (int64)t);
899 runtime_mal(uintptr n)
901 return runtime_mallocgc(n, 0, 0);
904 func new(typ *Type) (ret *uint8) {
905 ret = runtime_mallocgc(typ->__size, (uintptr)typ | TypeInfo_SingleObject, typ->kind&KindNoPointers ? FlagNoScan : 0);
909 cnew(const Type *typ, intgo n, int32 objtyp)
911 if((objtyp&(PtrSize-1)) != objtyp)
912 runtime_throw("runtime: invalid objtyp");
913 if(n < 0 || (typ->__size > 0 && (uintptr)n > (MaxMem/typ->__size)))
914 runtime_panicstring("runtime: allocation size out of range");
915 return runtime_mallocgc(typ->__size*n, (uintptr)typ | objtyp, typ->kind&KindNoPointers ? FlagNoScan : 0);
918 // same as runtime_new, but callable from C
920 runtime_cnew(const Type *typ)
922 return cnew(typ, 1, TypeInfo_SingleObject);
926 runtime_cnewarray(const Type *typ, intgo n)
928 return cnew(typ, n, TypeInfo_Array);
932 runtime_gc(2); // force GC and do eager sweep
935 func SetFinalizer(obj Eface, finalizer Eface) {
942 if(obj.__type_descriptor == nil) {
943 runtime_printf("runtime.SetFinalizer: first argument is nil interface\n");
946 if(obj.__type_descriptor->__code != GO_PTR) {
947 runtime_printf("runtime.SetFinalizer: first argument is %S, not pointer\n", *obj.__type_descriptor->__reflection);
950 ot = (const PtrType*)obj.type;
951 // As an implementation detail we do not run finalizers for zero-sized objects,
952 // because we use &runtime_zerobase for all such allocations.
953 if(ot->__element_type != nil && ot->__element_type->__size == 0)
955 // The following check is required for cases when a user passes a pointer to composite literal,
956 // but compiler makes it a pointer to global. For example:
957 // var Foo = &Object{}
959 // runtime.SetFinalizer(Foo, nil)
962 if((byte*)obj.__object < runtime_mheap.arena_start || runtime_mheap.arena_used <= (byte*)obj.__object)
964 if(!runtime_mlookup(obj.__object, &base, &size, nil) || obj.__object != base) {
965 // As an implementation detail we allow to set finalizers for an inner byte
966 // of an object if it could come from tiny alloc (see mallocgc for details).
967 if(ot->__element_type == nil || (ot->__element_type->__code&KindNoPointers) == 0 || ot->__element_type->__size >= TinySize) {
968 runtime_printf("runtime.SetFinalizer: pointer not at beginning of allocated block (%p)\n", obj.__object);
972 if(finalizer.__type_descriptor != nil) {
973 runtime_createfing();
974 if(finalizer.__type_descriptor->__code != GO_FUNC)
976 ft = (const FuncType*)finalizer.__type_descriptor;
977 if(ft->__dotdotdot || ft->__in.__count != 1)
979 fint = *(Type**)ft->__in.__values;
980 if(__go_type_descriptors_equal(fint, obj.__type_descriptor)) {
982 } else if(fint->__code == GO_PTR && (fint->__uncommon == nil || fint->__uncommon->__name == nil || obj.type->__uncommon == nil || obj.type->__uncommon->__name == nil) && __go_type_descriptors_equal(((const PtrType*)fint)->__element_type, ((const PtrType*)obj.type)->__element_type)) {
983 // ok - not same type, but both pointers,
984 // one or the other is unnamed, and same element type, so assignable.
985 } else if(fint->kind == GO_INTERFACE && ((const InterfaceType*)fint)->__methods.__count == 0) {
986 // ok - satisfies empty interface
987 } else if(fint->kind == GO_INTERFACE && __go_convert_interface_2(fint, obj.__type_descriptor, 1) != nil) {
988 // ok - satisfies non-empty interface
992 ot = (const PtrType*)obj.__type_descriptor;
993 if(!runtime_addfinalizer(obj.__object, *(FuncVal**)finalizer.__object, ft, ot)) {
994 runtime_printf("runtime.SetFinalizer: finalizer already set\n");
998 // NOTE: asking to remove a finalizer when there currently isn't one set is OK.
999 runtime_removefinalizer(obj.__object);
1004 runtime_printf("runtime.SetFinalizer: cannot pass %S to finalizer %S\n", *obj.__type_descriptor->__reflection, *finalizer.__type_descriptor->__reflection);
1006 runtime_throw("runtime.SetFinalizer");