Importing Upstream version 4.8.2
[platform/upstream/gcc48.git] / libgo / runtime / malloc.goc
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.
4
5 // See malloc.h for overview.
6 //
7 // TODO(rsc): double-check stats.
8
9 package runtime
10 #include <stddef.h>
11 #include <errno.h>
12 #include <stdlib.h>
13 #include "go-alloc.h"
14 #include "runtime.h"
15 #include "arch.h"
16 #include "malloc.h"
17 #include "interface.h"
18 #include "go-type.h"
19 #include "race.h"
20
21 MHeap *runtime_mheap;
22
23 int32   runtime_checking;
24
25 extern MStats mstats;   // defined in zruntime_def_$GOOS_$GOARCH.go
26
27 extern volatile intgo runtime_MemProfileRate
28   __asm__ (GOSYM_PREFIX "runtime.MemProfileRate");
29
30 // Allocate an object of at least size bytes.
31 // Small objects are allocated from the per-thread cache's free lists.
32 // Large objects (> 32 kB) are allocated straight from the heap.
33 void*
34 runtime_mallocgc(uintptr size, uint32 flag, int32 dogc, int32 zeroed)
35 {
36         M *m;
37         G *g;
38         int32 sizeclass;
39         intgo rate;
40         MCache *c;
41         uintptr npages;
42         MSpan *s;
43         void *v;
44         bool incallback;
45
46         m = runtime_m();
47         g = runtime_g();
48
49         incallback = false;
50         if(m->mcache == nil && g->ncgo > 0) {
51                 // For gccgo this case can occur when a cgo or SWIG function
52                 // has an interface return type and the function
53                 // returns a non-pointer, so memory allocation occurs
54                 // after syscall.Cgocall but before syscall.CgocallDone.
55                 // We treat it as a callback.
56                 runtime_exitsyscall();
57                 m = runtime_m();
58                 incallback = true;
59                 dogc = false;
60         }
61
62         if(runtime_gcwaiting && g != m->g0 && m->locks == 0 && dogc) {
63                 runtime_gosched();
64                 m = runtime_m();
65         }
66         if(m->mallocing)
67                 runtime_throw("malloc/free - deadlock");
68         m->mallocing = 1;
69         if(size == 0)
70                 size = 1;
71
72         if(DebugTypeAtBlockEnd)
73                 size += sizeof(uintptr);
74
75         c = m->mcache;
76         c->local_nmalloc++;
77         if(size <= MaxSmallSize) {
78                 // Allocate from mcache free lists.
79                 sizeclass = runtime_SizeToClass(size);
80                 size = runtime_class_to_size[sizeclass];
81                 v = runtime_MCache_Alloc(c, sizeclass, size, zeroed);
82                 if(v == nil)
83                         runtime_throw("out of memory");
84                 c->local_alloc += size;
85                 c->local_total_alloc += size;
86                 c->local_by_size[sizeclass].nmalloc++;
87         } else {
88                 // TODO(rsc): Report tracebacks for very large allocations.
89
90                 // Allocate directly from heap.
91                 npages = size >> PageShift;
92                 if((size & PageMask) != 0)
93                         npages++;
94                 s = runtime_MHeap_Alloc(runtime_mheap, npages, 0, 1, zeroed);
95                 if(s == nil)
96                         runtime_throw("out of memory");
97                 size = npages<<PageShift;
98                 c->local_alloc += size;
99                 c->local_total_alloc += size;
100                 v = (void*)(s->start << PageShift);
101
102                 // setup for mark sweep
103                 runtime_markspan(v, 0, 0, true);
104         }
105
106         if (sizeof(void*) == 4 && c->local_total_alloc >= (1<<30)) {
107                 // purge cache stats to prevent overflow
108                 runtime_lock(runtime_mheap);
109                 runtime_purgecachedstats(c);
110                 runtime_unlock(runtime_mheap);
111         }
112
113         if(!(flag & FlagNoGC))
114                 runtime_markallocated(v, size, (flag&FlagNoPointers) != 0);
115
116         if(DebugTypeAtBlockEnd)
117                 *(uintptr*)((uintptr)v+size-sizeof(uintptr)) = 0;
118
119         m->mallocing = 0;
120
121         if(!(flag & FlagNoProfiling) && (rate = runtime_MemProfileRate) > 0) {
122                 if(size >= (uint32) rate)
123                         goto profile;
124                 if((uint32) m->mcache->next_sample > size)
125                         m->mcache->next_sample -= size;
126                 else {
127                         // pick next profile time
128                         // If you change this, also change allocmcache.
129                         if(rate > 0x3fffffff)   // make 2*rate not overflow
130                                 rate = 0x3fffffff;
131                         m->mcache->next_sample = runtime_fastrand1() % (2*rate);
132                 profile:
133                         runtime_setblockspecial(v, true);
134                         runtime_MProf_Malloc(v, size);
135                 }
136         }
137
138         if(dogc && mstats.heap_alloc >= mstats.next_gc)
139                 runtime_gc(0);
140
141         if(raceenabled) {
142                 runtime_racemalloc(v, size, m->racepc);
143                 m->racepc = nil;
144         }
145
146         if(incallback)
147                 runtime_entersyscall();
148
149         return v;
150 }
151
152 void*
153 __go_alloc(uintptr size)
154 {
155         return runtime_mallocgc(size, 0, 0, 1);
156 }
157
158 // Free the object whose base pointer is v.
159 void
160 __go_free(void *v)
161 {
162         M *m;
163         int32 sizeclass;
164         MSpan *s;
165         MCache *c;
166         uint32 prof;
167         uintptr size;
168
169         if(v == nil)
170                 return;
171         
172         // If you change this also change mgc0.c:/^sweep,
173         // which has a copy of the guts of free.
174
175         m = runtime_m();
176         if(m->mallocing)
177                 runtime_throw("malloc/free - deadlock");
178         m->mallocing = 1;
179
180         if(!runtime_mlookup(v, nil, nil, &s)) {
181                 runtime_printf("free %p: not an allocated block\n", v);
182                 runtime_throw("free runtime_mlookup");
183         }
184         prof = runtime_blockspecial(v);
185
186         if(raceenabled)
187                 runtime_racefree(v);
188
189         // Find size class for v.
190         sizeclass = s->sizeclass;
191         c = m->mcache;
192         if(sizeclass == 0) {
193                 // Large object.
194                 size = s->npages<<PageShift;
195                 *(uintptr*)(s->start<<PageShift) = (uintptr)0xfeedfeedfeedfeedll;       // mark as "needs to be zeroed"
196                 // Must mark v freed before calling unmarkspan and MHeap_Free:
197                 // they might coalesce v into other spans and change the bitmap further.
198                 runtime_markfreed(v, size);
199                 runtime_unmarkspan(v, 1<<PageShift);
200                 runtime_MHeap_Free(runtime_mheap, s, 1);
201         } else {
202                 // Small object.
203                 size = runtime_class_to_size[sizeclass];
204                 if(size > sizeof(uintptr))
205                         ((uintptr*)v)[1] = (uintptr)0xfeedfeedfeedfeedll;       // mark as "needs to be zeroed"
206                 // Must mark v freed before calling MCache_Free:
207                 // it might coalesce v and other blocks into a bigger span
208                 // and change the bitmap further.
209                 runtime_markfreed(v, size);
210                 c->local_by_size[sizeclass].nfree++;
211                 runtime_MCache_Free(c, v, sizeclass, size);
212         }
213         c->local_nfree++;
214         c->local_alloc -= size;
215         if(prof)
216                 runtime_MProf_Free(v, size);
217         m->mallocing = 0;
218 }
219
220 int32
221 runtime_mlookup(void *v, byte **base, uintptr *size, MSpan **sp)
222 {
223         M *m;
224         uintptr n, i;
225         byte *p;
226         MSpan *s;
227
228         m = runtime_m();
229
230         m->mcache->local_nlookup++;
231         if (sizeof(void*) == 4 && m->mcache->local_nlookup >= (1<<30)) {
232                 // purge cache stats to prevent overflow
233                 runtime_lock(runtime_mheap);
234                 runtime_purgecachedstats(m->mcache);
235                 runtime_unlock(runtime_mheap);
236         }
237
238         s = runtime_MHeap_LookupMaybe(runtime_mheap, v);
239         if(sp)
240                 *sp = s;
241         if(s == nil) {
242                 runtime_checkfreed(v, 1);
243                 if(base)
244                         *base = nil;
245                 if(size)
246                         *size = 0;
247                 return 0;
248         }
249
250         p = (byte*)((uintptr)s->start<<PageShift);
251         if(s->sizeclass == 0) {
252                 // Large object.
253                 if(base)
254                         *base = p;
255                 if(size)
256                         *size = s->npages<<PageShift;
257                 return 1;
258         }
259
260         if((byte*)v >= (byte*)s->limit) {
261                 // pointers past the last block do not count as pointers.
262                 return 0;
263         }
264
265         n = s->elemsize;
266         if(base) {
267                 i = ((byte*)v - p)/n;
268                 *base = p + i*n;
269         }
270         if(size)
271                 *size = n;
272
273         return 1;
274 }
275
276 MCache*
277 runtime_allocmcache(void)
278 {
279         intgo rate;
280         MCache *c;
281
282         runtime_lock(runtime_mheap);
283         c = runtime_FixAlloc_Alloc(&runtime_mheap->cachealloc);
284         mstats.mcache_inuse = runtime_mheap->cachealloc.inuse;
285         mstats.mcache_sys = runtime_mheap->cachealloc.sys;
286         runtime_unlock(runtime_mheap);
287         runtime_memclr((byte*)c, sizeof(*c));
288
289         // Set first allocation sample size.
290         rate = runtime_MemProfileRate;
291         if(rate > 0x3fffffff)   // make 2*rate not overflow
292                 rate = 0x3fffffff;
293         if(rate != 0)
294                 c->next_sample = runtime_fastrand1() % (2*rate);
295
296         return c;
297 }
298
299 void
300 runtime_freemcache(MCache *c)
301 {
302         runtime_MCache_ReleaseAll(c);
303         runtime_lock(runtime_mheap);
304         runtime_purgecachedstats(c);
305         runtime_FixAlloc_Free(&runtime_mheap->cachealloc, c);
306         runtime_unlock(runtime_mheap);
307 }
308
309 void
310 runtime_purgecachedstats(MCache *c)
311 {
312         // Protected by either heap or GC lock.
313         mstats.heap_alloc += c->local_cachealloc;
314         c->local_cachealloc = 0;
315         mstats.heap_objects += c->local_objects;
316         c->local_objects = 0;
317         mstats.nmalloc += c->local_nmalloc;
318         c->local_nmalloc = 0;
319         mstats.nfree += c->local_nfree;
320         c->local_nfree = 0;
321         mstats.nlookup += c->local_nlookup;
322         c->local_nlookup = 0;
323         mstats.alloc += c->local_alloc;
324         c->local_alloc= 0;
325         mstats.total_alloc += c->local_total_alloc;
326         c->local_total_alloc= 0;
327 }
328
329 extern uintptr runtime_sizeof_C_MStats
330   __asm__ (GOSYM_PREFIX "runtime.Sizeof_C_MStats");
331
332 #define MaxArena32 (2U<<30)
333
334 void
335 runtime_mallocinit(void)
336 {
337         byte *p;
338         uintptr arena_size, bitmap_size;
339         extern byte _end[];
340         byte *want;
341         uintptr limit;
342
343         runtime_sizeof_C_MStats = sizeof(MStats);
344
345         p = nil;
346         arena_size = 0;
347         bitmap_size = 0;
348         
349         // for 64-bit build
350         USED(p);
351         USED(arena_size);
352         USED(bitmap_size);
353
354         if((runtime_mheap = runtime_SysAlloc(sizeof(*runtime_mheap))) == nil)
355                 runtime_throw("runtime: cannot allocate heap metadata");
356
357         runtime_InitSizes();
358
359         // limit = runtime_memlimit();
360         // See https://code.google.com/p/go/issues/detail?id=5049
361         // TODO(rsc): Fix after 1.1.
362         limit = 0;
363
364         // Set up the allocation arena, a contiguous area of memory where
365         // allocated data will be found.  The arena begins with a bitmap large
366         // enough to hold 4 bits per allocated word.
367         if(sizeof(void*) == 8 && (limit == 0 || limit > (1<<30))) {
368                 // On a 64-bit machine, allocate from a single contiguous reservation.
369                 // 128 GB (MaxMem) should be big enough for now.
370                 //
371                 // The code will work with the reservation at any address, but ask
372                 // SysReserve to use 0x000000c000000000 if possible.
373                 // Allocating a 128 GB region takes away 37 bits, and the amd64
374                 // doesn't let us choose the top 17 bits, so that leaves the 11 bits
375                 // in the middle of 0x00c0 for us to choose.  Choosing 0x00c0 means
376                 // that the valid memory addresses will begin 0x00c0, 0x00c1, ..., 0x0x00df.
377                 // In little-endian, that's c0 00, c1 00, ..., df 00. None of those are valid
378                 // UTF-8 sequences, and they are otherwise as far away from 
379                 // ff (likely a common byte) as possible. An earlier attempt to use 0x11f8 
380                 // caused out of memory errors on OS X during thread allocations.
381                 // These choices are both for debuggability and to reduce the
382                 // odds of the conservative garbage collector not collecting memory
383                 // because some non-pointer block of memory had a bit pattern
384                 // that matched a memory address.
385                 //
386                 // Actually we reserve 136 GB (because the bitmap ends up being 8 GB)
387                 // but it hardly matters: e0 00 is not valid UTF-8 either.
388                 //
389                 // If this fails we fall back to the 32 bit memory mechanism
390                 arena_size = MaxMem;
391                 bitmap_size = arena_size / (sizeof(void*)*8/4);
392                 p = runtime_SysReserve((void*)(0x00c0ULL<<32), bitmap_size + arena_size);
393         }
394         if (p == nil) {
395                 // On a 32-bit machine, we can't typically get away
396                 // with a giant virtual address space reservation.
397                 // Instead we map the memory information bitmap
398                 // immediately after the data segment, large enough
399                 // to handle another 2GB of mappings (256 MB),
400                 // along with a reservation for another 512 MB of memory.
401                 // When that gets used up, we'll start asking the kernel
402                 // for any memory anywhere and hope it's in the 2GB
403                 // following the bitmap (presumably the executable begins
404                 // near the bottom of memory, so we'll have to use up
405                 // most of memory before the kernel resorts to giving out
406                 // memory before the beginning of the text segment).
407                 //
408                 // Alternatively we could reserve 512 MB bitmap, enough
409                 // for 4GB of mappings, and then accept any memory the
410                 // kernel threw at us, but normally that's a waste of 512 MB
411                 // of address space, which is probably too much in a 32-bit world.
412                 bitmap_size = MaxArena32 / (sizeof(void*)*8/4);
413                 arena_size = 512<<20;
414                 if(limit > 0 && arena_size+bitmap_size > limit) {
415                         bitmap_size = (limit / 9) & ~((1<<PageShift) - 1);
416                         arena_size = bitmap_size * 8;
417                 }
418                 
419                 // SysReserve treats the address we ask for, end, as a hint,
420                 // not as an absolute requirement.  If we ask for the end
421                 // of the data segment but the operating system requires
422                 // a little more space before we can start allocating, it will
423                 // give out a slightly higher pointer.  Except QEMU, which
424                 // is buggy, as usual: it won't adjust the pointer upward.
425                 // So adjust it upward a little bit ourselves: 1/4 MB to get
426                 // away from the running binary image and then round up
427                 // to a MB boundary.
428                 want = (byte*)(((uintptr)_end + (1<<18) + (1<<20) - 1)&~((1<<20)-1));
429                 if(0xffffffff - (uintptr)want <= bitmap_size + arena_size)
430                   want = 0;
431                 p = runtime_SysReserve(want, bitmap_size + arena_size);
432                 if(p == nil)
433                         runtime_throw("runtime: cannot reserve arena virtual address space");
434                 if((uintptr)p & (((uintptr)1<<PageShift)-1))
435                         runtime_printf("runtime: SysReserve returned unaligned address %p; asked for %p", p, bitmap_size+arena_size);
436         }
437         if((uintptr)p & (((uintptr)1<<PageShift)-1))
438                 runtime_throw("runtime: SysReserve returned unaligned address");
439
440         runtime_mheap->bitmap = p;
441         runtime_mheap->arena_start = p + bitmap_size;
442         runtime_mheap->arena_used = runtime_mheap->arena_start;
443         runtime_mheap->arena_end = runtime_mheap->arena_start + arena_size;
444
445         // Initialize the rest of the allocator.        
446         runtime_MHeap_Init(runtime_mheap, runtime_SysAlloc);
447         runtime_m()->mcache = runtime_allocmcache();
448
449         // See if it works.
450         runtime_free(runtime_malloc(1));
451 }
452
453 void*
454 runtime_MHeap_SysAlloc(MHeap *h, uintptr n)
455 {
456         byte *p;
457
458
459         if(n > (uintptr)(h->arena_end - h->arena_used)) {
460                 // We are in 32-bit mode, maybe we didn't use all possible address space yet.
461                 // Reserve some more space.
462                 byte *new_end;
463                 uintptr needed;
464
465                 needed = (uintptr)h->arena_used + n - (uintptr)h->arena_end;
466                 // Round wanted arena size to a multiple of 256MB.
467                 needed = (needed + (256<<20) - 1) & ~((256<<20)-1);
468                 new_end = h->arena_end + needed;
469                 if(new_end <= h->arena_start + MaxArena32) {
470                         p = runtime_SysReserve(h->arena_end, new_end - h->arena_end);
471                         if(p == h->arena_end)
472                                 h->arena_end = new_end;
473                 }
474         }
475         if(n <= (uintptr)(h->arena_end - h->arena_used)) {
476                 // Keep taking from our reservation.
477                 p = h->arena_used;
478                 runtime_SysMap(p, n);
479                 h->arena_used += n;
480                 runtime_MHeap_MapBits(h);
481                 if(raceenabled)
482                         runtime_racemapshadow(p, n);
483                 return p;
484         }
485         
486         // If using 64-bit, our reservation is all we have.
487         if(sizeof(void*) == 8 && (uintptr)h->bitmap >= 0xffffffffU)
488                 return nil;
489
490         // On 32-bit, once the reservation is gone we can
491         // try to get memory at a location chosen by the OS
492         // and hope that it is in the range we allocated bitmap for.
493         p = runtime_SysAlloc(n);
494         if(p == nil)
495                 return nil;
496
497         if(p < h->arena_start || (uintptr)(p+n - h->arena_start) >= MaxArena32) {
498                 runtime_printf("runtime: memory allocated by OS (%p) not in usable range [%p,%p)\n",
499                         p, h->arena_start, h->arena_start+MaxArena32);
500                 runtime_SysFree(p, n);
501                 return nil;
502         }
503
504         if(p+n > h->arena_used) {
505                 h->arena_used = p+n;
506                 if(h->arena_used > h->arena_end)
507                         h->arena_end = h->arena_used;
508                 runtime_MHeap_MapBits(h);
509                 if(raceenabled)
510                         runtime_racemapshadow(p, n);
511         }
512         
513         return p;
514 }
515
516 static Lock settype_lock;
517
518 void
519 runtime_settype_flush(M *mp, bool sysalloc)
520 {
521         uintptr *buf, *endbuf;
522         uintptr size, ofs, j, t;
523         uintptr ntypes, nbytes2, nbytes3;
524         uintptr *data2;
525         byte *data3;
526         bool sysalloc3;
527         void *v;
528         uintptr typ, p;
529         MSpan *s;
530
531         buf = mp->settype_buf;
532         endbuf = buf + mp->settype_bufsize;
533
534         runtime_lock(&settype_lock);
535         while(buf < endbuf) {
536                 v = (void*)*buf;
537                 *buf = 0;
538                 buf++;
539                 typ = *buf;
540                 buf++;
541
542                 // (Manually inlined copy of runtime_MHeap_Lookup)
543                 p = (uintptr)v>>PageShift;
544                 if(sizeof(void*) == 8)
545                         p -= (uintptr)runtime_mheap->arena_start >> PageShift;
546                 s = runtime_mheap->map[p];
547
548                 if(s->sizeclass == 0) {
549                         s->types.compression = MTypes_Single;
550                         s->types.data = typ;
551                         continue;
552                 }
553
554                 size = s->elemsize;
555                 ofs = ((uintptr)v - (s->start<<PageShift)) / size;
556
557                 switch(s->types.compression) {
558                 case MTypes_Empty:
559                         ntypes = (s->npages << PageShift) / size;
560                         nbytes3 = 8*sizeof(uintptr) + 1*ntypes;
561
562                         if(!sysalloc) {
563                                 data3 = runtime_mallocgc(nbytes3, FlagNoProfiling|FlagNoPointers, 0, 1);
564                         } else {
565                                 data3 = runtime_SysAlloc(nbytes3);
566                                 if(data3 == nil)
567                                         runtime_throw("runtime: cannot allocate memory");
568                                 if(0) runtime_printf("settype(0->3): SysAlloc(%x) --> %p\n", (uint32)nbytes3, data3);
569                         }
570
571                         s->types.compression = MTypes_Bytes;
572                         s->types.sysalloc = sysalloc;
573                         s->types.data = (uintptr)data3;
574
575                         ((uintptr*)data3)[1] = typ;
576                         data3[8*sizeof(uintptr) + ofs] = 1;
577                         break;
578
579                 case MTypes_Words:
580                         ((uintptr*)s->types.data)[ofs] = typ;
581                         break;
582
583                 case MTypes_Bytes:
584                         data3 = (byte*)s->types.data;
585                         for(j=1; j<8; j++) {
586                                 if(((uintptr*)data3)[j] == typ) {
587                                         break;
588                                 }
589                                 if(((uintptr*)data3)[j] == 0) {
590                                         ((uintptr*)data3)[j] = typ;
591                                         break;
592                                 }
593                         }
594                         if(j < 8) {
595                                 data3[8*sizeof(uintptr) + ofs] = j;
596                         } else {
597                                 ntypes = (s->npages << PageShift) / size;
598                                 nbytes2 = ntypes * sizeof(uintptr);
599
600                                 if(!sysalloc) {
601                                         data2 = runtime_mallocgc(nbytes2, FlagNoProfiling|FlagNoPointers, 0, 1);
602                                 } else {
603                                         data2 = runtime_SysAlloc(nbytes2);
604                                         if(data2 == nil)
605                                                 runtime_throw("runtime: cannot allocate memory");
606                                         if(0) runtime_printf("settype.(3->2): SysAlloc(%x) --> %p\n", (uint32)nbytes2, data2);
607                                 }
608
609                                 sysalloc3 = s->types.sysalloc;
610
611                                 s->types.compression = MTypes_Words;
612                                 s->types.sysalloc = sysalloc;
613                                 s->types.data = (uintptr)data2;
614
615                                 // Move the contents of data3 to data2. Then deallocate data3.
616                                 for(j=0; j<ntypes; j++) {
617                                         t = data3[8*sizeof(uintptr) + j];
618                                         t = ((uintptr*)data3)[t];
619                                         data2[j] = t;
620                                 }
621                                 if(sysalloc3) {
622                                         nbytes3 = 8*sizeof(uintptr) + 1*ntypes;
623                                         if(0) runtime_printf("settype.(3->2): SysFree(%p,%x)\n", data3, (uint32)nbytes3);
624                                         runtime_SysFree(data3, nbytes3);
625                                 }
626
627                                 data2[ofs] = typ;
628                         }
629                         break;
630                 }
631         }
632         runtime_unlock(&settype_lock);
633
634         mp->settype_bufsize = 0;
635 }
636
637 // It is forbidden to use this function if it is possible that
638 // explicit deallocation via calling runtime_free(v) may happen.
639 void
640 runtime_settype(void *v, uintptr t)
641 {
642         M *mp;
643         uintptr *buf;
644         uintptr i;
645         MSpan *s;
646
647         if(t == 0)
648                 runtime_throw("settype: zero type");
649
650         mp = runtime_m();
651         buf = mp->settype_buf;
652         i = mp->settype_bufsize;
653         buf[i+0] = (uintptr)v;
654         buf[i+1] = t;
655         i += 2;
656         mp->settype_bufsize = i;
657
658         if(i == nelem(mp->settype_buf)) {
659                 runtime_settype_flush(mp, false);
660         }
661
662         if(DebugTypeAtBlockEnd) {
663                 s = runtime_MHeap_Lookup(runtime_mheap, v);
664                 *(uintptr*)((uintptr)v+s->elemsize-sizeof(uintptr)) = t;
665         }
666 }
667
668 void
669 runtime_settype_sysfree(MSpan *s)
670 {
671         uintptr ntypes, nbytes;
672
673         if(!s->types.sysalloc)
674                 return;
675
676         nbytes = (uintptr)-1;
677
678         switch (s->types.compression) {
679         case MTypes_Words:
680                 ntypes = (s->npages << PageShift) / s->elemsize;
681                 nbytes = ntypes * sizeof(uintptr);
682                 break;
683         case MTypes_Bytes:
684                 ntypes = (s->npages << PageShift) / s->elemsize;
685                 nbytes = 8*sizeof(uintptr) + 1*ntypes;
686                 break;
687         }
688
689         if(nbytes != (uintptr)-1) {
690                 if(0) runtime_printf("settype: SysFree(%p,%x)\n", (void*)s->types.data, (uint32)nbytes);
691                 runtime_SysFree((void*)s->types.data, nbytes);
692         }
693 }
694
695 uintptr
696 runtime_gettype(void *v)
697 {
698         MSpan *s;
699         uintptr t, ofs;
700         byte *data;
701
702         s = runtime_MHeap_LookupMaybe(runtime_mheap, v);
703         if(s != nil) {
704                 t = 0;
705                 switch(s->types.compression) {
706                 case MTypes_Empty:
707                         break;
708                 case MTypes_Single:
709                         t = s->types.data;
710                         break;
711                 case MTypes_Words:
712                         ofs = (uintptr)v - (s->start<<PageShift);
713                         t = ((uintptr*)s->types.data)[ofs/s->elemsize];
714                         break;
715                 case MTypes_Bytes:
716                         ofs = (uintptr)v - (s->start<<PageShift);
717                         data = (byte*)s->types.data;
718                         t = data[8*sizeof(uintptr) + ofs/s->elemsize];
719                         t = ((uintptr*)data)[t];
720                         break;
721                 default:
722                         runtime_throw("runtime_gettype: invalid compression kind");
723                 }
724                 if(0) {
725                         runtime_lock(&settype_lock);
726                         runtime_printf("%p -> %d,%X\n", v, (int32)s->types.compression, (int64)t);
727                         runtime_unlock(&settype_lock);
728                 }
729                 return t;
730         }
731         return 0;
732 }
733
734 // Runtime stubs.
735
736 void*
737 runtime_mal(uintptr n)
738 {
739         return runtime_mallocgc(n, 0, 1, 1);
740 }
741
742 void *
743 runtime_new(const Type *typ)
744 {
745         void *ret;
746         uint32 flag;
747
748         if(raceenabled)
749                 runtime_m()->racepc = runtime_getcallerpc(&typ);
750
751         if(typ->__size == 0) {
752                 // All 0-length allocations use this pointer.
753                 // The language does not require the allocations to
754                 // have distinct values.
755                 ret = (uint8*)&runtime_zerobase;
756         } else {
757                 flag = typ->__code&GO_NO_POINTERS ? FlagNoPointers : 0;
758                 ret = runtime_mallocgc(typ->__size, flag, 1, 1);
759
760                 if(UseSpanType && !flag) {
761                         if(false)
762                                 runtime_printf("new %S: %p\n", *typ->__reflection, ret);
763                         runtime_settype(ret, (uintptr)typ | TypeInfo_SingleObject);
764                 }
765         }
766
767         return ret;
768 }
769
770 static void*
771 cnew(const Type *typ, intgo n, int32 objtyp)
772 {
773         uint32 flag;
774         void *ret;
775
776         if((objtyp&(PtrSize-1)) != objtyp)
777                 runtime_throw("runtime: invalid objtyp");
778         if(n < 0 || (typ->__size > 0 && (uintptr)n > (MaxMem/typ->__size)))
779                 runtime_panicstring("runtime: allocation size out of range");
780         if(typ->__size == 0 || n == 0) {
781                 // All 0-length allocations use this pointer.
782                 // The language does not require the allocations to
783                 // have distinct values.
784                 return &runtime_zerobase;
785         }
786         flag = typ->__code&GO_NO_POINTERS ? FlagNoPointers : 0;
787         ret = runtime_mallocgc(typ->__size*n, flag, 1, 1);
788         if(UseSpanType && !flag) {
789                 if(false)
790                         runtime_printf("cnew [%D]%S: %p\n", (int64)n, *typ->__reflection, ret);
791                 runtime_settype(ret, (uintptr)typ | TypeInfo_SingleObject);
792         }
793         return ret;
794 }
795
796 // same as runtime_new, but callable from C
797 void*
798 runtime_cnew(const Type *typ)
799 {
800         return cnew(typ, 1, TypeInfo_SingleObject);
801 }
802
803 void*
804 runtime_cnewarray(const Type *typ, intgo n)
805 {
806         return cnew(typ, n, TypeInfo_Array);
807 }
808
809 func GC() {
810         runtime_gc(1);
811 }
812
813 func SetFinalizer(obj Eface, finalizer Eface) {
814         byte *base;
815         uintptr size;
816         const FuncType *ft;
817
818         if(obj.__type_descriptor == nil) {
819                 runtime_printf("runtime.SetFinalizer: first argument is nil interface\n");
820                 goto throw;
821         }
822         if(obj.__type_descriptor->__code != GO_PTR) {
823                 runtime_printf("runtime.SetFinalizer: first argument is %S, not pointer\n", *obj.__type_descriptor->__reflection);
824                 goto throw;
825         }
826         if(!runtime_mlookup(obj.__object, &base, &size, nil) || obj.__object != base) {
827                 runtime_printf("runtime.SetFinalizer: pointer not at beginning of allocated block\n");
828                 goto throw;
829         }
830         ft = nil;
831         if(finalizer.__type_descriptor != nil) {
832                 if(finalizer.__type_descriptor->__code != GO_FUNC)
833                         goto badfunc;
834                 ft = (const FuncType*)finalizer.__type_descriptor;
835                 if(ft->__dotdotdot || ft->__in.__count != 1 || !__go_type_descriptors_equal(*(Type**)ft->__in.__values, obj.__type_descriptor))
836                         goto badfunc;
837         }
838
839         if(!runtime_addfinalizer(obj.__object, finalizer.__type_descriptor != nil ? *(void**)finalizer.__object : nil, ft)) {
840                 runtime_printf("runtime.SetFinalizer: finalizer already set\n");
841                 goto throw;
842         }
843         return;
844
845 badfunc:
846         runtime_printf("runtime.SetFinalizer: second argument is %S, not func(%S)\n", *finalizer.__type_descriptor->__reflection, *obj.__type_descriptor->__reflection);
847 throw:
848         runtime_throw("runtime.SetFinalizer");
849 }