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.
19 // Map gccgo field names to gc field names.
20 // Type aka __go_type_descriptor
22 #define string __reflection
24 // GCCGO SPECIFIC CHANGE
26 // There is a long comment in runtime_mallocinit about where to put the heap
27 // on a 64-bit system. It makes assumptions that are not valid on linux/arm64
28 // -- it assumes user space can choose the lower 47 bits of a pointer, but on
29 // linux/arm64 we can only choose the lower 39 bits. This means the heap is
30 // roughly a quarter of the available address space and we cannot choose a bit
31 // pattern that all pointers will have -- luckily the GC is mostly precise
32 // these days so this doesn't matter all that much. The kernel (as of 3.13)
33 // will allocate address space starting either down from 0x7fffffffff or up
34 // from 0x2000000000, so we put the heap roughly in the middle of these two
35 // addresses to minimize the chance that a non-heap allocation will get in the
38 // This all means that there isn't much point in trying 256 different
39 // locations for the heap on such systems.
41 #define HeapBase(i) ((void*)(uintptr)(0x40ULL<<32))
42 #define HeapBaseOptions 1
44 #define HeapBase(i) ((void*)(uintptr)(i<<40|0x00c0ULL<<32))
45 #define HeapBaseOptions 0x80
47 // END GCCGO SPECIFIC CHANGE
49 // Mark mheap as 'no pointers', it does not contain interesting pointers but occupies ~45K.
52 int32 runtime_checking;
54 extern volatile intgo runtime_MemProfileRate
55 __asm__ (GOSYM_PREFIX "runtime.MemProfileRate");
57 static MSpan* largealloc(uint32, uintptr*);
58 static void runtime_profilealloc(void *v, uintptr size);
59 static void settype(MSpan *s, void *v, uintptr typ);
61 // Allocate an object of at least size bytes.
62 // Small objects are allocated from the per-thread cache's free lists.
63 // Large objects (> 32 kB) are allocated straight from the heap.
64 // If the block will be freed with runtime_free(), typ must be 0.
66 runtime_mallocgc(uintptr size, uintptr typ, uint32 flag)
71 uintptr tinysize, size1;
81 // All 0-length allocations use this pointer.
82 // The language does not require the allocations to
83 // have distinct values.
84 return runtime_getZerobase();
91 if(m->mcache == nil && m->ncgo > 0) {
92 // For gccgo this case can occur when a cgo or SWIG function
93 // has an interface return type and the function
94 // returns a non-pointer, so memory allocation occurs
95 // after syscall.Cgocall but before syscall.CgocallDone.
96 // We treat it as a callback.
97 runtime_exitsyscall(0);
100 flag |= FlagNoInvokeGC;
103 if(runtime_gcwaiting() && g != m->g0 && m->locks == 0 && !(flag & FlagNoInvokeGC) && m->preemptoff.len == 0) {
108 runtime_throw("malloc/free - deadlock");
109 // Disable preemption during settype.
110 // We can not use m->mallocing for this, because settype calls mallocgc.
114 if(DebugTypeAtBlockEnd)
115 size += sizeof(uintptr);
118 if(!runtime_debug.efence && size <= MaxSmallSize) {
119 if((flag&(FlagNoScan|FlagNoGC)) == FlagNoScan && size < TinySize) {
122 // Tiny allocator combines several tiny allocation requests
123 // into a single memory block. The resulting memory block
124 // is freed when all subobjects are unreachable. The subobjects
125 // must be FlagNoScan (don't have pointers), this ensures that
126 // the amount of potentially wasted memory is bounded.
128 // Size of the memory block used for combining (TinySize) is tunable.
129 // Current setting is 16 bytes, which relates to 2x worst case memory
130 // wastage (when all but one subobjects are unreachable).
131 // 8 bytes would result in no wastage at all, but provides less
132 // opportunities for combining.
133 // 32 bytes provides more opportunities for combining,
134 // but can lead to 4x worst case wastage.
135 // The best case winning is 8x regardless of block size.
137 // Objects obtained from tiny allocator must not be freed explicitly.
138 // So when an object will be freed explicitly, we ensure that
139 // its size >= TinySize.
141 // SetFinalizer has a special case for objects potentially coming
142 // from tiny allocator, it such case it allows to set finalizers
143 // for an inner byte of a memory block.
145 // The main targets of tiny allocator are small strings and
146 // standalone escaping variables. On a json benchmark
147 // the allocator reduces number of allocations by ~12% and
148 // reduces heap size by ~20%.
150 tinysize = c->tinysize;
151 if(size <= tinysize) {
153 // Align tiny pointer for required (conservative) alignment.
155 tiny = (byte*)ROUND((uintptr)tiny, 8);
156 else if((size&3) == 0)
157 tiny = (byte*)ROUND((uintptr)tiny, 4);
158 else if((size&1) == 0)
159 tiny = (byte*)ROUND((uintptr)tiny, 2);
160 size1 = size + (tiny - (byte*)c->tiny);
161 if(size1 <= tinysize) {
162 // The object fits into existing tiny block.
164 c->tiny = (byte*)c->tiny + size1;
165 c->tinysize -= size1;
169 runtime_entersyscall(0);
173 // Allocate a new TinySize block.
174 s = c->alloc[TinySizeClass];
175 if(s->freelist == nil)
176 s = runtime_MCache_Refill(c, TinySizeClass);
181 if(next != nil) // prefetching nil leads to a DTLB miss
185 // See if we need to replace the existing tiny block with the new one
186 // based on amount of remaining free space.
187 if(TinySize-size > tinysize) {
188 c->tiny = (byte*)v + size;
189 c->tinysize = TinySize - size;
194 // Allocate from mcache free lists.
195 // Inlined version of SizeToClass().
197 sizeclass = runtime_size_to_class8[(size+7)>>3];
199 sizeclass = runtime_size_to_class128[(size-1024+127) >> 7];
200 size = runtime_class_to_size[sizeclass];
201 s = c->alloc[sizeclass];
202 if(s->freelist == nil)
203 s = runtime_MCache_Refill(c, sizeclass);
208 if(next != nil) // prefetching nil leads to a DTLB miss
210 if(!(flag & FlagNoZero)) {
212 // block is zeroed iff second word is zero ...
213 if(size > 2*sizeof(uintptr) && ((uintptr*)v)[1] != 0)
214 runtime_memclr((byte*)v, size);
217 c->local_cachealloc += size;
219 // Allocate directly from heap.
220 s = largealloc(flag, &size);
221 v = (void*)(s->start << PageShift);
226 else if(!(flag & FlagNoScan))
229 if(DebugTypeAtBlockEnd)
230 *(uintptr*)((uintptr)v+size-sizeof(uintptr)) = typ;
233 // TODO: save type even if FlagNoScan? Potentially expensive but might help
234 // heap profiling/tracing.
235 if(UseSpanType && !(flag & FlagNoScan) && typ != 0)
238 if(runtime_debug.allocfreetrace)
239 runtime_tracealloc(v, size, typ);
241 if(!(flag & FlagNoProfiling) && (rate = runtime_MemProfileRate) > 0) {
242 if(size < (uintptr)rate && size < (uintptr)(uint32)c->next_sample)
243 c->next_sample -= size;
245 runtime_profilealloc(v, size);
251 if(!(flag & FlagNoInvokeGC) && pmstats->heap_alloc >= pmstats->next_gc)
255 runtime_entersyscall(0);
261 largealloc(uint32 flag, uintptr *sizep)
263 uintptr npages, size;
267 // Allocate directly from heap.
269 if(size + PageSize < size)
270 runtime_throw("out of memory");
271 npages = size >> PageShift;
272 if((size & PageMask) != 0)
274 s = runtime_MHeap_Alloc(&runtime_mheap, npages, 0, 1, !(flag & FlagNoZero));
276 runtime_throw("out of memory");
277 s->limit = (uintptr)((byte*)(s->start<<PageShift) + size);
278 *sizep = npages<<PageShift;
279 v = (void*)(s->start << PageShift);
280 // setup for mark sweep
281 runtime_markspan(v, 0, 0, true);
286 runtime_profilealloc(void *v, uintptr size)
292 c = runtime_m()->mcache;
293 rate = runtime_MemProfileRate;
295 // pick next profile time
296 // If you change this, also change allocmcache.
297 if(rate > 0x3fffffff) // make 2*rate not overflow
299 next = runtime_fastrand1() % (2*rate);
300 // Subtract the "remainder" of the current allocation.
301 // Otherwise objects that are close in size to sampling rate
302 // will be under-sampled, because we consistently discard this remainder.
303 next -= (size - c->next_sample);
306 c->next_sample = next;
308 runtime_MProf_Malloc(v, size);
312 __go_alloc(uintptr size)
314 return runtime_mallocgc(size, 0, FlagNoInvokeGC);
317 // Free the object whose base pointer is v.
330 // If you change this also change mgc0.c:/^sweep,
331 // which has a copy of the guts of free.
335 runtime_throw("malloc/free - deadlock");
338 if(!runtime_mlookup(v, nil, nil, &s)) {
339 runtime_printf("free %p: not an allocated block\n", v);
340 runtime_throw("free runtime_mlookup");
343 sizeclass = s->sizeclass;
344 // Objects that are smaller than TinySize can be allocated using tiny alloc,
345 // if then such object is combined with an object with finalizer, we will crash.
347 runtime_throw("freeing too small block");
349 if(runtime_debug.allocfreetrace)
350 runtime_tracefree(v, size);
352 // Ensure that the span is swept.
353 // If we free into an unswept span, we will corrupt GC bitmaps.
354 runtime_MSpan_EnsureSwept(s);
356 if(s->specials != nil)
357 runtime_freeallspecials(s, v, size);
363 // Must mark v freed before calling unmarkspan and MHeap_Free:
364 // they might coalesce v into other spans and change the bitmap further.
365 runtime_markfreed(v);
366 runtime_unmarkspan(v, 1<<PageShift);
367 // NOTE(rsc,dvyukov): The original implementation of efence
368 // in CL 22060046 used SysFree instead of SysFault, so that
369 // the operating system would eventually give the memory
370 // back to us again, so that an efence program could run
371 // longer without running out of memory. Unfortunately,
372 // calling SysFree here without any kind of adjustment of the
373 // heap data structures means that when the memory does
374 // come back to us, we have the wrong metadata for it, either in
375 // the MSpan structures or in the garbage collection bitmap.
376 // Using SysFault here means that the program will run out of
377 // memory fairly quickly in efence mode, but at least it won't
378 // have mysterious crashes due to confused memory reuse.
379 // It should be possible to switch back to SysFree if we also
380 // implement and then call some kind of MHeap_DeleteSpan.
381 if(runtime_debug.efence)
382 runtime_SysFault((void*)(s->start<<PageShift), size);
384 runtime_MHeap_Free(&runtime_mheap, s, 1);
385 c->local_nlargefree++;
386 c->local_largefree += size;
389 if(size > 2*sizeof(uintptr))
390 ((uintptr*)v)[1] = (uintptr)0xfeedfeedfeedfeedll; // mark as "needs to be zeroed"
391 else if(size > sizeof(uintptr))
392 ((uintptr*)v)[1] = 0;
393 // Must mark v freed before calling MCache_Free:
394 // it might coalesce v and other blocks into a bigger span
395 // and change the bitmap further.
396 c->local_nsmallfree[sizeclass]++;
397 c->local_cachealloc -= size;
398 if(c->alloc[sizeclass] == s) {
399 // We own the span, so we can just add v to the freelist
400 runtime_markfreed(v);
401 ((MLink*)v)->next = s->freelist;
405 // Someone else owns this span. Add to free queue.
406 runtime_MCache_Free(c, v, sizeclass, size);
413 runtime_mlookup(void *v, byte **base, uintptr *size, MSpan **sp)
422 m->mcache->local_nlookup++;
423 if (sizeof(void*) == 4 && m->mcache->local_nlookup >= (1<<30)) {
424 // purge cache stats to prevent overflow
425 runtime_lock(&runtime_mheap);
426 runtime_purgecachedstats(m->mcache);
427 runtime_unlock(&runtime_mheap);
430 s = runtime_MHeap_LookupMaybe(&runtime_mheap, v);
434 runtime_checkfreed(v, 1);
442 p = (byte*)((uintptr)s->start<<PageShift);
443 if(s->sizeclass == 0) {
448 *size = s->npages<<PageShift;
454 i = ((byte*)v - p)/n;
464 runtime_purgecachedstats(MCache *c)
469 // Protected by either heap or GC lock.
471 mstats()->heap_alloc += (intptr)c->local_cachealloc;
472 c->local_cachealloc = 0;
473 mstats()->nlookup += c->local_nlookup;
474 c->local_nlookup = 0;
475 h->largefree += c->local_largefree;
476 c->local_largefree = 0;
477 h->nlargefree += c->local_nlargefree;
478 c->local_nlargefree = 0;
479 for(i=0; i<(int32)nelem(c->local_nsmallfree); i++) {
480 h->nsmallfree[i] += c->local_nsmallfree[i];
481 c->local_nsmallfree[i] = 0;
485 // Initialized in mallocinit because it's defined in go/runtime/mem.go.
487 #define MaxArena32 (2U<<30)
490 runtime_mallocinit(void)
493 uintptr arena_size, bitmap_size, spans_size, p_size;
516 if(runtime_class_to_size[TinySizeClass] != TinySize)
517 runtime_throw("bad TinySizeClass");
519 // limit = runtime_memlimit();
520 // See https://code.google.com/p/go/issues/detail?id=5049
521 // TODO(rsc): Fix after 1.1.
524 // Set up the allocation arena, a contiguous area of memory where
525 // allocated data will be found. The arena begins with a bitmap large
526 // enough to hold 4 bits per allocated word.
527 if(sizeof(void*) == 8 && (limit == 0 || limit > (1<<30))) {
528 // On a 64-bit machine, allocate from a single contiguous reservation.
529 // 128 GB (MaxMem) should be big enough for now.
531 // The code will work with the reservation at any address, but ask
532 // SysReserve to use 0x0000XXc000000000 if possible (XX=00...7f).
533 // Allocating a 128 GB region takes away 37 bits, and the amd64
534 // doesn't let us choose the top 17 bits, so that leaves the 11 bits
535 // in the middle of 0x00c0 for us to choose. Choosing 0x00c0 means
536 // that the valid memory addresses will begin 0x00c0, 0x00c1, ..., 0x00df.
537 // In little-endian, that's c0 00, c1 00, ..., df 00. None of those are valid
538 // UTF-8 sequences, and they are otherwise as far away from
539 // ff (likely a common byte) as possible. If that fails, we try other 0xXXc0
540 // addresses. An earlier attempt to use 0x11f8 caused out of memory errors
541 // on OS X during thread allocations. 0x00c0 causes conflicts with
542 // AddressSanitizer which reserves all memory up to 0x0100.
543 // These choices are both for debuggability and to reduce the
544 // odds of the conservative garbage collector not collecting memory
545 // because some non-pointer block of memory had a bit pattern
546 // that matched a memory address.
548 // Actually we reserve 136 GB (because the bitmap ends up being 8 GB)
549 // but it hardly matters: e0 00 is not valid UTF-8 either.
551 // If this fails we fall back to the 32 bit memory mechanism
553 bitmap_size = arena_size / (sizeof(void*)*8/4);
554 spans_size = arena_size / PageSize * sizeof(runtime_mheap.spans[0]);
555 spans_size = ROUND(spans_size, PageSize);
556 for(i = 0; i < HeapBaseOptions; i++) {
558 p_size = bitmap_size + spans_size + arena_size + PageSize;
559 p = runtime_SysReserve(p, p_size, &reserved);
565 // On a 32-bit machine, we can't typically get away
566 // with a giant virtual address space reservation.
567 // Instead we map the memory information bitmap
568 // immediately after the data segment, large enough
569 // to handle another 2GB of mappings (256 MB),
570 // along with a reservation for another 512 MB of memory.
571 // When that gets used up, we'll start asking the kernel
572 // for any memory anywhere and hope it's in the 2GB
573 // following the bitmap (presumably the executable begins
574 // near the bottom of memory, so we'll have to use up
575 // most of memory before the kernel resorts to giving out
576 // memory before the beginning of the text segment).
578 // Alternatively we could reserve 512 MB bitmap, enough
579 // for 4GB of mappings, and then accept any memory the
580 // kernel threw at us, but normally that's a waste of 512 MB
581 // of address space, which is probably too much in a 32-bit world.
582 bitmap_size = MaxArena32 / (sizeof(void*)*8/4);
583 arena_size = 512<<20;
584 spans_size = MaxArena32 / PageSize * sizeof(runtime_mheap.spans[0]);
585 if(limit > 0 && arena_size+bitmap_size+spans_size > limit) {
586 bitmap_size = (limit / 9) & ~((1<<PageShift) - 1);
587 arena_size = bitmap_size * 8;
588 spans_size = arena_size / PageSize * sizeof(runtime_mheap.spans[0]);
590 spans_size = ROUND(spans_size, PageSize);
592 // SysReserve treats the address we ask for, end, as a hint,
593 // not as an absolute requirement. If we ask for the end
594 // of the data segment but the operating system requires
595 // a little more space before we can start allocating, it will
596 // give out a slightly higher pointer. Except QEMU, which
597 // is buggy, as usual: it won't adjust the pointer upward.
598 // So adjust it upward a little bit ourselves: 1/4 MB to get
599 // away from the running binary image and then round up
606 p = (byte*)ROUND(end + (1<<18), 1<<20);
607 p_size = bitmap_size + spans_size + arena_size + PageSize;
608 p = runtime_SysReserve(p, p_size, &reserved);
610 runtime_throw("runtime: cannot reserve arena virtual address space");
613 // PageSize can be larger than OS definition of page size,
614 // so SysReserve can give us a PageSize-unaligned pointer.
615 // To overcome this we ask for PageSize more and round up the pointer.
616 p1 = (byte*)ROUND((uintptr)p, PageSize);
618 runtime_mheap.spans = (MSpan**)p1;
619 runtime_mheap.bitmap = p1 + spans_size;
620 runtime_mheap.arena_start = p1 + spans_size + bitmap_size;
621 runtime_mheap.arena_used = runtime_mheap.arena_start;
622 runtime_mheap.arena_end = p + p_size;
623 runtime_mheap.arena_reserved = reserved;
625 if(((uintptr)runtime_mheap.arena_start & (PageSize-1)) != 0)
626 runtime_throw("misrounded allocation in mallocinit");
628 // Initialize the rest of the allocator.
629 runtime_MHeap_Init(&runtime_mheap);
630 runtime_m()->mcache = runtime_allocmcache();
633 runtime_free(runtime_malloc(TinySize));
637 runtime_MHeap_SysAlloc(MHeap *h, uintptr n)
644 if(n > (uintptr)(h->arena_end - h->arena_used)) {
645 // We are in 32-bit mode, maybe we didn't use all possible address space yet.
646 // Reserve some more space.
649 p_size = ROUND(n + PageSize, 256<<20);
650 new_end = h->arena_end + p_size;
651 if(new_end <= h->arena_start + MaxArena32) {
652 // TODO: It would be bad if part of the arena
653 // is reserved and part is not.
654 p = runtime_SysReserve(h->arena_end, p_size, &reserved);
655 if(p == h->arena_end) {
656 h->arena_end = new_end;
657 h->arena_reserved = reserved;
659 else if(p+p_size <= h->arena_start + MaxArena32) {
660 // Keep everything page-aligned.
661 // Our pages are bigger than hardware pages.
662 h->arena_end = p+p_size;
663 h->arena_used = p + (-(uintptr)p&(PageSize-1));
664 h->arena_reserved = reserved;
668 runtime_SysFree(p, p_size, &stat);
672 if(n <= (uintptr)(h->arena_end - h->arena_used)) {
673 // Keep taking from our reservation.
675 runtime_SysMap(p, n, h->arena_reserved, &mstats()->heap_sys);
677 runtime_MHeap_MapBits(h);
678 runtime_MHeap_MapSpans(h);
680 if(((uintptr)p & (PageSize-1)) != 0)
681 runtime_throw("misrounded allocation in MHeap_SysAlloc");
685 // If using 64-bit, our reservation is all we have.
686 if((uintptr)(h->arena_end - h->arena_start) >= MaxArena32)
689 // On 32-bit, once the reservation is gone we can
690 // try to get memory at a location chosen by the OS
691 // and hope that it is in the range we allocated bitmap for.
692 p_size = ROUND(n, PageSize) + PageSize;
693 p = runtime_SysAlloc(p_size, &mstats()->heap_sys);
697 if(p < h->arena_start || (uintptr)(p+p_size - h->arena_start) >= MaxArena32) {
698 runtime_printf("runtime: memory allocated by OS (%p) not in usable range [%p,%p)\n",
699 p, h->arena_start, h->arena_start+MaxArena32);
700 runtime_SysFree(p, p_size, &mstats()->heap_sys);
705 p += -(uintptr)p & (PageSize-1);
706 if(p+n > h->arena_used) {
708 if(p_end > h->arena_end)
709 h->arena_end = p_end;
710 runtime_MHeap_MapBits(h);
711 runtime_MHeap_MapSpans(h);
714 if(((uintptr)p & (PageSize-1)) != 0)
715 runtime_throw("misrounded allocation in MHeap_SysAlloc");
728 PersistentAllocChunk = 256<<10,
729 PersistentAllocMaxBlock = 64<<10, // VM reservation granularity is 64K on windows
732 // Wrapper around SysAlloc that can allocate small chunks.
733 // There is no associated free operation.
734 // Intended for things like function/type/debug-related persistent data.
735 // If align is 0, uses default align (currently 8).
737 runtime_persistentalloc(uintptr size, uintptr align, uint64 *stat)
743 runtime_throw("persistentalloc: align is not a power of 2");
745 runtime_throw("persistentalloc: align is too large");
748 if(size >= PersistentAllocMaxBlock)
749 return runtime_SysAlloc(size, stat);
750 runtime_lock(&persistent);
751 persistent.pos = (byte*)ROUND((uintptr)persistent.pos, align);
752 if(persistent.pos + size > persistent.end) {
753 persistent.pos = runtime_SysAlloc(PersistentAllocChunk, &mstats()->other_sys);
754 if(persistent.pos == nil) {
755 runtime_unlock(&persistent);
756 runtime_throw("runtime: cannot allocate memory");
758 persistent.end = persistent.pos + PersistentAllocChunk;
761 persistent.pos += size;
762 runtime_unlock(&persistent);
763 if(stat != &mstats()->other_sys) {
764 // reaccount the allocation against provided stat
765 runtime_xadd64(stat, size);
766 runtime_xadd64(&mstats()->other_sys, -(uint64)size);
772 settype(MSpan *s, void *v, uintptr typ)
774 uintptr size, ofs, j, t;
775 uintptr ntypes, nbytes2, nbytes3;
779 if(s->sizeclass == 0) {
780 s->types.compression = MTypes_Single;
785 ofs = ((uintptr)v - (s->start<<PageShift)) / size;
787 switch(s->types.compression) {
789 ntypes = (s->npages << PageShift) / size;
790 nbytes3 = 8*sizeof(uintptr) + 1*ntypes;
791 data3 = runtime_mallocgc(nbytes3, 0, FlagNoProfiling|FlagNoScan|FlagNoInvokeGC);
792 s->types.compression = MTypes_Bytes;
793 s->types.data = (uintptr)data3;
794 ((uintptr*)data3)[1] = typ;
795 data3[8*sizeof(uintptr) + ofs] = 1;
799 ((uintptr*)s->types.data)[ofs] = typ;
803 data3 = (byte*)s->types.data;
805 if(((uintptr*)data3)[j] == typ) {
808 if(((uintptr*)data3)[j] == 0) {
809 ((uintptr*)data3)[j] = typ;
814 data3[8*sizeof(uintptr) + ofs] = j;
816 ntypes = (s->npages << PageShift) / size;
817 nbytes2 = ntypes * sizeof(uintptr);
818 data2 = runtime_mallocgc(nbytes2, 0, FlagNoProfiling|FlagNoScan|FlagNoInvokeGC);
819 s->types.compression = MTypes_Words;
820 s->types.data = (uintptr)data2;
822 // Move the contents of data3 to data2. Then deallocate data3.
823 for(j=0; j<ntypes; j++) {
824 t = data3[8*sizeof(uintptr) + j];
825 t = ((uintptr*)data3)[t];
835 runtime_gettype(void *v)
841 s = runtime_MHeap_LookupMaybe(&runtime_mheap, v);
844 switch(s->types.compression) {
851 ofs = (uintptr)v - (s->start<<PageShift);
852 t = ((uintptr*)s->types.data)[ofs/s->elemsize];
855 ofs = (uintptr)v - (s->start<<PageShift);
856 data = (byte*)s->types.data;
857 t = data[8*sizeof(uintptr) + ofs/s->elemsize];
858 t = ((uintptr*)data)[t];
861 runtime_throw("runtime_gettype: invalid compression kind");
864 runtime_printf("%p -> %d,%X\n", v, (int32)s->types.compression, (int64)t);
874 runtime_mal(uintptr n)
876 return runtime_mallocgc(n, 0, 0);
879 func new(typ *Type) (ret *uint8) {
880 ret = runtime_mallocgc(typ->__size, (uintptr)typ | TypeInfo_SingleObject, typ->kind&kindNoPointers ? FlagNoScan : 0);
884 runtime_docnew(const Type *typ, intgo n, int32 objtyp)
886 if((objtyp&(PtrSize-1)) != objtyp)
887 runtime_throw("runtime: invalid objtyp");
888 if(n < 0 || (typ->__size > 0 && (uintptr)n > (MaxMem/typ->__size)))
889 runtime_panicstring("runtime: allocation size out of range");
890 return runtime_mallocgc(typ->__size*n, (uintptr)typ | objtyp, typ->kind&kindNoPointers ? FlagNoScan : 0);
893 // same as runtime_new, but callable from C
895 runtime_cnew(const Type *typ)
897 return runtime_docnew(typ, 1, TypeInfo_SingleObject);
901 runtime_cnewarray(const Type *typ, intgo n)
903 return runtime_docnew(typ, n, TypeInfo_Array);
907 runtime_gc(2); // force GC and do eager sweep
910 func SetFinalizer(obj Eface, finalizer Eface) {
917 if((Type*)obj._type == nil) {
918 runtime_printf("runtime.SetFinalizer: first argument is nil interface\n");
921 if((((Type*)obj._type)->kind&kindMask) != GO_PTR) {
922 runtime_printf("runtime.SetFinalizer: first argument is %S, not pointer\n", *((Type*)obj._type)->__reflection);
925 ot = (const PtrType*)obj._type;
926 // As an implementation detail we do not run finalizers for zero-sized objects,
927 // because we use &runtime_zerobase for all such allocations.
928 if(ot->__element_type != nil && ot->__element_type->__size == 0)
930 // The following check is required for cases when a user passes a pointer to composite literal,
931 // but compiler makes it a pointer to global. For example:
932 // var Foo = &Object{}
934 // runtime.SetFinalizer(Foo, nil)
937 if((byte*)obj.data < runtime_mheap.arena_start || runtime_mheap.arena_used <= (byte*)obj.data)
939 if(!runtime_mlookup(obj.data, &base, &size, nil) || obj.data != base) {
940 // As an implementation detail we allow to set finalizers for an inner byte
941 // of an object if it could come from tiny alloc (see mallocgc for details).
942 if(ot->__element_type == nil || (ot->__element_type->kind&kindNoPointers) == 0 || ot->__element_type->__size >= TinySize) {
943 runtime_printf("runtime.SetFinalizer: pointer not at beginning of allocated block (%p)\n", obj.data);
947 if((Type*)finalizer._type != nil) {
948 runtime_createfing();
949 if((((Type*)finalizer._type)->kind&kindMask) != GO_FUNC)
951 ft = (const FuncType*)finalizer._type;
952 if(ft->__dotdotdot || ft->__in.__count != 1)
954 fint = *(Type**)ft->__in.__values;
955 if(__go_type_descriptors_equal(fint, (Type*)obj._type)) {
957 } else if((fint->kind&kindMask) == GO_PTR && (fint->__uncommon == nil || fint->__uncommon->__name == nil || ((Type*)obj._type)->__uncommon == nil || ((Type*)obj._type)->__uncommon->__name == nil) && __go_type_descriptors_equal(((const PtrType*)fint)->__element_type, ((const PtrType*)obj._type)->__element_type)) {
958 // ok - not same type, but both pointers,
959 // one or the other is unnamed, and same element type, so assignable.
960 } else if((fint->kind&kindMask) == GO_INTERFACE && ((const InterfaceType*)fint)->__methods.__count == 0) {
961 // ok - satisfies empty interface
962 } else if((fint->kind&kindMask) == GO_INTERFACE && getitab(fint, (Type*)obj._type, true) != nil) {
963 // ok - satisfies non-empty interface
967 ot = (const PtrType*)obj._type;
968 if(!runtime_addfinalizer(obj.data, *(FuncVal**)finalizer.data, ft, ot)) {
969 runtime_printf("runtime.SetFinalizer: finalizer already set\n");
973 // NOTE: asking to remove a finalizer when there currently isn't one set is OK.
974 runtime_removefinalizer(obj.data);
979 runtime_printf("runtime.SetFinalizer: cannot pass %S to finalizer %S\n", *((Type*)obj._type)->__reflection, *((Type*)finalizer._type)->__reflection);
981 runtime_throw("runtime.SetFinalizer");
984 func KeepAlive(x Eface) {