1 // Copyright 2014 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 // Implementation of runtime/debug.WriteHeapDump. Writes all
6 // objects in the heap plus additional info (roots, threads,
7 // finalizers, etc.) to a file.
9 // The format of the dumped file is described at
10 // https://golang.org/s/go15heapdump.
20 //go:linkname runtime_debug_WriteHeapDump runtime/debug.WriteHeapDump
21 func runtime_debug_WriteHeapDump(fd uintptr) {
22 stopTheWorld(stwWriteHeapDump)
24 // Keep m on this G's stack instead of the system stack.
25 // Both readmemstats_m and writeheapdump_m have pretty large
26 // peak stack depths and we risk blowing the system stack.
27 // This is safe because the world is stopped, so we don't
28 // need to worry about anyone shrinking and therefore moving
32 // Call readmemstats_m here instead of deeper in
33 // writeheapdump_m because we might blow the system stack
36 writeheapdump_m(fd, &m)
58 tagQueuedFinalizer = 11
67 var dumpfd uintptr // fd to write the dump to.
70 // buffer of pending write data
78 func dwrite(data unsafe.Pointer, len uintptr) {
82 if nbuf+len <= bufSize {
83 copy(buf[nbuf:], (*[bufSize]byte)(data)[:len])
88 write(dumpfd, unsafe.Pointer(&buf), int32(nbuf))
90 write(dumpfd, data, int32(len))
93 copy(buf[:], (*[bufSize]byte)(data)[:len])
98 func dwritebyte(b byte) {
99 dwrite(unsafe.Pointer(&b), 1)
103 write(dumpfd, unsafe.Pointer(&buf), int32(nbuf))
107 // Cache of types that have been serialized already.
108 // We use a type's hash field to pick a bucket.
109 // Inside a bucket, we keep a list of types that
110 // have been serialized so far, most recently used first.
111 // Note: when a bucket overflows we may end up
112 // serializing a type more than once. That's ok.
114 typeCacheBuckets = 256
118 type typeCacheBucket struct {
119 t [typeCacheAssoc]*_type
122 var typecache [typeCacheBuckets]typeCacheBucket
124 // dump a uint64 in a varint format parseable by encoding/binary.
125 func dumpint(v uint64) {
129 buf[n] = byte(v | 0x80)
135 dwrite(unsafe.Pointer(&buf), uintptr(n))
138 func dumpbool(b bool) {
146 // dump varint uint64 length followed by memory contents.
147 func dumpmemrange(data unsafe.Pointer, len uintptr) {
152 func dumpslice(b []byte) {
153 dumpint(uint64(len(b)))
155 dwrite(unsafe.Pointer(&b[0]), uintptr(len(b)))
159 func dumpstr(s string) {
160 dumpmemrange(unsafe.Pointer(unsafe.StringData(s)), uintptr(len(s)))
163 // dump information for a type.
164 func dumptype(t *_type) {
169 // If we've definitely serialized the type before,
170 // no need to do it again.
171 b := &typecache[t.Hash&(typeCacheBuckets-1)]
175 for i := 1; i < typeCacheAssoc; i++ {
178 for j := i; j > 0; j-- {
186 // Might not have been dumped yet. Dump it and
187 // remember we did so.
188 for j := typeCacheAssoc - 1; j > 0; j-- {
195 dumpint(uint64(uintptr(unsafe.Pointer(t))))
196 dumpint(uint64(t.Size_))
198 if x := t.Uncommon(); x == nil || rt.nameOff(x.PkgPath).Name() == "" {
201 pkgpath := rt.nameOff(x.PkgPath).Name()
203 dumpint(uint64(uintptr(len(pkgpath)) + 1 + uintptr(len(name))))
204 dwrite(unsafe.Pointer(unsafe.StringData(pkgpath)), uintptr(len(pkgpath)))
206 dwrite(unsafe.Pointer(unsafe.StringData(name)), uintptr(len(name)))
208 dumpbool(t.Kind_&kindDirectIface == 0 || t.PtrBytes != 0)
212 func dumpobj(obj unsafe.Pointer, size uintptr, bv bitvector) {
214 dumpint(uint64(uintptr(obj)))
215 dumpmemrange(obj, size)
219 func dumpotherroot(description string, to unsafe.Pointer) {
220 dumpint(tagOtherRoot)
222 dumpint(uint64(uintptr(to)))
225 func dumpfinalizer(obj unsafe.Pointer, fn *funcval, fint *_type, ot *ptrtype) {
226 dumpint(tagFinalizer)
227 dumpint(uint64(uintptr(obj)))
228 dumpint(uint64(uintptr(unsafe.Pointer(fn))))
229 dumpint(uint64(uintptr(unsafe.Pointer(fn.fn))))
230 dumpint(uint64(uintptr(unsafe.Pointer(fint))))
231 dumpint(uint64(uintptr(unsafe.Pointer(ot))))
234 type childInfo struct {
235 // Information passed up from the callee frame about
236 // the layout of the outargs region.
237 argoff uintptr // where the arguments start in the frame
238 arglen uintptr // size of args region
239 args bitvector // if args.n >= 0, pointer map of args region
240 sp *uint8 // callee sp
241 depth uintptr // depth in call stack (0 == most recent)
244 // dump kinds & offsets of interesting fields in bv.
245 func dumpbv(cbv *bitvector, offset uintptr) {
246 for i := uintptr(0); i < uintptr(cbv.n); i++ {
247 if cbv.ptrbit(i) == 1 {
248 dumpint(fieldKindPtr)
249 dumpint(uint64(offset + i*goarch.PtrSize))
254 func dumpframe(s *stkframe, child *childInfo) {
257 // Figure out what we can about our stack map
259 pcdata := int32(-1) // Use the entry map at function entry
262 pcdata = pcdatavalue(f, abi.PCDATA_StackMapIndex, pc)
265 // We do not have a valid pcdata value but there might be a
266 // stackmap for this function. It is likely that we are looking
267 // at the function prologue, assume so and hope for the best.
270 stkmap := (*stackmap)(funcdata(f, abi.FUNCDATA_LocalsPointerMaps))
273 if stkmap != nil && stkmap.n > 0 {
274 bv = stackmapdata(stkmap, pcdata)
279 // Dump main body of stack frame.
280 dumpint(tagStackFrame)
281 dumpint(uint64(s.sp)) // lowest address in frame
282 dumpint(uint64(child.depth)) // # of frames deep on the stack
283 dumpint(uint64(uintptr(unsafe.Pointer(child.sp)))) // sp of child, or 0 if bottom of stack
284 dumpmemrange(unsafe.Pointer(s.sp), s.fp-s.sp) // frame contents
285 dumpint(uint64(f.entry()))
286 dumpint(uint64(s.pc))
287 dumpint(uint64(s.continpc))
290 name = "unknown function"
294 // Dump fields in the outargs section
295 if child.args.n >= 0 {
296 dumpbv(&child.args, child.argoff)
298 // conservative - everything might be a pointer
299 for off := child.argoff; off < child.argoff+child.arglen; off += goarch.PtrSize {
300 dumpint(fieldKindPtr)
305 // Dump fields in the local vars section
307 // No locals information, dump everything.
308 for off := child.arglen; off < s.varp-s.sp; off += goarch.PtrSize {
309 dumpint(fieldKindPtr)
312 } else if stkmap.n < 0 {
313 // Locals size information, dump just the locals.
314 size := uintptr(-stkmap.n)
315 for off := s.varp - size - s.sp; off < s.varp-s.sp; off += goarch.PtrSize {
316 dumpint(fieldKindPtr)
319 } else if stkmap.n > 0 {
320 // Locals bitmap information, scan just the pointers in
322 dumpbv(&bv, s.varp-uintptr(bv.n)*goarch.PtrSize-s.sp)
324 dumpint(fieldKindEol)
326 // Record arg info for parent.
327 child.argoff = s.argp - s.fp
328 child.arglen = s.argBytes()
329 child.sp = (*uint8)(unsafe.Pointer(s.sp))
331 stkmap = (*stackmap)(funcdata(f, abi.FUNCDATA_ArgsPointerMaps))
333 child.args = stackmapdata(stkmap, pcdata)
340 func dumpgoroutine(gp *g) {
341 var sp, pc, lr uintptr
342 if gp.syscallsp != 0 {
352 dumpint(tagGoroutine)
353 dumpint(uint64(uintptr(unsafe.Pointer(gp))))
356 dumpint(uint64(gp.gopc))
357 dumpint(uint64(readgstatus(gp)))
358 dumpbool(isSystemGoroutine(gp, false))
359 dumpbool(false) // isbackground
360 dumpint(uint64(gp.waitsince))
361 dumpstr(gp.waitreason.String())
362 dumpint(uint64(uintptr(gp.sched.ctxt)))
363 dumpint(uint64(uintptr(unsafe.Pointer(gp.m))))
364 dumpint(uint64(uintptr(unsafe.Pointer(gp._defer))))
365 dumpint(uint64(uintptr(unsafe.Pointer(gp._panic))))
374 for u.initAt(pc, sp, lr, gp, 0); u.valid(); u.next() {
375 dumpframe(&u.frame, &child)
378 // dump defer & panic records
379 for d := gp._defer; d != nil; d = d.link {
381 dumpint(uint64(uintptr(unsafe.Pointer(d))))
382 dumpint(uint64(uintptr(unsafe.Pointer(gp))))
383 dumpint(uint64(d.sp))
384 dumpint(uint64(d.pc))
385 fn := *(**funcval)(unsafe.Pointer(&d.fn))
386 dumpint(uint64(uintptr(unsafe.Pointer(fn))))
388 // d.fn can be nil for open-coded defers
391 dumpint(uint64(uintptr(unsafe.Pointer(fn.fn))))
393 dumpint(uint64(uintptr(unsafe.Pointer(d.link))))
395 for p := gp._panic; p != nil; p = p.link {
397 dumpint(uint64(uintptr(unsafe.Pointer(p))))
398 dumpint(uint64(uintptr(unsafe.Pointer(gp))))
399 eface := efaceOf(&p.arg)
400 dumpint(uint64(uintptr(unsafe.Pointer(eface._type))))
401 dumpint(uint64(uintptr(eface.data)))
402 dumpint(0) // was p->defer, no longer recorded
403 dumpint(uint64(uintptr(unsafe.Pointer(p.link))))
410 // goroutines & stacks
411 forEachG(func(gp *g) {
412 status := readgstatus(gp) // The world is stopped so gp will not be in a scan state.
415 print("runtime: unexpected G.status ", hex(status), "\n")
416 throw("dumpgs in STW - bad status")
427 func finq_callback(fn *funcval, obj unsafe.Pointer, nret uintptr, fint *_type, ot *ptrtype) {
428 dumpint(tagQueuedFinalizer)
429 dumpint(uint64(uintptr(obj)))
430 dumpint(uint64(uintptr(unsafe.Pointer(fn))))
431 dumpint(uint64(uintptr(unsafe.Pointer(fn.fn))))
432 dumpint(uint64(uintptr(unsafe.Pointer(fint))))
433 dumpint(uint64(uintptr(unsafe.Pointer(ot))))
437 // To protect mheap_.allspans.
440 // TODO(mwhudson): dump datamask etc from all objects
443 dumpint(uint64(firstmoduledata.data))
444 dumpmemrange(unsafe.Pointer(firstmoduledata.data), firstmoduledata.edata-firstmoduledata.data)
445 dumpfields(firstmoduledata.gcdatamask)
449 dumpint(uint64(firstmoduledata.bss))
450 dumpmemrange(unsafe.Pointer(firstmoduledata.bss), firstmoduledata.ebss-firstmoduledata.bss)
451 dumpfields(firstmoduledata.gcbssmask)
454 for _, s := range mheap_.allspans {
455 if s.state.get() == mSpanInUse {
457 for sp := s.specials; sp != nil; sp = sp.next {
458 if sp.kind != _KindSpecialFinalizer {
461 spf := (*specialfinalizer)(unsafe.Pointer(sp))
462 p := unsafe.Pointer(s.base() + uintptr(spf.special.offset))
463 dumpfinalizer(p, spf.fn, spf.fint, spf.ot)
469 iterate_finq(finq_callback)
472 // Bit vector of free marks.
473 // Needs to be as big as the largest number of objects per span.
474 var freemark [_PageSize / 8]bool
477 // To protect mheap_.allspans.
480 for _, s := range mheap_.allspans {
481 if s.state.get() != mSpanInUse {
486 n := (s.npages << _PageShift) / size
487 if n > uintptr(len(freemark)) {
488 throw("freemark array doesn't have enough entries")
491 for freeIndex := uint16(0); freeIndex < s.nelems; freeIndex++ {
492 if s.isFree(uintptr(freeIndex)) {
493 freemark[freeIndex] = true
497 for j := uintptr(0); j < n; j, p = j+1, p+size {
502 dumpobj(unsafe.Pointer(p), size, makeheapobjbv(p, size))
510 if *(*byte)(unsafe.Pointer(&x)) == 1 {
511 dumpbool(false) // little-endian ptrs
513 dumpbool(true) // big-endian ptrs
515 dumpint(goarch.PtrSize)
516 var arenaStart, arenaEnd uintptr
517 for i1 := range mheap_.arenas {
518 if mheap_.arenas[i1] == nil {
521 for i, ha := range mheap_.arenas[i1] {
525 base := arenaBase(arenaIdx(i1)<<arenaL1Shift | arenaIdx(i))
526 if arenaStart == 0 || base < arenaStart {
529 if base+heapArenaBytes > arenaEnd {
530 arenaEnd = base + heapArenaBytes
534 dumpint(uint64(arenaStart))
535 dumpint(uint64(arenaEnd))
536 dumpstr(goarch.GOARCH)
537 dumpstr(buildVersion)
538 dumpint(uint64(ncpu))
541 func itab_callback(tab *itab) {
545 dumpint(uint64(uintptr(unsafe.Pointer(tab))))
546 dumpint(uint64(uintptr(unsafe.Pointer(t))))
550 iterate_itabs(itab_callback)
554 for mp := allm; mp != nil; mp = mp.alllink {
556 dumpint(uint64(uintptr(unsafe.Pointer(mp))))
557 dumpint(uint64(mp.id))
563 func dumpmemstats(m *MemStats) {
566 // These ints should be identical to the exported
567 // MemStats structure and should be ordered the same
571 dumpint(m.TotalAlloc)
580 dumpint(m.HeapReleased)
581 dumpint(m.HeapObjects)
582 dumpint(m.StackInuse)
584 dumpint(m.MSpanInuse)
586 dumpint(m.MCacheInuse)
588 dumpint(m.BuckHashSys)
593 dumpint(m.PauseTotalNs)
594 for i := 0; i < 256; i++ {
595 dumpint(m.PauseNs[i])
597 dumpint(uint64(m.NumGC))
600 func dumpmemprof_callback(b *bucket, nstk uintptr, pstk *uintptr, size, allocs, frees uintptr) {
601 stk := (*[100000]uintptr)(unsafe.Pointer(pstk))
603 dumpint(uint64(uintptr(unsafe.Pointer(b))))
604 dumpint(uint64(size))
605 dumpint(uint64(nstk))
606 for i := uintptr(0); i < nstk; i++ {
620 buf[n] = "0123456789abcdef"[pc&15]
635 if i > 0 && pc > f.entry() {
638 file, line := funcline(f, pc)
640 dumpint(uint64(line))
643 dumpint(uint64(allocs))
644 dumpint(uint64(frees))
648 // To protect mheap_.allspans.
651 iterate_memprof(dumpmemprof_callback)
652 for _, s := range mheap_.allspans {
653 if s.state.get() != mSpanInUse {
656 for sp := s.specials; sp != nil; sp = sp.next {
657 if sp.kind != _KindSpecialProfile {
660 spp := (*specialprofile)(unsafe.Pointer(sp))
661 p := s.base() + uintptr(spp.special.offset)
662 dumpint(tagAllocSample)
664 dumpint(uint64(uintptr(unsafe.Pointer(spp.b))))
669 var dumphdr = []byte("go1.7 heap dump\n")
671 func mdump(m *MemStats) {
674 // make sure we're done sweeping
675 for _, s := range mheap_.allspans {
676 if s.state.get() == mSpanInUse {
680 memclrNoHeapPointers(unsafe.Pointer(&typecache), unsafe.Sizeof(typecache))
681 dwrite(unsafe.Pointer(&dumphdr[0]), uintptr(len(dumphdr)))
694 func writeheapdump_m(fd uintptr, m *MemStats) {
698 casGToWaiting(gp.m.curg, _Grunning, waitReasonDumpingHeap)
703 // Call dump routine.
709 sysFree(unsafe.Pointer(&tmpbuf[0]), uintptr(len(tmpbuf)), &memstats.other_sys)
713 casgstatus(gp.m.curg, _Gwaiting, _Grunning)
716 // dumpint() the kind & offset of each field in an object.
717 func dumpfields(bv bitvector) {
719 dumpint(fieldKindEol)
722 func makeheapobjbv(p uintptr, size uintptr) bitvector {
723 // Extend the temp buffer if necessary.
724 nptr := size / goarch.PtrSize
725 if uintptr(len(tmpbuf)) < nptr/8+1 {
727 sysFree(unsafe.Pointer(&tmpbuf[0]), uintptr(len(tmpbuf)), &memstats.other_sys)
730 p := sysAlloc(n, &memstats.other_sys)
732 throw("heapdump: out of memory")
734 tmpbuf = (*[1 << 30]byte)(p)[:n]
736 // Convert heap bitmap to pointer bitmap.
737 for i := uintptr(0); i < nptr/8+1; i++ {
741 hbits := heapBitsForAddr(p, size)
744 hbits, addr = hbits.next()
748 i := (addr - p) / goarch.PtrSize
749 tmpbuf[i/8] |= 1 << (i % 8)
751 return bitvector{int32(nptr), &tmpbuf[0]}