]> Cypherpunks.ru repositories - gostls13.git/blob - src/runtime/mprof.go
runtime: snapshot heap profile during mark termination
[gostls13.git] / src / runtime / mprof.go
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 // Malloc profiling.
6 // Patterned after tcmalloc's algorithms; shorter code.
7
8 package runtime
9
10 import (
11         "runtime/internal/atomic"
12         "unsafe"
13 )
14
15 // NOTE(rsc): Everything here could use cas if contention became an issue.
16 var proflock mutex
17
18 // All memory allocations are local and do not escape outside of the profiler.
19 // The profiler is forbidden from referring to garbage-collected memory.
20
21 const (
22         // profile types
23         memProfile bucketType = 1 + iota
24         blockProfile
25         mutexProfile
26
27         // size of bucket hash table
28         buckHashSize = 179999
29
30         // max depth of stack to record in bucket
31         maxStack = 32
32 )
33
34 type bucketType int
35
36 // A bucket holds per-call-stack profiling information.
37 // The representation is a bit sleazy, inherited from C.
38 // This struct defines the bucket header. It is followed in
39 // memory by the stack words and then the actual record
40 // data, either a memRecord or a blockRecord.
41 //
42 // Per-call-stack profiling information.
43 // Lookup by hashing call stack into a linked-list hash table.
44 //
45 // No heap pointers.
46 //
47 //go:notinheap
48 type bucket struct {
49         next    *bucket
50         allnext *bucket
51         typ     bucketType // memBucket or blockBucket (includes mutexProfile)
52         hash    uintptr
53         size    uintptr
54         nstk    uintptr
55 }
56
57 // A memRecord is the bucket data for a bucket of type memProfile,
58 // part of the memory profile.
59 type memRecord struct {
60         // The following complex 3-stage scheme of stats accumulation
61         // is required to obtain a consistent picture of mallocs and frees
62         // for some point in time.
63         // The problem is that mallocs come in real time, while frees
64         // come only after a GC during concurrent sweeping. So if we would
65         // naively count them, we would get a skew toward mallocs.
66         //
67         // Hence, we delay information to get consistent snapshots as
68         // of mark termination. Allocations count toward the next mark
69         // termination's snapshot, while sweep frees count toward the
70         // previous mark termination's snapshot:
71         //
72         //              MT          MT          MT          MT
73         //             .·|         .·|         .·|         .·|
74         //          .·˙  |      .·˙  |      .·˙  |      .·˙  |
75         //       .·˙     |   .·˙     |   .·˙     |   .·˙     |
76         //    .·˙        |.·˙        |.·˙        |.·˙        |
77         //
78         //       alloc → ▲ ← free
79         //               ┠┅┅┅┅┅┅┅┅┅┅┅P
80         //       C+2     →    C+1    →  C
81         //
82         //                   alloc → ▲ ← free
83         //                           ┠┅┅┅┅┅┅┅┅┅┅┅P
84         //                   C+2     →    C+1    →  C
85         //
86         // Since we can't publish a consistent snapshot until all of
87         // the sweep frees are accounted for, we wait until the next
88         // mark termination ("MT" above) to publish the previous mark
89         // termination's snapshot ("P" above). To do this, allocation
90         // and free events are accounted to *future* heap profile
91         // cycles ("C+n" above) and we only publish a cycle once all
92         // of the events from that cycle must be done. Specifically:
93         //
94         // Mallocs are accounted to cycle C+2.
95         // Explicit frees are accounted to cycle C+2.
96         // GC frees (done during sweeping) are accounted to cycle C+1.
97         //
98         // After mark termination, we increment the global heap
99         // profile cycle counter and accumulate the stats from cycle C
100         // into the active profile.
101
102         // active is the currently published profile. A profiling
103         // cycle can be accumulated into active once its complete.
104         active memRecordCycle
105
106         // future records the profile events we're counting for cycles
107         // that have not yet been published. This is ring buffer
108         // indexed by the global heap profile cycle C and stores
109         // cycles C, C+1, and C+2. Unlike active, these counts are
110         // only for a single cycle; they are not cumulative across
111         // cycles.
112         //
113         // We store cycle C here because there's a window between when
114         // C becomes the active cycle and when we've flushed it to
115         // active.
116         future [3]memRecordCycle
117 }
118
119 // memRecordCycle
120 type memRecordCycle struct {
121         allocs, frees           uintptr
122         alloc_bytes, free_bytes uintptr
123 }
124
125 // add accumulates b into a. It does not zero b.
126 func (a *memRecordCycle) add(b *memRecordCycle) {
127         a.allocs += b.allocs
128         a.frees += b.frees
129         a.alloc_bytes += b.alloc_bytes
130         a.free_bytes += b.free_bytes
131 }
132
133 // A blockRecord is the bucket data for a bucket of type blockProfile,
134 // which is used in blocking and mutex profiles.
135 type blockRecord struct {
136         count  int64
137         cycles int64
138 }
139
140 var (
141         mbuckets  *bucket // memory profile buckets
142         bbuckets  *bucket // blocking profile buckets
143         xbuckets  *bucket // mutex profile buckets
144         buckhash  *[179999]*bucket
145         bucketmem uintptr
146
147         mProf struct {
148                 // All fields in mProf are protected by proflock.
149
150                 // cycle is the global heap profile cycle. This wraps
151                 // at mProfCycleWrap.
152                 cycle uint32
153                 // flushed indicates that future[cycle] in all buckets
154                 // has been flushed to the active profile.
155                 flushed bool
156         }
157 )
158
159 const mProfCycleWrap = uint32(len(memRecord{}.future)) * (2 << 24)
160
161 // newBucket allocates a bucket with the given type and number of stack entries.
162 func newBucket(typ bucketType, nstk int) *bucket {
163         size := unsafe.Sizeof(bucket{}) + uintptr(nstk)*unsafe.Sizeof(uintptr(0))
164         switch typ {
165         default:
166                 throw("invalid profile bucket type")
167         case memProfile:
168                 size += unsafe.Sizeof(memRecord{})
169         case blockProfile, mutexProfile:
170                 size += unsafe.Sizeof(blockRecord{})
171         }
172
173         b := (*bucket)(persistentalloc(size, 0, &memstats.buckhash_sys))
174         bucketmem += size
175         b.typ = typ
176         b.nstk = uintptr(nstk)
177         return b
178 }
179
180 // stk returns the slice in b holding the stack.
181 func (b *bucket) stk() []uintptr {
182         stk := (*[maxStack]uintptr)(add(unsafe.Pointer(b), unsafe.Sizeof(*b)))
183         return stk[:b.nstk:b.nstk]
184 }
185
186 // mp returns the memRecord associated with the memProfile bucket b.
187 func (b *bucket) mp() *memRecord {
188         if b.typ != memProfile {
189                 throw("bad use of bucket.mp")
190         }
191         data := add(unsafe.Pointer(b), unsafe.Sizeof(*b)+b.nstk*unsafe.Sizeof(uintptr(0)))
192         return (*memRecord)(data)
193 }
194
195 // bp returns the blockRecord associated with the blockProfile bucket b.
196 func (b *bucket) bp() *blockRecord {
197         if b.typ != blockProfile && b.typ != mutexProfile {
198                 throw("bad use of bucket.bp")
199         }
200         data := add(unsafe.Pointer(b), unsafe.Sizeof(*b)+b.nstk*unsafe.Sizeof(uintptr(0)))
201         return (*blockRecord)(data)
202 }
203
204 // Return the bucket for stk[0:nstk], allocating new bucket if needed.
205 func stkbucket(typ bucketType, size uintptr, stk []uintptr, alloc bool) *bucket {
206         if buckhash == nil {
207                 buckhash = (*[buckHashSize]*bucket)(sysAlloc(unsafe.Sizeof(*buckhash), &memstats.buckhash_sys))
208                 if buckhash == nil {
209                         throw("runtime: cannot allocate memory")
210                 }
211         }
212
213         // Hash stack.
214         var h uintptr
215         for _, pc := range stk {
216                 h += pc
217                 h += h << 10
218                 h ^= h >> 6
219         }
220         // hash in size
221         h += size
222         h += h << 10
223         h ^= h >> 6
224         // finalize
225         h += h << 3
226         h ^= h >> 11
227
228         i := int(h % buckHashSize)
229         for b := buckhash[i]; b != nil; b = b.next {
230                 if b.typ == typ && b.hash == h && b.size == size && eqslice(b.stk(), stk) {
231                         return b
232                 }
233         }
234
235         if !alloc {
236                 return nil
237         }
238
239         // Create new bucket.
240         b := newBucket(typ, len(stk))
241         copy(b.stk(), stk)
242         b.hash = h
243         b.size = size
244         b.next = buckhash[i]
245         buckhash[i] = b
246         if typ == memProfile {
247                 b.allnext = mbuckets
248                 mbuckets = b
249         } else if typ == mutexProfile {
250                 b.allnext = xbuckets
251                 xbuckets = b
252         } else {
253                 b.allnext = bbuckets
254                 bbuckets = b
255         }
256         return b
257 }
258
259 func eqslice(x, y []uintptr) bool {
260         if len(x) != len(y) {
261                 return false
262         }
263         for i, xi := range x {
264                 if xi != y[i] {
265                         return false
266                 }
267         }
268         return true
269 }
270
271 // mProf_NextCycle publishes the next heap profile cycle and creates a
272 // fresh heap profile cycle. This operation is fast and can be done
273 // during STW. The caller must call mProf_Flush before calling
274 // mProf_NextCycle again.
275 //
276 // This is called by mark termination during STW so allocations and
277 // frees after the world is started again count towards a new heap
278 // profiling cycle.
279 func mProf_NextCycle() {
280         lock(&proflock)
281         // We explicitly wrap mProf.cycle rather than depending on
282         // uint wraparound because the memRecord.future ring does not
283         // itself wrap at a power of two.
284         mProf.cycle = (mProf.cycle + 1) % mProfCycleWrap
285         mProf.flushed = false
286         unlock(&proflock)
287 }
288
289 // mProf_Flush flushes the events from the current heap profiling
290 // cycle into the active profile. After this it is safe to start a new
291 // heap profiling cycle with mProf_NextCycle.
292 //
293 // This is called by GC after mark termination starts the world. In
294 // contrast with mProf_NextCycle, this is somewhat expensive, but safe
295 // to do concurrently.
296 func mProf_Flush() {
297         lock(&proflock)
298         if !mProf.flushed {
299                 mProf_FlushLocked()
300                 mProf.flushed = true
301         }
302         unlock(&proflock)
303 }
304
305 func mProf_FlushLocked() {
306         c := mProf.cycle
307         for b := mbuckets; b != nil; b = b.allnext {
308                 mp := b.mp()
309
310                 // Flush cycle C into the published profile and clear
311                 // it for reuse.
312                 mpc := &mp.future[c%uint32(len(mp.future))]
313                 mp.active.add(mpc)
314                 *mpc = memRecordCycle{}
315         }
316 }
317
318 // Called by malloc to record a profiled block.
319 func mProf_Malloc(p unsafe.Pointer, size uintptr) {
320         var stk [maxStack]uintptr
321         nstk := callers(4, stk[:])
322         lock(&proflock)
323         b := stkbucket(memProfile, size, stk[:nstk], true)
324         c := mProf.cycle
325         mp := b.mp()
326         mpc := &mp.future[(c+2)%uint32(len(mp.future))]
327         mpc.allocs++
328         mpc.alloc_bytes += size
329         unlock(&proflock)
330
331         // Setprofilebucket locks a bunch of other mutexes, so we call it outside of proflock.
332         // This reduces potential contention and chances of deadlocks.
333         // Since the object must be alive during call to mProf_Malloc,
334         // it's fine to do this non-atomically.
335         systemstack(func() {
336                 setprofilebucket(p, b)
337         })
338 }
339
340 // Called when freeing a profiled block.
341 func mProf_Free(b *bucket, size uintptr) {
342         lock(&proflock)
343         c := mProf.cycle
344         mp := b.mp()
345         mpc := &mp.future[(c+1)%uint32(len(mp.future))]
346         mpc.frees++
347         mpc.free_bytes += size
348         unlock(&proflock)
349 }
350
351 var blockprofilerate uint64 // in CPU ticks
352
353 // SetBlockProfileRate controls the fraction of goroutine blocking events
354 // that are reported in the blocking profile. The profiler aims to sample
355 // an average of one blocking event per rate nanoseconds spent blocked.
356 //
357 // To include every blocking event in the profile, pass rate = 1.
358 // To turn off profiling entirely, pass rate <= 0.
359 func SetBlockProfileRate(rate int) {
360         var r int64
361         if rate <= 0 {
362                 r = 0 // disable profiling
363         } else if rate == 1 {
364                 r = 1 // profile everything
365         } else {
366                 // convert ns to cycles, use float64 to prevent overflow during multiplication
367                 r = int64(float64(rate) * float64(tickspersecond()) / (1000 * 1000 * 1000))
368                 if r == 0 {
369                         r = 1
370                 }
371         }
372
373         atomic.Store64(&blockprofilerate, uint64(r))
374 }
375
376 func blockevent(cycles int64, skip int) {
377         if cycles <= 0 {
378                 cycles = 1
379         }
380         if blocksampled(cycles) {
381                 saveblockevent(cycles, skip+1, blockProfile)
382         }
383 }
384
385 func blocksampled(cycles int64) bool {
386         rate := int64(atomic.Load64(&blockprofilerate))
387         if rate <= 0 || (rate > cycles && int64(fastrand())%rate > cycles) {
388                 return false
389         }
390         return true
391 }
392
393 func saveblockevent(cycles int64, skip int, which bucketType) {
394         gp := getg()
395         var nstk int
396         var stk [maxStack]uintptr
397         if gp.m.curg == nil || gp.m.curg == gp {
398                 nstk = callers(skip, stk[:])
399         } else {
400                 nstk = gcallers(gp.m.curg, skip, stk[:])
401         }
402         lock(&proflock)
403         b := stkbucket(which, 0, stk[:nstk], true)
404         b.bp().count++
405         b.bp().cycles += cycles
406         unlock(&proflock)
407 }
408
409 var mutexprofilerate uint64 // fraction sampled
410
411 // SetMutexProfileFraction controls the fraction of mutex contention events
412 // that are reported in the mutex profile. On average 1/rate events are
413 // reported. The previous rate is returned.
414 //
415 // To turn off profiling entirely, pass rate 0.
416 // To just read the current rate, pass rate -1.
417 // (For n>1 the details of sampling may change.)
418 func SetMutexProfileFraction(rate int) int {
419         if rate < 0 {
420                 return int(mutexprofilerate)
421         }
422         old := mutexprofilerate
423         atomic.Store64(&mutexprofilerate, uint64(rate))
424         return int(old)
425 }
426
427 //go:linkname mutexevent sync.event
428 func mutexevent(cycles int64, skip int) {
429         if cycles < 0 {
430                 cycles = 0
431         }
432         rate := int64(atomic.Load64(&mutexprofilerate))
433         // TODO(pjw): measure impact of always calling fastrand vs using something
434         // like malloc.go:nextSample()
435         if rate > 0 && int64(fastrand())%rate == 0 {
436                 saveblockevent(cycles, skip+1, mutexProfile)
437         }
438 }
439
440 // Go interface to profile data.
441
442 // A StackRecord describes a single execution stack.
443 type StackRecord struct {
444         Stack0 [32]uintptr // stack trace for this record; ends at first 0 entry
445 }
446
447 // Stack returns the stack trace associated with the record,
448 // a prefix of r.Stack0.
449 func (r *StackRecord) Stack() []uintptr {
450         for i, v := range r.Stack0 {
451                 if v == 0 {
452                         return r.Stack0[0:i]
453                 }
454         }
455         return r.Stack0[0:]
456 }
457
458 // MemProfileRate controls the fraction of memory allocations
459 // that are recorded and reported in the memory profile.
460 // The profiler aims to sample an average of
461 // one allocation per MemProfileRate bytes allocated.
462 //
463 // To include every allocated block in the profile, set MemProfileRate to 1.
464 // To turn off profiling entirely, set MemProfileRate to 0.
465 //
466 // The tools that process the memory profiles assume that the
467 // profile rate is constant across the lifetime of the program
468 // and equal to the current value. Programs that change the
469 // memory profiling rate should do so just once, as early as
470 // possible in the execution of the program (for example,
471 // at the beginning of main).
472 var MemProfileRate int = 512 * 1024
473
474 // A MemProfileRecord describes the live objects allocated
475 // by a particular call sequence (stack trace).
476 type MemProfileRecord struct {
477         AllocBytes, FreeBytes     int64       // number of bytes allocated, freed
478         AllocObjects, FreeObjects int64       // number of objects allocated, freed
479         Stack0                    [32]uintptr // stack trace for this record; ends at first 0 entry
480 }
481
482 // InUseBytes returns the number of bytes in use (AllocBytes - FreeBytes).
483 func (r *MemProfileRecord) InUseBytes() int64 { return r.AllocBytes - r.FreeBytes }
484
485 // InUseObjects returns the number of objects in use (AllocObjects - FreeObjects).
486 func (r *MemProfileRecord) InUseObjects() int64 {
487         return r.AllocObjects - r.FreeObjects
488 }
489
490 // Stack returns the stack trace associated with the record,
491 // a prefix of r.Stack0.
492 func (r *MemProfileRecord) Stack() []uintptr {
493         for i, v := range r.Stack0 {
494                 if v == 0 {
495                         return r.Stack0[0:i]
496                 }
497         }
498         return r.Stack0[0:]
499 }
500
501 // MemProfile returns a profile of memory allocated and freed per allocation
502 // site.
503 //
504 // MemProfile returns n, the number of records in the current memory profile.
505 // If len(p) >= n, MemProfile copies the profile into p and returns n, true.
506 // If len(p) < n, MemProfile does not change p and returns n, false.
507 //
508 // If inuseZero is true, the profile includes allocation records
509 // where r.AllocBytes > 0 but r.AllocBytes == r.FreeBytes.
510 // These are sites where memory was allocated, but it has all
511 // been released back to the runtime.
512 //
513 // The returned profile may be up to two garbage collection cycles old.
514 // This is to avoid skewing the profile toward allocations; because
515 // allocations happen in real time but frees are delayed until the garbage
516 // collector performs sweeping, the profile only accounts for allocations
517 // that have had a chance to be freed by the garbage collector.
518 //
519 // Most clients should use the runtime/pprof package or
520 // the testing package's -test.memprofile flag instead
521 // of calling MemProfile directly.
522 func MemProfile(p []MemProfileRecord, inuseZero bool) (n int, ok bool) {
523         lock(&proflock)
524         // If we're between mProf_NextCycle and mProf_Flush, take care
525         // of flushing to the active profile so we only have to look
526         // at the active profile below.
527         mProf_FlushLocked()
528         clear := true
529         for b := mbuckets; b != nil; b = b.allnext {
530                 mp := b.mp()
531                 if inuseZero || mp.active.alloc_bytes != mp.active.free_bytes {
532                         n++
533                 }
534                 if mp.active.allocs != 0 || mp.active.frees != 0 {
535                         clear = false
536                 }
537         }
538         if clear {
539                 // Absolutely no data, suggesting that a garbage collection
540                 // has not yet happened. In order to allow profiling when
541                 // garbage collection is disabled from the beginning of execution,
542                 // accumulate all of the cycles, and recount buckets.
543                 n = 0
544                 for b := mbuckets; b != nil; b = b.allnext {
545                         mp := b.mp()
546                         for c := range mp.future {
547                                 mp.active.add(&mp.future[c])
548                                 mp.future[c] = memRecordCycle{}
549                         }
550                         if inuseZero || mp.active.alloc_bytes != mp.active.free_bytes {
551                                 n++
552                         }
553                 }
554         }
555         if n <= len(p) {
556                 ok = true
557                 idx := 0
558                 for b := mbuckets; b != nil; b = b.allnext {
559                         mp := b.mp()
560                         if inuseZero || mp.active.alloc_bytes != mp.active.free_bytes {
561                                 record(&p[idx], b)
562                                 idx++
563                         }
564                 }
565         }
566         unlock(&proflock)
567         return
568 }
569
570 // Write b's data to r.
571 func record(r *MemProfileRecord, b *bucket) {
572         mp := b.mp()
573         r.AllocBytes = int64(mp.active.alloc_bytes)
574         r.FreeBytes = int64(mp.active.free_bytes)
575         r.AllocObjects = int64(mp.active.allocs)
576         r.FreeObjects = int64(mp.active.frees)
577         if raceenabled {
578                 racewriterangepc(unsafe.Pointer(&r.Stack0[0]), unsafe.Sizeof(r.Stack0), getcallerpc(unsafe.Pointer(&r)), funcPC(MemProfile))
579         }
580         if msanenabled {
581                 msanwrite(unsafe.Pointer(&r.Stack0[0]), unsafe.Sizeof(r.Stack0))
582         }
583         copy(r.Stack0[:], b.stk())
584         for i := int(b.nstk); i < len(r.Stack0); i++ {
585                 r.Stack0[i] = 0
586         }
587 }
588
589 func iterate_memprof(fn func(*bucket, uintptr, *uintptr, uintptr, uintptr, uintptr)) {
590         lock(&proflock)
591         for b := mbuckets; b != nil; b = b.allnext {
592                 mp := b.mp()
593                 fn(b, b.nstk, &b.stk()[0], b.size, mp.active.allocs, mp.active.frees)
594         }
595         unlock(&proflock)
596 }
597
598 // BlockProfileRecord describes blocking events originated
599 // at a particular call sequence (stack trace).
600 type BlockProfileRecord struct {
601         Count  int64
602         Cycles int64
603         StackRecord
604 }
605
606 // BlockProfile returns n, the number of records in the current blocking profile.
607 // If len(p) >= n, BlockProfile copies the profile into p and returns n, true.
608 // If len(p) < n, BlockProfile does not change p and returns n, false.
609 //
610 // Most clients should use the runtime/pprof package or
611 // the testing package's -test.blockprofile flag instead
612 // of calling BlockProfile directly.
613 func BlockProfile(p []BlockProfileRecord) (n int, ok bool) {
614         lock(&proflock)
615         for b := bbuckets; b != nil; b = b.allnext {
616                 n++
617         }
618         if n <= len(p) {
619                 ok = true
620                 for b := bbuckets; b != nil; b = b.allnext {
621                         bp := b.bp()
622                         r := &p[0]
623                         r.Count = bp.count
624                         r.Cycles = bp.cycles
625                         if raceenabled {
626                                 racewriterangepc(unsafe.Pointer(&r.Stack0[0]), unsafe.Sizeof(r.Stack0), getcallerpc(unsafe.Pointer(&p)), funcPC(BlockProfile))
627                         }
628                         if msanenabled {
629                                 msanwrite(unsafe.Pointer(&r.Stack0[0]), unsafe.Sizeof(r.Stack0))
630                         }
631                         i := copy(r.Stack0[:], b.stk())
632                         for ; i < len(r.Stack0); i++ {
633                                 r.Stack0[i] = 0
634                         }
635                         p = p[1:]
636                 }
637         }
638         unlock(&proflock)
639         return
640 }
641
642 // MutexProfile returns n, the number of records in the current mutex profile.
643 // If len(p) >= n, MutexProfile copies the profile into p and returns n, true.
644 // Otherwise, MutexProfile does not change p, and returns n, false.
645 //
646 // Most clients should use the runtime/pprof package
647 // instead of calling MutexProfile directly.
648 func MutexProfile(p []BlockProfileRecord) (n int, ok bool) {
649         lock(&proflock)
650         for b := xbuckets; b != nil; b = b.allnext {
651                 n++
652         }
653         if n <= len(p) {
654                 ok = true
655                 for b := xbuckets; b != nil; b = b.allnext {
656                         bp := b.bp()
657                         r := &p[0]
658                         r.Count = int64(bp.count)
659                         r.Cycles = bp.cycles
660                         i := copy(r.Stack0[:], b.stk())
661                         for ; i < len(r.Stack0); i++ {
662                                 r.Stack0[i] = 0
663                         }
664                         p = p[1:]
665                 }
666         }
667         unlock(&proflock)
668         return
669 }
670
671 // ThreadCreateProfile returns n, the number of records in the thread creation profile.
672 // If len(p) >= n, ThreadCreateProfile copies the profile into p and returns n, true.
673 // If len(p) < n, ThreadCreateProfile does not change p and returns n, false.
674 //
675 // Most clients should use the runtime/pprof package instead
676 // of calling ThreadCreateProfile directly.
677 func ThreadCreateProfile(p []StackRecord) (n int, ok bool) {
678         first := (*m)(atomic.Loadp(unsafe.Pointer(&allm)))
679         for mp := first; mp != nil; mp = mp.alllink {
680                 n++
681         }
682         if n <= len(p) {
683                 ok = true
684                 i := 0
685                 for mp := first; mp != nil; mp = mp.alllink {
686                         p[i].Stack0 = mp.createstack
687                         i++
688                 }
689         }
690         return
691 }
692
693 // GoroutineProfile returns n, the number of records in the active goroutine stack profile.
694 // If len(p) >= n, GoroutineProfile copies the profile into p and returns n, true.
695 // If len(p) < n, GoroutineProfile does not change p and returns n, false.
696 //
697 // Most clients should use the runtime/pprof package instead
698 // of calling GoroutineProfile directly.
699 func GoroutineProfile(p []StackRecord) (n int, ok bool) {
700         gp := getg()
701
702         isOK := func(gp1 *g) bool {
703                 // Checking isSystemGoroutine here makes GoroutineProfile
704                 // consistent with both NumGoroutine and Stack.
705                 return gp1 != gp && readgstatus(gp1) != _Gdead && !isSystemGoroutine(gp1)
706         }
707
708         stopTheWorld("profile")
709
710         n = 1
711         for _, gp1 := range allgs {
712                 if isOK(gp1) {
713                         n++
714                 }
715         }
716
717         if n <= len(p) {
718                 ok = true
719                 r := p
720
721                 // Save current goroutine.
722                 sp := getcallersp(unsafe.Pointer(&p))
723                 pc := getcallerpc(unsafe.Pointer(&p))
724                 systemstack(func() {
725                         saveg(pc, sp, gp, &r[0])
726                 })
727                 r = r[1:]
728
729                 // Save other goroutines.
730                 for _, gp1 := range allgs {
731                         if isOK(gp1) {
732                                 if len(r) == 0 {
733                                         // Should be impossible, but better to return a
734                                         // truncated profile than to crash the entire process.
735                                         break
736                                 }
737                                 saveg(^uintptr(0), ^uintptr(0), gp1, &r[0])
738                                 r = r[1:]
739                         }
740                 }
741         }
742
743         startTheWorld()
744
745         return n, ok
746 }
747
748 func saveg(pc, sp uintptr, gp *g, r *StackRecord) {
749         n := gentraceback(pc, sp, 0, gp, 0, &r.Stack0[0], len(r.Stack0), nil, nil, 0)
750         if n < len(r.Stack0) {
751                 r.Stack0[n] = 0
752         }
753 }
754
755 // Stack formats a stack trace of the calling goroutine into buf
756 // and returns the number of bytes written to buf.
757 // If all is true, Stack formats stack traces of all other goroutines
758 // into buf after the trace for the current goroutine.
759 func Stack(buf []byte, all bool) int {
760         if all {
761                 stopTheWorld("stack trace")
762         }
763
764         n := 0
765         if len(buf) > 0 {
766                 gp := getg()
767                 sp := getcallersp(unsafe.Pointer(&buf))
768                 pc := getcallerpc(unsafe.Pointer(&buf))
769                 systemstack(func() {
770                         g0 := getg()
771                         // Force traceback=1 to override GOTRACEBACK setting,
772                         // so that Stack's results are consistent.
773                         // GOTRACEBACK is only about crash dumps.
774                         g0.m.traceback = 1
775                         g0.writebuf = buf[0:0:len(buf)]
776                         goroutineheader(gp)
777                         traceback(pc, sp, 0, gp)
778                         if all {
779                                 tracebackothers(gp)
780                         }
781                         g0.m.traceback = 0
782                         n = len(g0.writebuf)
783                         g0.writebuf = nil
784                 })
785         }
786
787         if all {
788                 startTheWorld()
789         }
790         return n
791 }
792
793 // Tracing of alloc/free/gc.
794
795 var tracelock mutex
796
797 func tracealloc(p unsafe.Pointer, size uintptr, typ *_type) {
798         lock(&tracelock)
799         gp := getg()
800         gp.m.traceback = 2
801         if typ == nil {
802                 print("tracealloc(", p, ", ", hex(size), ")\n")
803         } else {
804                 print("tracealloc(", p, ", ", hex(size), ", ", typ.string(), ")\n")
805         }
806         if gp.m.curg == nil || gp == gp.m.curg {
807                 goroutineheader(gp)
808                 pc := getcallerpc(unsafe.Pointer(&p))
809                 sp := getcallersp(unsafe.Pointer(&p))
810                 systemstack(func() {
811                         traceback(pc, sp, 0, gp)
812                 })
813         } else {
814                 goroutineheader(gp.m.curg)
815                 traceback(^uintptr(0), ^uintptr(0), 0, gp.m.curg)
816         }
817         print("\n")
818         gp.m.traceback = 0
819         unlock(&tracelock)
820 }
821
822 func tracefree(p unsafe.Pointer, size uintptr) {
823         lock(&tracelock)
824         gp := getg()
825         gp.m.traceback = 2
826         print("tracefree(", p, ", ", hex(size), ")\n")
827         goroutineheader(gp)
828         pc := getcallerpc(unsafe.Pointer(&p))
829         sp := getcallersp(unsafe.Pointer(&p))
830         systemstack(func() {
831                 traceback(pc, sp, 0, gp)
832         })
833         print("\n")
834         gp.m.traceback = 0
835         unlock(&tracelock)
836 }
837
838 func tracegc() {
839         lock(&tracelock)
840         gp := getg()
841         gp.m.traceback = 2
842         print("tracegc()\n")
843         // running on m->g0 stack; show all non-g0 goroutines
844         tracebackothers(gp)
845         print("end tracegc\n")
846         print("\n")
847         gp.m.traceback = 0
848         unlock(&tracelock)
849 }