| 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 |
// For gofrontend, use go:linkname for blockevent so that |
| 16 |
// runtime/pprof/pprof_test can call it. |
| 17 |
//go:linkname blockevent |
| 18 |
|
| 19 |
// NOTE(rsc): Everything here could use cas if contention became an issue. |
| 20 |
var proflock mutex |
| 21 |
|
| 22 |
// All memory allocations are local and do not escape outside of the profiler. |
| 23 |
// The profiler is forbidden from referring to garbage-collected memory. |
| 24 |
|
| 25 |
const ( |
| 26 |
// profile types |
| 27 |
memProfile bucketType = 1 + iota |
| 28 |
blockProfile |
| 29 |
mutexProfile |
| 30 |
|
| 31 |
// a profile bucket from one of the categories above whose stack |
| 32 |
// trace has been fixed up / pruned. |
| 33 |
prunedProfile |
| 34 |
|
| 35 |
// size of bucket hash table |
| 36 |
buckHashSize = 179999 |
| 37 |
|
| 38 |
// max depth of stack to record in bucket |
| 39 |
maxStack = 32 |
| 40 |
) |
| 41 |
|
| 42 |
type bucketType int |
| 43 |
|
| 44 |
// A bucket holds per-call-stack profiling information. |
| 45 |
// The representation is a bit sleazy, inherited from C. |
| 46 |
// This struct defines the bucket header. It is followed in |
| 47 |
// memory by the stack words and then the actual record |
| 48 |
// data, either a memRecord or a blockRecord. |
| 49 |
// |
| 50 |
// Per-call-stack profiling information. |
| 51 |
// Lookup by hashing call stack into a linked-list hash table. |
| 52 |
// |
| 53 |
// No heap pointers. |
| 54 |
// |
| 55 |
//go:notinheap |
| 56 |
type bucket struct { |
| 57 |
next *bucket |
| 58 |
allnext *bucket |
| 59 |
typ bucketType // memBucket or blockBucket (includes mutexProfile) |
| 60 |
hash uintptr |
| 61 |
size uintptr |
| 62 |
nstk uintptr |
| 63 |
skip int |
| 64 |
} |
| 65 |
|
| 66 |
// A memRecord is the bucket data for a bucket of type memProfile, |
| 67 |
// part of the memory profile. |
| 68 |
type memRecord struct { |
| 69 |
// The following complex 3-stage scheme of stats accumulation |
| 70 |
// is required to obtain a consistent picture of mallocs and frees |
| 71 |
// for some point in time. |
| 72 |
// The problem is that mallocs come in real time, while frees |
| 73 |
// come only after a GC during concurrent sweeping. So if we would |
| 74 |
// naively count them, we would get a skew toward mallocs. |
| 75 |
// |
| 76 |
// Hence, we delay information to get consistent snapshots as |
| 77 |
// of mark termination. Allocations count toward the next mark |
| 78 |
// termination's snapshot, while sweep frees count toward the |
| 79 |
// previous mark termination's snapshot: |
| 80 |
// |
| 81 |
// MT MT MT MT |
| 82 |
// .·| .·| .·| .·| |
| 83 |
// .·˙ | .·˙ | .·˙ | .·˙ | |
| 84 |
// .·˙ | .·˙ | .·˙ | .·˙ | |
| 85 |
// .·˙ |.·˙ |.·˙ |.·˙ | |
| 86 |
// |
| 87 |
// alloc → ▲ ← free |
| 88 |
// ┠┅┅┅┅┅┅┅┅┅┅┅P |
| 89 |
// C+2 → C+1 → C |
| 90 |
// |
| 91 |
// alloc → ▲ ← free |
| 92 |
// ┠┅┅┅┅┅┅┅┅┅┅┅P |
| 93 |
// C+2 → C+1 → C |
| 94 |
// |
| 95 |
// Since we can't publish a consistent snapshot until all of |
| 96 |
// the sweep frees are accounted for, we wait until the next |
| 97 |
// mark termination ("MT" above) to publish the previous mark |
| 98 |
// termination's snapshot ("P" above). To do this, allocation |
| 99 |
// and free events are accounted to *future* heap profile |
| 100 |
// cycles ("C+n" above) and we only publish a cycle once all |
| 101 |
// of the events from that cycle must be done. Specifically: |
| 102 |
// |
| 103 |
// Mallocs are accounted to cycle C+2. |
| 104 |
// Explicit frees are accounted to cycle C+2. |
| 105 |
// GC frees (done during sweeping) are accounted to cycle C+1. |
| 106 |
// |
| 107 |
// After mark termination, we increment the global heap |
| 108 |
// profile cycle counter and accumulate the stats from cycle C |
| 109 |
// into the active profile. |
| 110 |
|
| 111 |
// active is the currently published profile. A profiling |
| 112 |
// cycle can be accumulated into active once its complete. |
| 113 |
active memRecordCycle |
| 114 |
|
| 115 |
// future records the profile events we're counting for cycles |
| 116 |
// that have not yet been published. This is ring buffer |
| 117 |
// indexed by the global heap profile cycle C and stores |
| 118 |
// cycles C, C+1, and C+2. Unlike active, these counts are |
| 119 |
// only for a single cycle; they are not cumulative across |
| 120 |
// cycles. |
| 121 |
// |
| 122 |
// We store cycle C here because there's a window between when |
| 123 |
// C becomes the active cycle and when we've flushed it to |
| 124 |
// active. |
| 125 |
future [3]memRecordCycle |
| 126 |
} |
| 127 |
|
| 128 |
// memRecordCycle |
| 129 |
type memRecordCycle struct { |
| 130 |
allocs, frees uintptr |
| 131 |
alloc_bytes, free_bytes uintptr |
| 132 |
} |
| 133 |
|
| 134 |
// add accumulates b into a. It does not zero b. |
| 135 |
func (a *memRecordCycle) add(b *memRecordCycle) { |
| 136 |
a.allocs += b.allocs |
| 137 |
a.frees += b.frees |
| 138 |
a.alloc_bytes += b.alloc_bytes |
| 139 |
a.free_bytes += b.free_bytes |
| 140 |
} |
| 141 |
|
| 142 |
// A blockRecord is the bucket data for a bucket of type blockProfile, |
| 143 |
// which is used in blocking and mutex profiles. |
| 144 |
type blockRecord struct { |
| 145 |
count float64 |
| 146 |
cycles int64 |
| 147 |
} |
| 148 |
|
| 149 |
var ( |
| 150 |
mbuckets *bucket // memory profile buckets |
| 151 |
bbuckets *bucket // blocking profile buckets |
| 152 |
xbuckets *bucket // mutex profile buckets |
| 153 |
sbuckets *bucket // pre-symbolization profile buckets (stacks fixed up) |
| 154 |
freebuckets *bucket // freelist of unused fixed up profile buckets |
| 155 |
buckhash *[buckHashSize]*bucket |
| 156 |
bucketmem uintptr |
| 157 |
|
| 158 |
mProf struct { |
| 159 |
// All fields in mProf are protected by proflock. |
| 160 |
|
| 161 |
// cycle is the global heap profile cycle. This wraps |
| 162 |
// at mProfCycleWrap. |
| 163 |
cycle uint32 |
| 164 |
// flushed indicates that future[cycle] in all buckets |
| 165 |
// has been flushed to the active profile. |
| 166 |
flushed bool |
| 167 |
} |
| 168 |
) |
| 169 |
|
| 170 |
const mProfCycleWrap = uint32(len(memRecord{}.future)) * (2 << 24) |
| 171 |
|
| 172 |
// payloadOffset() returns a pointer into the part of a bucket |
| 173 |
// containing the profile payload (skips past the bucket struct itself |
| 174 |
// and then the stack trace). |
| 175 |
func payloadOffset(typ bucketType, nstk uintptr) uintptr { |
| 176 |
if typ == prunedProfile { |
| 177 |
// To allow reuse of prunedProfile buckets between different |
| 178 |
// collections, allocate them with the max stack size (the portion |
| 179 |
// of the stack used will vary from trace to trace). |
| 180 |
nstk = maxStack |
| 181 |
} |
| 182 |
return unsafe.Sizeof(bucket{}) + uintptr(nstk)*unsafe.Sizeof(uintptr) |
| 183 |
} |
| 184 |
|
| 185 |
func max(x, y uintptr) uintptr { |
| 186 |
if x > y { |
| 187 |
return x |
| 188 |
} |
| 189 |
return y |
| 190 |
} |
| 191 |
|
| 192 |
// newBucket allocates a bucket with the given type and number of stack entries. |
| 193 |
func newBucket(typ bucketType, nstk int, skipCount int) *bucket { |
| 194 |
size := payloadOffset(typ, uintptr(nstk)) |
| 195 |
switch typ { |
| 196 |
default: |
| 197 |
throw("invalid profile bucket type") |
| 198 |
case prunedProfile: |
| 199 |
// stack-fixed buckets are large enough to accommodate any payload. |
| 200 |
size += max(unsafe.Sizeof(memRecord{}), unsafe.Sizeof(blockRecord{})) |
| 201 |
case memProfile: |
| 202 |
size += unsafe.Sizeof(memRecord{}) |
| 203 |
case blockProfile, mutexProfile: |
| 204 |
size += unsafe.Sizeof(blockRecord{}) |
| 205 |
} |
| 206 |
|
| 207 |
b := (*bucket)(persistentalloc(size, 0, &memstats.buckhash_sys)) |
| 208 |
bucketmem += size |
| 209 |
b.typ = typ |
| 210 |
b.nstk = uintptr(nstk) |
| 211 |
b.skip = skipCount |
| 212 |
return b |
| 213 |
} |
| 214 |
|
| 215 |
// stk returns the slice in b holding the stack. |
| 216 |
func (b *bucket) stk() []uintptr { |
| 217 |
stk := (*[maxStack]uintptr)(add(unsafe.Pointer(b), unsafe.Sizeof(*b))) |
| 218 |
return stk[:b.nstk:b.nstk] |
| 219 |
} |
| 220 |
|
| 221 |
// mp returns the memRecord associated with the memProfile bucket b. |
| 222 |
func (b *bucket) mp() *memRecord { |
| 223 |
if b.typ != memProfile && b.typ != prunedProfile { |
| 224 |
throw("bad use of bucket.mp") |
| 225 |
} |
| 226 |
return (*memRecord)(add(unsafe.Pointer(b), payloadOffset(b.typ, b.nstk))) |
| 227 |
} |
| 228 |
|
| 229 |
// bp returns the blockRecord associated with the blockProfile bucket b. |
| 230 |
func (b *bucket) bp() *blockRecord { |
| 231 |
if b.typ != blockProfile && b.typ != mutexProfile && b.typ != prunedProfile { |
| 232 |
throw("bad use of bucket.bp") |
| 233 |
} |
| 234 |
return (*blockRecord)(add(unsafe.Pointer(b), payloadOffset(b.typ, b.nstk))) |
| 235 |
} |
| 236 |
|
| 237 |
// Return the bucket for stk[0:nstk], allocating new bucket if needed. |
| 238 |
func stkbucket(typ bucketType, size uintptr, skip int, stk []uintptr, alloc bool) *bucket { |
| 239 |
if buckhash == nil { |
| 240 |
buckhash = (*[buckHashSize]*bucket)(sysAlloc(unsafe.Sizeof(*buckhash), &memstats.buckhash_sys)) |
| 241 |
if buckhash == nil { |
| 242 |
throw("runtime: cannot allocate memory") |
| 243 |
} |
| 244 |
} |
| 245 |
|
| 246 |
// Hash stack. |
| 247 |
var h uintptr |
| 248 |
for _, pc := range stk { |
| 249 |
h += pc |
| 250 |
h += h << 10 |
| 251 |
h ^= h >> 6 |
| 252 |
} |
| 253 |
// hash in size |
| 254 |
h += size |
| 255 |
h += h << 10 |
| 256 |
h ^= h >> 6 |
| 257 |
// finalize |
| 258 |
h += h << 3 |
| 259 |
h ^= h >> 11 |
| 260 |
|
| 261 |
i := int(h % buckHashSize) |
| 262 |
for b := buckhash[i]; b != nil; b = b.next { |
| 263 |
if b.typ == typ && b.hash == h && b.size == size && eqslice(b.stk(), stk) { |
| 264 |
return b |
| 265 |
} |
| 266 |
} |
| 267 |
|
| 268 |
if !alloc { |
| 269 |
return nil |
| 270 |
} |
| 271 |
|
| 272 |
// Create new bucket. |
| 273 |
b := newBucket(typ, len(stk), skip) |
| 274 |
copy(b.stk(), stk) |
| 275 |
b.hash = h |
| 276 |
b.size = size |
| 277 |
b.next = buckhash[i] |
| 278 |
buckhash[i] = b |
| 279 |
if typ == memProfile { |
| 280 |
b.allnext = mbuckets |
| 281 |
mbuckets = b |
| 282 |
} else if typ == mutexProfile { |
| 283 |
b.allnext = xbuckets |
| 284 |
xbuckets = b |
| 285 |
} else if typ == prunedProfile { |
| 286 |
b.allnext = sbuckets |
| 287 |
sbuckets = b |
| 288 |
} else { |
| 289 |
b.allnext = bbuckets |
| 290 |
bbuckets = b |
| 291 |
} |
| 292 |
return b |
| 293 |
} |
| 294 |
|
| 295 |
func eqslice(x, y []uintptr) bool { |
| 296 |
if len(x) != len(y) { |
| 297 |
return false |
| 298 |
} |
| 299 |
for i, xi := range x { |
| 300 |
if xi != y[i] { |
| 301 |
return false |
| 302 |
} |
| 303 |
} |
| 304 |
return true |
| 305 |
} |
| 306 |
|
| 307 |
// mProf_NextCycle publishes the next heap profile cycle and creates a |
| 308 |
// fresh heap profile cycle. This operation is fast and can be done |
| 309 |
// during STW. The caller must call mProf_Flush before calling |
| 310 |
// mProf_NextCycle again. |
| 311 |
// |
| 312 |
// This is called by mark termination during STW so allocations and |
| 313 |
// frees after the world is started again count towards a new heap |
| 314 |
// profiling cycle. |
| 315 |
func mProf_NextCycle() { |
| 316 |
lock(&proflock) |
| 317 |
// We explicitly wrap mProf.cycle rather than depending on |
| 318 |
// uint wraparound because the memRecord.future ring does not |
| 319 |
// itself wrap at a power of two. |
| 320 |
mProf.cycle = (mProf.cycle + 1) % mProfCycleWrap |
| 321 |
mProf.flushed = false |
| 322 |
unlock(&proflock) |
| 323 |
} |
| 324 |
|
| 325 |
// mProf_Flush flushes the events from the current heap profiling |
| 326 |
// cycle into the active profile. After this it is safe to start a new |
| 327 |
// heap profiling cycle with mProf_NextCycle. |
| 328 |
// |
| 329 |
// This is called by GC after mark termination starts the world. In |
| 330 |
// contrast with mProf_NextCycle, this is somewhat expensive, but safe |
| 331 |
// to do concurrently. |
| 332 |
func mProf_Flush() { |
| 333 |
lock(&proflock) |
| 334 |
if !mProf.flushed { |
| 335 |
mProf_FlushLocked() |
| 336 |
mProf.flushed = true |
| 337 |
} |
| 338 |
unlock(&proflock) |
| 339 |
} |
| 340 |
|
| 341 |
func mProf_FlushLocked() { |
| 342 |
c := mProf.cycle |
| 343 |
for b := mbuckets; b != nil; b = b.allnext { |
| 344 |
mp := b.mp() |
| 345 |
|
| 346 |
// Flush cycle C into the published profile and clear |
| 347 |
// it for reuse. |
| 348 |
mpc := &mp.future[c%uint32(len(mp.future))] |
| 349 |
mp.active.add(mpc) |
| 350 |
*mpc = memRecordCycle{} |
| 351 |
} |
| 352 |
} |
| 353 |
|
| 354 |
// mProf_PostSweep records that all sweep frees for this GC cycle have |
| 355 |
// completed. This has the effect of publishing the heap profile |
| 356 |
// snapshot as of the last mark termination without advancing the heap |
| 357 |
// profile cycle. |
| 358 |
func mProf_PostSweep() { |
| 359 |
lock(&proflock) |
| 360 |
// Flush cycle C+1 to the active profile so everything as of |
| 361 |
// the last mark termination becomes visible. *Don't* advance |
| 362 |
// the cycle, since we're still accumulating allocs in cycle |
| 363 |
// C+2, which have to become C+1 in the next mark termination |
| 364 |
// and so on. |
| 365 |
c := mProf.cycle |
| 366 |
for b := mbuckets; b != nil; b = b.allnext { |
| 367 |
mp := b.mp() |
| 368 |
mpc := &mp.future[(c+1)%uint32(len(mp.future))] |
| 369 |
mp.active.add(mpc) |
| 370 |
*mpc = memRecordCycle{} |
| 371 |
} |
| 372 |
unlock(&proflock) |
| 373 |
} |
| 374 |
|
| 375 |
// Called by malloc to record a profiled block. |
| 376 |
func mProf_Malloc(p unsafe.Pointer, size uintptr) { |
| 377 |
var stk [maxStack]uintptr |
| 378 |
nstk := callersRaw(stk[:]) |
| 379 |
lock(&proflock) |
| 380 |
skip := 1 |
| 381 |
b := stkbucket(memProfile, size, skip, stk[:nstk], true) |
| 382 |
c := mProf.cycle |
| 383 |
mp := b.mp() |
| 384 |
mpc := &mp.future[(c+2)%uint32(len(mp.future))] |
| 385 |
mpc.allocs++ |
| 386 |
mpc.alloc_bytes += size |
| 387 |
unlock(&proflock) |
| 388 |
|
| 389 |
// Setprofilebucket locks a bunch of other mutexes, so we call it outside of proflock. |
| 390 |
// This reduces potential contention and chances of deadlocks. |
| 391 |
// Since the object must be alive during call to mProf_Malloc, |
| 392 |
// it's fine to do this non-atomically. |
| 393 |
systemstack(func() { |
| 394 |
setprofilebucket(p, b) |
| 395 |
}) |
| 396 |
} |
| 397 |
|
| 398 |
// Called when freeing a profiled block. |
| 399 |
func mProf_Free(b *bucket, size uintptr) { |
| 400 |
lock(&proflock) |
| 401 |
c := mProf.cycle |
| 402 |
mp := b.mp() |
| 403 |
mpc := &mp.future[(c+1)%uint32(len(mp.future))] |
| 404 |
mpc.frees++ |
| 405 |
mpc.free_bytes += size |
| 406 |
unlock(&proflock) |
| 407 |
} |
| 408 |
|
| 409 |
var blockprofilerate uint64 // in CPU ticks |
| 410 |
|
| 411 |
// SetBlockProfileRate controls the fraction of goroutine blocking events |
| 412 |
// that are reported in the blocking profile. The profiler aims to sample |
| 413 |
// an average of one blocking event per rate nanoseconds spent blocked. |
| 414 |
// |
| 415 |
// To include every blocking event in the profile, pass rate = 1. |
| 416 |
// To turn off profiling entirely, pass rate <= 0. |
| 417 |
func SetBlockProfileRate(rate int) { |
| 418 |
var r int64 |
| 419 |
if rate <= 0 { |
| 420 |
r = 0 // disable profiling |
| 421 |
} else if rate == 1 { |
| 422 |
r = 1 // profile everything |
| 423 |
} else { |
| 424 |
// convert ns to cycles, use float64 to prevent overflow during multiplication |
| 425 |
r = int64(float64(rate) * float64(tickspersecond()) / (1000 * 1000 * 1000)) |
| 426 |
if r == 0 { |
| 427 |
r = 1 |
| 428 |
} |
| 429 |
} |
| 430 |
|
| 431 |
atomic.Store64(&blockprofilerate, uint64(r)) |
| 432 |
} |
| 433 |
|
| 434 |
func blockevent(cycles int64, skip int) { |
| 435 |
if cycles <= 0 { |
| 436 |
cycles = 1 |
| 437 |
} |
| 438 |
|
| 439 |
rate := int64(atomic.Load64(&blockprofilerate)) |
| 440 |
if blocksampled(cycles, rate) { |
| 441 |
saveblockevent(cycles, rate, skip+1, blockProfile) |
| 442 |
} |
| 443 |
} |
| 444 |
|
| 445 |
// blocksampled returns true for all events where cycles >= rate. Shorter |
| 446 |
// events have a cycles/rate random chance of returning true. |
| 447 |
func blocksampled(cycles, rate int64) bool { |
| 448 |
if rate <= 0 || (rate > cycles && int64(fastrand())%rate > cycles) { |
| 449 |
return false |
| 450 |
} |
| 451 |
return true |
| 452 |
} |
| 453 |
|
| 454 |
func saveblockevent(cycles, rate int64, skip int, which bucketType) { |
| 455 |
gp := getg() |
| 456 |
var nstk int |
| 457 |
var stk [maxStack]uintptr |
| 458 |
if gp.m.curg == nil || gp.m.curg == gp { |
| 459 |
nstk = callersRaw(stk[:]) |
| 460 |
} else { |
| 461 |
// FIXME: This should get a traceback of gp.m.curg. |
| 462 |
// nstk = gcallers(gp.m.curg, skip, stk[:]) |
| 463 |
nstk = callersRaw(stk[:]) |
| 464 |
} |
| 465 |
lock(&proflock) |
| 466 |
b := stkbucket(which, 0, skip, stk[:nstk], true) |
| 467 |
|
| 468 |
if which == blockProfile && cycles < rate { |
| 469 |
// Remove sampling bias, see discussion on http://golang.org/cl/299991. |
| 470 |
b.bp().count += float64(rate) / float64(cycles) |
| 471 |
b.bp().cycles += rate |
| 472 |
} else { |
| 473 |
b.bp().count++ |
| 474 |
b.bp().cycles += cycles |
| 475 |
} |
| 476 |
unlock(&proflock) |
| 477 |
} |
| 478 |
|
| 479 |
var mutexprofilerate uint64 // fraction sampled |
| 480 |
|
| 481 |
// SetMutexProfileFraction controls the fraction of mutex contention events |
| 482 |
// that are reported in the mutex profile. On average 1/rate events are |
| 483 |
// reported. The previous rate is returned. |
| 484 |
// |
| 485 |
// To turn off profiling entirely, pass rate 0. |
| 486 |
// To just read the current rate, pass rate < 0. |
| 487 |
// (For n>1 the details of sampling may change.) |
| 488 |
func SetMutexProfileFraction(rate int) int { |
| 489 |
if rate < 0 { |
| 490 |
return int(mutexprofilerate) |
| 491 |
} |
| 492 |
old := mutexprofilerate |
| 493 |
atomic.Store64(&mutexprofilerate, uint64(rate)) |
| 494 |
return int(old) |
| 495 |
} |
| 496 |
|
| 497 |
//go:linkname mutexevent sync.event |
| 498 |
func mutexevent(cycles int64, skip int) { |
| 499 |
if cycles < 0 { |
| 500 |
cycles = 0 |
| 501 |
} |
| 502 |
rate := int64(atomic.Load64(&mutexprofilerate)) |
| 503 |
// TODO(pjw): measure impact of always calling fastrand vs using something |
| 504 |
// like malloc.go:nextSample() |
| 505 |
if rate > 0 && int64(fastrand())%rate == 0 { |
| 506 |
saveblockevent(cycles, rate, skip+1, mutexProfile) |
| 507 |
} |
| 508 |
} |
| 509 |
|
| 510 |
// Go interface to profile data. |
| 511 |
|
| 512 |
// A StackRecord describes a single execution stack. |
| 513 |
type StackRecord struct { |
| 514 |
Stack0 [32]uintptr // stack trace for this record; ends at first 0 entry |
| 515 |
} |
| 516 |
|
| 517 |
// Stack returns the stack trace associated with the record, |
| 518 |
// a prefix of r.Stack0. |
| 519 |
func (r *StackRecord) Stack() []uintptr { |
| 520 |
for i, v := range r.Stack0 { |
| 521 |
if v == 0 { |
| 522 |
return r.Stack0[0:i] |
| 523 |
} |
| 524 |
} |
| 525 |
return r.Stack0[0:] |
| 526 |
} |
| 527 |
|
| 528 |
// MemProfileRate controls the fraction of memory allocations |
| 529 |
// that are recorded and reported in the memory profile. |
| 530 |
// The profiler aims to sample an average of |
| 531 |
// one allocation per MemProfileRate bytes allocated. |
| 532 |
// |
| 533 |
// To include every allocated block in the profile, set MemProfileRate to 1. |
| 534 |
// To turn off profiling entirely, set MemProfileRate to 0. |
| 535 |
// |
| 536 |
// The tools that process the memory profiles assume that the |
| 537 |
// profile rate is constant across the lifetime of the program |
| 538 |
// and equal to the current value. Programs that change the |
| 539 |
// memory profiling rate should do so just once, as early as |
| 540 |
// possible in the execution of the program (for example, |
| 541 |
// at the beginning of main). |
| 542 |
var MemProfileRate int = defaultMemProfileRate(512 * 1024) |
| 543 |
|
| 544 |
// defaultMemProfileRate returns 0 if disableMemoryProfiling is set. |
| 545 |
// It exists primarily for the godoc rendering of MemProfileRate |
| 546 |
// above. |
| 547 |
func defaultMemProfileRate(v int) int { |
| 548 |
if disableMemoryProfiling { |
| 549 |
return 0 |
| 550 |
} |
| 551 |
return v |
| 552 |
} |
| 553 |
|
| 554 |
// disableMemoryProfiling is set by the linker if runtime.MemProfile |
| 555 |
// is not used and the link type guarantees nobody else could use it |
| 556 |
// elsewhere. |
| 557 |
var disableMemoryProfiling bool |
| 558 |
|
| 559 |
// A MemProfileRecord describes the live objects allocated |
| 560 |
// by a particular call sequence (stack trace). |
| 561 |
type MemProfileRecord struct { |
| 562 |
AllocBytes, FreeBytes int64 // number of bytes allocated, freed |
| 563 |
AllocObjects, FreeObjects int64 // number of objects allocated, freed |
| 564 |
Stack0 [32]uintptr // stack trace for this record; ends at first 0 entry |
| 565 |
} |
| 566 |
|
| 567 |
// InUseBytes returns the number of bytes in use (AllocBytes - FreeBytes). |
| 568 |
func (r *MemProfileRecord) InUseBytes() int64 { return r.AllocBytes - r.FreeBytes } |
| 569 |
|
| 570 |
// InUseObjects returns the number of objects in use (AllocObjects - FreeObjects). |
| 571 |
func (r *MemProfileRecord) InUseObjects() int64 { |
| 572 |
return r.AllocObjects - r.FreeObjects |
| 573 |
} |
| 574 |
|
| 575 |
// Stack returns the stack trace associated with the record, |
| 576 |
// a prefix of r.Stack0. |
| 577 |
func (r *MemProfileRecord) Stack() []uintptr { |
| 578 |
for i, v := range r.Stack0 { |
| 579 |
if v == 0 { |
| 580 |
return r.Stack0[0:i] |
| 581 |
} |
| 582 |
} |
| 583 |
return r.Stack0[0:] |
| 584 |
} |
| 585 |
|
| 586 |
// reusebucket tries to pick a prunedProfile bucket off |
| 587 |
// the freebuckets list, returning it if one is available or nil |
| 588 |
// if the free list is empty. |
| 589 |
func reusebucket(nstk int) *bucket { |
| 590 |
var b *bucket |
| 591 |
if freebuckets != nil { |
| 592 |
b = freebuckets |
| 593 |
freebuckets = freebuckets.allnext |
| 594 |
b.typ = prunedProfile |
| 595 |
b.nstk = uintptr(nstk) |
| 596 |
mp := b.mp() |
| 597 |
// Hack: rely on the fact that memprofile records are |
| 598 |
// larger than blockprofile records when clearing. |
| 599 |
*mp = memRecord{} |
| 600 |
} |
| 601 |
return b |
| 602 |
} |
| 603 |
|
| 604 |
// freebucket appends the specified prunedProfile bucket |
| 605 |
// onto the free list, and removes references to it from the hash. |
| 606 |
func freebucket(tofree *bucket) *bucket { |
| 607 |
// Thread this bucket into the free list. |
| 608 |
ret := tofree.allnext |
| 609 |
tofree.allnext = freebuckets |
| 610 |
freebuckets = tofree |
| 611 |
|
| 612 |
// Clean up the hash. The hash may point directly to this bucket... |
| 613 |
i := int(tofree.hash % buckHashSize) |
| 614 |
if buckhash[i] == tofree { |
| 615 |
buckhash[i] = tofree.next |
| 616 |
} else { |
| 617 |
// ... or when this bucket was inserted by stkbucket, it may have been |
| 618 |
// chained off some other unrelated bucket. |
| 619 |
for b := buckhash[i]; b != nil; b = b.next { |
| 620 |
if b.next == tofree { |
| 621 |
b.next = tofree.next |
| 622 |
break |
| 623 |
} |
| 624 |
} |
| 625 |
} |
| 626 |
return ret |
| 627 |
} |
| 628 |
|
| 629 |
// fixupStack takes a 'raw' stack trace (stack of PCs generated by |
| 630 |
// callersRaw) and performs pre-symbolization fixup on it, returning |
| 631 |
// the results in 'canonStack'. For each frame we look at the |
| 632 |
// file/func/line information, then use that info to decide whether to |
| 633 |
// include the frame in the final symbolized stack (removing frames |
| 634 |
// corresponding to 'morestack' routines, for example). We also expand |
| 635 |
// frames if the PC values to which they refer correponds to inlined |
| 636 |
// functions to allow for expanded symbolic info to be filled in |
| 637 |
// later. Note: there is code in go-callers.c's backtrace_full callback() |
| 638 |
// function that performs very similar fixups; these two code paths |
| 639 |
// should be kept in sync. |
| 640 |
func fixupStack(stk []uintptr, skip int, canonStack *[maxStack]uintptr, size uintptr) int { |
| 641 |
var cidx int |
| 642 |
var termTrace bool |
| 643 |
// Increase the skip count to take into account the frames corresponding |
| 644 |
// to runtime.callersRaw and to the C routine that it invokes. |
| 645 |
skip += 2 |
| 646 |
sawSigtramp := false |
| 647 |
for _, pc := range stk { |
| 648 |
// Subtract 1 from PC to undo the 1 we added in callback in |
| 649 |
// go-callers.c. |
| 650 |
function, file, _, frames := funcfileline(pc-1, -1, false) |
| 651 |
|
| 652 |
// Skip an unnamed function above sigtramp, as it is |
| 653 |
// likely the signal handler. |
| 654 |
if sawSigtramp { |
| 655 |
sawSigtramp = false |
| 656 |
if function == "" { |
| 657 |
continue |
| 658 |
} |
| 659 |
} |
| 660 |
|
| 661 |
// Skip split-stack functions (match by function name) |
| 662 |
skipFrame := false |
| 663 |
if hasPrefix(function, "_____morestack_") || hasPrefix(function, "__morestack_") { |
| 664 |
skipFrame = true |
| 665 |
} |
| 666 |
|
| 667 |
// Skip split-stack functions (match by file) |
| 668 |
if hasSuffix(file, "/morestack.S") { |
| 669 |
skipFrame = true |
| 670 |
} |
| 671 |
|
| 672 |
// Skip thunks and recover functions and other functions |
| 673 |
// specific to gccgo, that do not appear in the gc toolchain. |
| 674 |
fcn := function |
| 675 |
if hasSuffix(fcn, "..r") { |
| 676 |
skipFrame = true |
| 677 |
} else if function == "runtime.deferreturn" || function == "runtime.sighandler" { |
| 678 |
skipFrame = true |
| 679 |
} else if function == "runtime.sigtramp" || function == "runtime.sigtrampgo" { |
| 680 |
skipFrame = true |
| 681 |
// Also skip subsequent unnamed functions, |
| 682 |
// which will be the signal handler itself. |
| 683 |
sawSigtramp = true |
| 684 |
} else { |
| 685 |
for fcn != "" && (fcn[len(fcn)-1] >= '0' && fcn[len(fcn)-1] <= '9') { |
| 686 |
fcn = fcn[:len(fcn)-1] |
| 687 |
} |
| 688 |
if hasSuffix(fcn, "..stub") || hasSuffix(fcn, "..thunk") { |
| 689 |
skipFrame = true |
| 690 |
} |
| 691 |
} |
| 692 |
if skipFrame { |
| 693 |
continue |
| 694 |
} |
| 695 |
|
| 696 |
// Terminate the trace if we encounter a frame corresponding to |
| 697 |
// runtime.main, runtime.kickoff, makecontext, etc. See the |
| 698 |
// corresponding code in go-callers.c, callback function used |
| 699 |
// with backtrace_full. |
| 700 |
if function == "makecontext" { |
| 701 |
termTrace = true |
| 702 |
} |
| 703 |
if hasSuffix(file, "/proc.c") && function == "runtime_mstart" { |
| 704 |
termTrace = true |
| 705 |
} |
| 706 |
if hasSuffix(file, "/proc.go") && |
| 707 |
(function == "runtime.main" || function == "runtime.kickoff") { |
| 708 |
termTrace = true |
| 709 |
} |
| 710 |
|
| 711 |
// Expand inline frames. |
| 712 |
for i := 0; i < frames; i++ { |
| 713 |
(*canonStack)[cidx] = pc |
| 714 |
cidx++ |
| 715 |
if cidx >= maxStack { |
| 716 |
termTrace = true |
| 717 |
break |
| 718 |
} |
| 719 |
} |
| 720 |
if termTrace { |
| 721 |
break |
| 722 |
} |
| 723 |
} |
| 724 |
|
| 725 |
// Apply skip count. Needs to be done after expanding inline frames. |
| 726 |
if skip != 0 { |
| 727 |
if skip >= cidx { |
| 728 |
return 0 |
| 729 |
} |
| 730 |
copy(canonStack[:cidx-skip], canonStack[skip:]) |
| 731 |
return cidx - skip |
| 732 |
} |
| 733 |
|
| 734 |
return cidx |
| 735 |
} |
| 736 |
|
| 737 |
// fixupBucket takes a raw memprofile bucket and creates a new bucket |
| 738 |
// in which the stack trace has been fixed up (inline frames expanded, |
| 739 |
// unwanted frames stripped out). Original bucket is left unmodified; |
| 740 |
// a new symbolizeProfile bucket may be generated as a side effect. |
| 741 |
// Payload information from the original bucket is incorporated into |
| 742 |
// the new bucket. |
| 743 |
func fixupBucket(b *bucket) { |
| 744 |
var canonStack [maxStack]uintptr |
| 745 |
frames := fixupStack(b.stk(), b.skip, &canonStack, b.size) |
| 746 |
cb := stkbucket(prunedProfile, b.size, 0, canonStack[:frames], true) |
| 747 |
switch b.typ { |
| 748 |
default: |
| 749 |
throw("invalid profile bucket type") |
| 750 |
case memProfile: |
| 751 |
rawrecord := b.mp() |
| 752 |
cb.mp().active.add(&rawrecord.active) |
| 753 |
case blockProfile, mutexProfile: |
| 754 |
cb.bp().count += b.bp().count |
| 755 |
cb.bp().cycles += b.bp().cycles |
| 756 |
} |
| 757 |
} |
| 758 |
|
| 759 |
// MemProfile returns a profile of memory allocated and freed per allocation |
| 760 |
// site. |
| 761 |
// |
| 762 |
// MemProfile returns n, the number of records in the current memory profile. |
| 763 |
// If len(p) >= n, MemProfile copies the profile into p and returns n, true. |
| 764 |
// If len(p) < n, MemProfile does not change p and returns n, false. |
| 765 |
// |
| 766 |
// If inuseZero is true, the profile includes allocation records |
| 767 |
// where r.AllocBytes > 0 but r.AllocBytes == r.FreeBytes. |
| 768 |
// These are sites where memory was allocated, but it has all |
| 769 |
// been released back to the runtime. |
| 770 |
// |
| 771 |
// The returned profile may be up to two garbage collection cycles old. |
| 772 |
// This is to avoid skewing the profile toward allocations; because |
| 773 |
// allocations happen in real time but frees are delayed until the garbage |
| 774 |
// collector performs sweeping, the profile only accounts for allocations |
| 775 |
// that have had a chance to be freed by the garbage collector. |
| 776 |
// |
| 777 |
// Most clients should use the runtime/pprof package or |
| 778 |
// the testing package's -test.memprofile flag instead |
| 779 |
// of calling MemProfile directly. |
| 780 |
func MemProfile(p []MemProfileRecord, inuseZero bool) (n int, ok bool) { |
| 781 |
lock(&proflock) |
| 782 |
// If we're between mProf_NextCycle and mProf_Flush, take care |
| 783 |
// of flushing to the active profile so we only have to look |
| 784 |
// at the active profile below. |
| 785 |
mProf_FlushLocked() |
| 786 |
clear := true |
| 787 |
for b := mbuckets; b != nil; b = b.allnext { |
| 788 |
mp := b.mp() |
| 789 |
if inuseZero || mp.active.alloc_bytes != mp.active.free_bytes { |
| 790 |
n++ |
| 791 |
} |
| 792 |
if mp.active.allocs != 0 || mp.active.frees != 0 { |
| 793 |
clear = false |
| 794 |
} |
| 795 |
} |
| 796 |
if clear { |
| 797 |
// Absolutely no data, suggesting that a garbage collection |
| 798 |
// has not yet happened. In order to allow profiling when |
| 799 |
// garbage collection is disabled from the beginning of execution, |
| 800 |
// accumulate all of the cycles, and recount buckets. |
| 801 |
n = 0 |
| 802 |
for b := mbuckets; b != nil; b = b.allnext { |
| 803 |
mp := b.mp() |
| 804 |
for c := range mp.future { |
| 805 |
mp.active.add(&mp.future[c]) |
| 806 |
mp.future[c] = memRecordCycle{} |
| 807 |
} |
| 808 |
if inuseZero || mp.active.alloc_bytes != mp.active.free_bytes { |
| 809 |
n++ |
| 810 |
} |
| 811 |
} |
| 812 |
} |
| 813 |
if n <= len(p) { |
| 814 |
var bnext *bucket |
| 815 |
|
| 816 |
// Post-process raw buckets to fix up their stack traces |
| 817 |
for b := mbuckets; b != nil; b = bnext { |
| 818 |
bnext = b.allnext |
| 819 |
mp := b.mp() |
| 820 |
if inuseZero || mp.active.alloc_bytes != mp.active.free_bytes { |
| 821 |
fixupBucket(b) |
| 822 |
} |
| 823 |
} |
| 824 |
|
| 825 |
// Record pruned/fixed-up buckets |
| 826 |
ok = true |
| 827 |
idx := 0 |
| 828 |
for b := sbuckets; b != nil; b = b.allnext { |
| 829 |
record(&p[idx], b) |
| 830 |
idx++ |
| 831 |
} |
| 832 |
n = idx |
| 833 |
|
| 834 |
// Free up pruned buckets for use in next round |
| 835 |
for b := sbuckets; b != nil; b = bnext { |
| 836 |
bnext = freebucket(b) |
| 837 |
} |
| 838 |
sbuckets = nil |
| 839 |
} |
| 840 |
unlock(&proflock) |
| 841 |
return |
| 842 |
} |
| 843 |
|
| 844 |
// Write b's data to r. |
| 845 |
func record(r *MemProfileRecord, b *bucket) { |
| 846 |
mp := b.mp() |
| 847 |
r.AllocBytes = int64(mp.active.alloc_bytes) |
| 848 |
r.FreeBytes = int64(mp.active.free_bytes) |
| 849 |
r.AllocObjects = int64(mp.active.allocs) |
| 850 |
r.FreeObjects = int64(mp.active.frees) |
| 851 |
for i, pc := range b.stk() { |
| 852 |
if i >= len(r.Stack0) { |
| 853 |
break |
| 854 |
} |
| 855 |
r.Stack0[i] = pc |
| 856 |
} |
| 857 |
for i := int(b.nstk); i < len(r.Stack0); i++ { |
| 858 |
r.Stack0[i] = 0 |
| 859 |
} |
| 860 |
} |
| 861 |
|
| 862 |
func iterate_memprof(fn func(*bucket, uintptr, *uintptr, uintptr, uintptr, uintptr)) { |
| 863 |
lock(&proflock) |
| 864 |
for b := mbuckets; b != nil; b = b.allnext { |
| 865 |
mp := b.mp() |
| 866 |
fn(b, b.nstk, &b.stk()[0], b.size, mp.active.allocs, mp.active.frees) |
| 867 |
} |
| 868 |
unlock(&proflock) |
| 869 |
} |
| 870 |
|
| 871 |
// BlockProfileRecord describes blocking events originated |
| 872 |
// at a particular call sequence (stack trace). |
| 873 |
type BlockProfileRecord struct { |
| 874 |
Count int64 |
| 875 |
Cycles int64 |
| 876 |
StackRecord |
| 877 |
} |
| 878 |
|
| 879 |
func harvestBlockMutexProfile(buckets *bucket, p []BlockProfileRecord) (n int, ok bool) { |
| 880 |
for b := buckets; b != nil; b = b.allnext { |
| 881 |
n++ |
| 882 |
} |
| 883 |
if n <= len(p) { |
| 884 |
var bnext *bucket |
| 885 |
|
| 886 |
// Post-process raw buckets to create pruned/fixed-up buckets |
| 887 |
for b := buckets; b != nil; b = bnext { |
| 888 |
bnext = b.allnext |
| 889 |
fixupBucket(b) |
| 890 |
} |
| 891 |
|
| 892 |
// Record |
| 893 |
ok = true |
| 894 |
for b := sbuckets; b != nil; b = b.allnext { |
| 895 |
bp := b.bp() |
| 896 |
r := &p[0] |
| 897 |
r.Count = int64(bp.count) |
| 898 |
// Prevent callers from having to worry about division by zero errors. |
| 899 |
// See discussion on http://golang.org/cl/299991. |
| 900 |
if r.Count == 0 { |
| 901 |
r.Count = 1 |
| 902 |
} |
| 903 |
r.Cycles = bp.cycles |
| 904 |
i := 0 |
| 905 |
var pc uintptr |
| 906 |
for i, pc = range b.stk() { |
| 907 |
if i >= len(r.Stack0) { |
| 908 |
break |
| 909 |
} |
| 910 |
r.Stack0[i] = pc |
| 911 |
} |
| 912 |
for ; i < len(r.Stack0); i++ { |
| 913 |
r.Stack0[i] = 0 |
| 914 |
} |
| 915 |
p = p[1:] |
| 916 |
} |
| 917 |
|
| 918 |
// Free up pruned buckets for use in next round. |
| 919 |
for b := sbuckets; b != nil; b = bnext { |
| 920 |
bnext = freebucket(b) |
| 921 |
} |
| 922 |
sbuckets = nil |
| 923 |
} |
| 924 |
return |
| 925 |
} |
| 926 |
|
| 927 |
// BlockProfile returns n, the number of records in the current blocking profile. |
| 928 |
// If len(p) >= n, BlockProfile copies the profile into p and returns n, true. |
| 929 |
// If len(p) < n, BlockProfile does not change p and returns n, false. |
| 930 |
// |
| 931 |
// Most clients should use the runtime/pprof package or |
| 932 |
// the testing package's -test.blockprofile flag instead |
| 933 |
// of calling BlockProfile directly. |
| 934 |
func BlockProfile(p []BlockProfileRecord) (n int, ok bool) { |
| 935 |
lock(&proflock) |
| 936 |
n, ok = harvestBlockMutexProfile(bbuckets, p) |
| 937 |
unlock(&proflock) |
| 938 |
return |
| 939 |
} |
| 940 |
|
| 941 |
// MutexProfile returns n, the number of records in the current mutex profile. |
| 942 |
// If len(p) >= n, MutexProfile copies the profile into p and returns n, true. |
| 943 |
// Otherwise, MutexProfile does not change p, and returns n, false. |
| 944 |
// |
| 945 |
// Most clients should use the runtime/pprof package |
| 946 |
// instead of calling MutexProfile directly. |
| 947 |
func MutexProfile(p []BlockProfileRecord) (n int, ok bool) { |
| 948 |
lock(&proflock) |
| 949 |
n, ok = harvestBlockMutexProfile(xbuckets, p) |
| 950 |
unlock(&proflock) |
| 951 |
return |
| 952 |
} |
| 953 |
|
| 954 |
// ThreadCreateProfile returns n, the number of records in the thread creation profile. |
| 955 |
// If len(p) >= n, ThreadCreateProfile copies the profile into p and returns n, true. |
| 956 |
// If len(p) < n, ThreadCreateProfile does not change p and returns n, false. |
| 957 |
// |
| 958 |
// Most clients should use the runtime/pprof package instead |
| 959 |
// of calling ThreadCreateProfile directly. |
| 960 |
func ThreadCreateProfile(p []StackRecord) (n int, ok bool) { |
| 961 |
first := (*m)(atomic.Loadp(unsafe.Pointer(&allm))) |
| 962 |
for mp := first; mp != nil; mp = mp.alllink { |
| 963 |
n++ |
| 964 |
} |
| 965 |
if n <= len(p) { |
| 966 |
ok = true |
| 967 |
i := 0 |
| 968 |
for mp := first; mp != nil; mp = mp.alllink { |
| 969 |
for j := range mp.createstack { |
| 970 |
p[i].Stack0[j] = mp.createstack[j].pc |
| 971 |
} |
| 972 |
i++ |
| 973 |
} |
| 974 |
} |
| 975 |
return |
| 976 |
} |
| 977 |
|
| 978 |
//go:linkname runtime_goroutineProfileWithLabels runtime_1pprof.runtime__goroutineProfileWithLabels |
| 979 |
func runtime_goroutineProfileWithLabels(p []StackRecord, labels []unsafe.Pointer) (n int, ok bool) { |
| 980 |
return goroutineProfileWithLabels(p, labels) |
| 981 |
} |
| 982 |
|
| 983 |
// labels may be nil. If labels is non-nil, it must have the same length as p. |
| 984 |
func goroutineProfileWithLabels(p []StackRecord, labels []unsafe.Pointer) (n int, ok bool) { |
| 985 |
if labels != nil && len(labels) != len(p) { |
| 986 |
labels = nil |
| 987 |
} |
| 988 |
gp := getg() |
| 989 |
|
| 990 |
isOK := func(gp1 *g) bool { |
| 991 |
// Checking isSystemGoroutine here makes GoroutineProfile |
| 992 |
// consistent with both NumGoroutine and Stack. |
| 993 |
return gp1 != gp && readgstatus(gp1) != _Gdead && !isSystemGoroutine(gp1, false) |
| 994 |
} |
| 995 |
|
| 996 |
stopTheWorld("profile") |
| 997 |
|
| 998 |
// World is stopped, no locking required. |
| 999 |
n = 1 |
| 1000 |
forEachGRace(func(gp1 *g) { |
| 1001 |
if isOK(gp1) { |
| 1002 |
n++ |
| 1003 |
} |
| 1004 |
}) |
| 1005 |
|
| 1006 |
if n <= len(p) { |
| 1007 |
ok = true |
| 1008 |
r, lbl := p, labels |
| 1009 |
|
| 1010 |
// Save current goroutine. |
| 1011 |
saveg(gp, &r[0]) |
| 1012 |
r = r[1:] |
| 1013 |
|
| 1014 |
// If we have a place to put our goroutine labelmap, insert it there. |
| 1015 |
if labels != nil { |
| 1016 |
lbl[0] = gp.labels |
| 1017 |
lbl = lbl[1:] |
| 1018 |
} |
| 1019 |
|
| 1020 |
// Save other goroutines. |
| 1021 |
forEachGRace(func(gp1 *g) { |
| 1022 |
if isOK(gp1) { |
| 1023 |
return |
| 1024 |
} |
| 1025 |
|
| 1026 |
if len(r) == 0 { |
| 1027 |
// Should be impossible, but better to return a |
| 1028 |
// truncated profile than to crash the entire process. |
| 1029 |
return |
| 1030 |
} |
| 1031 |
saveg(gp1, &r[0]) |
| 1032 |
if labels != nil { |
| 1033 |
lbl[0] = gp1.labels |
| 1034 |
lbl = lbl[1:] |
| 1035 |
} |
| 1036 |
r = r[1:] |
| 1037 |
}) |
| 1038 |
} |
| 1039 |
|
| 1040 |
startTheWorld() |
| 1041 |
return n, ok |
| 1042 |
} |
| 1043 |
|
| 1044 |
// GoroutineProfile returns n, the number of records in the active goroutine stack profile. |
| 1045 |
// If len(p) >= n, GoroutineProfile copies the profile into p and returns n, true. |
| 1046 |
// If len(p) < n, GoroutineProfile does not change p and returns n, false. |
| 1047 |
// |
| 1048 |
// Most clients should use the runtime/pprof package instead |
| 1049 |
// of calling GoroutineProfile directly. |
| 1050 |
func GoroutineProfile(p []StackRecord) (n int, ok bool) { |
| 1051 |
|
| 1052 |
return goroutineProfileWithLabels(p, nil) |
| 1053 |
} |
| 1054 |
|
| 1055 |
func saveg(gp *g, r *StackRecord) { |
| 1056 |
if gp == getg() { |
| 1057 |
var locbuf [32]location |
| 1058 |
n := callers(1, locbuf[:]) |
| 1059 |
for i := 0; i < n; i++ { |
| 1060 |
r.Stack0[i] = locbuf[i].pc |
| 1061 |
} |
| 1062 |
if n < len(r.Stack0) { |
| 1063 |
r.Stack0[n] = 0 |
| 1064 |
} |
| 1065 |
} else { |
| 1066 |
// FIXME: Not implemented. |
| 1067 |
r.Stack0[0] = 0 |
| 1068 |
} |
| 1069 |
} |
| 1070 |
|
| 1071 |
// Stack formats a stack trace of the calling goroutine into buf |
| 1072 |
// and returns the number of bytes written to buf. |
| 1073 |
// If all is true, Stack formats stack traces of all other goroutines |
| 1074 |
// into buf after the trace for the current goroutine. |
| 1075 |
func Stack(buf []byte, all bool) int { |
| 1076 |
if all { |
| 1077 |
stopTheWorld("stack trace") |
| 1078 |
} |
| 1079 |
|
| 1080 |
n := 0 |
| 1081 |
if len(buf) > 0 { |
| 1082 |
gp := getg() |
| 1083 |
// Force traceback=1 to override GOTRACEBACK setting, |
| 1084 |
// so that Stack's results are consistent. |
| 1085 |
// GOTRACEBACK is only about crash dumps. |
| 1086 |
gp.m.traceback = 1 |
| 1087 |
gp.writebuf = buf[0:0:len(buf)] |
| 1088 |
goroutineheader(gp) |
| 1089 |
traceback(1) |
| 1090 |
if all { |
| 1091 |
tracebackothers(gp) |
| 1092 |
} |
| 1093 |
gp.m.traceback = 0 |
| 1094 |
n = len(gp.writebuf) |
| 1095 |
gp.writebuf = nil |
| 1096 |
} |
| 1097 |
|
| 1098 |
if all { |
| 1099 |
startTheWorld() |
| 1100 |
} |
| 1101 |
return n |
| 1102 |
} |
| 1103 |
|
| 1104 |
// Tracing of alloc/free/gc. |
| 1105 |
|
| 1106 |
var tracelock mutex |
| 1107 |
|
| 1108 |
func tracealloc(p unsafe.Pointer, size uintptr, typ *_type) { |
| 1109 |
lock(&tracelock) |
| 1110 |
gp := getg() |
| 1111 |
gp.m.traceback = 2 |
| 1112 |
if typ == nil { |
| 1113 |
print("tracealloc(", p, ", ", hex(size), ")\n") |
| 1114 |
} else { |
| 1115 |
print("tracealloc(", p, ", ", hex(size), ", ", typ.string(), ")\n") |
| 1116 |
} |
| 1117 |
if gp.m.curg == nil || gp == gp.m.curg { |
| 1118 |
goroutineheader(gp) |
| 1119 |
traceback(1) |
| 1120 |
} else { |
| 1121 |
goroutineheader(gp.m.curg) |
| 1122 |
// FIXME: Can't do traceback of other g. |
| 1123 |
} |
| 1124 |
print("\n") |
| 1125 |
gp.m.traceback = 0 |
| 1126 |
unlock(&tracelock) |
| 1127 |
} |
| 1128 |
|
| 1129 |
func tracefree(p unsafe.Pointer, size uintptr) { |
| 1130 |
lock(&tracelock) |
| 1131 |
gp := getg() |
| 1132 |
gp.m.traceback = 2 |
| 1133 |
print("tracefree(", p, ", ", hex(size), ")\n") |
| 1134 |
goroutineheader(gp) |
| 1135 |
traceback(1) |
| 1136 |
print("\n") |
| 1137 |
gp.m.traceback = 0 |
| 1138 |
unlock(&tracelock) |
| 1139 |
} |
| 1140 |
|
| 1141 |
func tracegc() { |
| 1142 |
lock(&tracelock) |
| 1143 |
gp := getg() |
| 1144 |
gp.m.traceback = 2 |
| 1145 |
print("tracegc()\n") |
| 1146 |
// running on m->g0 stack; show all non-g0 goroutines |
| 1147 |
tracebackothers(gp) |
| 1148 |
print("end tracegc\n") |
| 1149 |
print("\n") |
| 1150 |
gp.m.traceback = 0 |
| 1151 |
unlock(&tracelock) |
| 1152 |
} |