读源码时我们常犯一个毛病:一个函数一个函数地抠,每个都懂,可它们到底怎么串起来、数据从哪来到哪去,脑子里还是一张散图。因为你记的是"有哪些零件",不是"零件装在哪条轴上"。
这篇不打算再分站讲解。这是跟拍------挑一行最普通的代码,跟着它从发生的那一刻一路走到落地。
go
pprof.Lookup("heap").WriteTo(w, 0)
就这一行。跟着它跑一趟,你会走遍这条流水线上的关键工位:查表、分流、两段式捞数、debug 扳道、贴签、漏斗去重、PC 翻 ID(内联折叠)、缩放、protobuf 封包(起点 + 八站)。先打个预防针 :主角 heap 的 debug=0 并不走满全部九站------它不带 g.labels、也不进通用漏斗,第 4、5 站是别的窗口(goroutine、自定义窗口)走的路;我会在那两站明说"主角不在此,绕路看一眼"。所以这一趟是"带着主角把每站都认一遍",不是"主角亲自走完每一站"。读到终点我还给你一张表,哪种导出实际走了哪几站。读完你不用记"runtime/pprof 有哪些机制",只需记一件事:"我"这行代码,从头到尾经历了什么。
每讲一站,我都会先报一句"我在哪",让你随时知道走到了流水线的哪个位置。零件归位,整体就通了。
先跑一遍:把主演请上台
光看一行不过瘾,我们把它补成一份能直接跑的程序。存成 main.go,go run main.go 就能看到每种导出的真实开头。
go
package main
import (
"bytes"
"context"
"fmt"
"runtime"
"runtime/pprof"
"strings"
)
type fd struct{ name string }
func firstLine(b []byte) string {
s := strings.TrimSpace(string(b))
if i := strings.IndexByte(s, '\n'); i >= 0 {
return s[:i]
}
return s
}
var openFiles = pprof.NewProfile("lab.openFiles") // 自定义窗口
func main() {
// 查表:内置窗口在册,CPU 不在
fmt.Println("lookup heap != nil:", pprof.Lookup("heap") != nil)
fmt.Println("lookup cpu != nil:", pprof.Lookup("cpu") != nil)
// 造点堆分配,让 heap 有内容
var sink [][]byte
for i := 0; i < 200; i++ {
sink = append(sink, make([]byte, 64*1024))
}
runtime.KeepAlive(sink)
// 自定义窗口:登记一笔、导出、注销
f := &fd{"a.txt"}
openFiles.Add(f, 0)
fmt.Println("custom count after Add:", openFiles.Count())
var cb bytes.Buffer
_ = openFiles.WriteTo(&cb, 1)
fmt.Println("custom debug=1 head:", firstLine(cb.Bytes()))
openFiles.Remove(f)
fmt.Println("custom count after Remove:", openFiles.Count())
// 内置窗口的 Add / Remove 差异
func() {
defer func() {
if r := recover(); r != nil {
fmt.Println("builtin heap Add -> panic")
}
}()
pprof.Lookup("heap").Add("x", 0)
}()
pprof.Lookup("heap").Remove("x")
fmt.Println("builtin heap Remove -> no panic")
// 主角:heap 的两种出口
var ht, hp bytes.Buffer
_ = pprof.Lookup("heap").WriteTo(&ht, 1)
_ = pprof.Lookup("heap").WriteTo(&hp, 0)
fmt.Println("heap debug=1 head:", firstLine(ht.Bytes()))
fmt.Printf("heap debug=0 first bytes: % x (gzip=1f8b)\n", hp.Bytes()[:2])
fmt.Println("heap debug=1 has MemStats:", bytes.Contains(ht.Bytes(), []byte("runtime.MemStats")))
fmt.Println("heap debug=0 has MemStats:", bytes.Contains(hp.Bytes(), []byte("runtime.MemStats")))
fmt.Println("heap debug=1 bytes:", ht.Len(), " debug=0 bytes:", hp.Len())
// goroutine:漏斗 vs 全文本短路
var g1, g2 bytes.Buffer
_ = pprof.Lookup("goroutine").WriteTo(&g1, 1)
_ = pprof.Lookup("goroutine").WriteTo(&g2, 2)
fmt.Println("goroutine debug=1 head:", firstLine(g1.Bytes()))
fmt.Println("goroutine debug=2 head:", firstLine(g2.Bytes()))
fmt.Println("goroutine debug=1 bytes:", g1.Len(), " debug=2 bytes:", g2.Len())
// block / mutex 文本头
var bb, mb bytes.Buffer
runtime.SetBlockProfileRate(1)
runtime.SetMutexProfileFraction(1)
_ = pprof.Lookup("block").WriteTo(&bb, 1)
_ = pprof.Lookup("mutex").WriteTo(&mb, 1)
fmt.Println("block debug=1 head:", firstLine(bb.Bytes()))
fmt.Println("mutex debug=1 head:", firstLine(mb.Bytes()))
// 标签覆盖
ctx := pprof.WithLabels(context.Background(),
pprof.Labels("route", "/old", "env", "prod", "route", "/final"))
route, ok := pprof.Label(ctx, "route")
fmt.Println("label route:", route, ok)
var pairs []string
pprof.ForLabels(ctx, func(k, v string) bool {
pairs = append(pairs, k+"="+v)
return true
})
fmt.Println("for labels:", strings.Join(pairs, ","))
}
实测结果(文中所有数字都来自这份程序在 go1.24.0 上的真实输出):
text
lookup heap != nil: true
lookup cpu != nil: false
custom count after Add: 1
custom debug=1 head: lab.openFiles profile: total 1
custom count after Remove: 0
builtin heap Add -> panic
builtin heap Remove -> no panic
heap debug=1 head: heap profile: 12: 659456 [12: 659457] @ heap/1048576
heap debug=0 first bytes: 1f 8b (gzip=1f8b)
heap debug=1 has MemStats: true
heap debug=0 has MemStats: false
heap debug=1 bytes: 3313 debug=0 bytes: 2216
goroutine debug=1 head: goroutine profile: total 1
goroutine debug=2 head: goroutine 1 [running]:
goroutine debug=1 bytes: 550 debug=2 bytes: 478
block debug=1 head: --- contention:
mutex debug=1 head: --- mutex:
label route: /final true
for labels: env=prod,route=/final
把这份程序放在手边,下面每讲一站,你都能回到这里找到对应的那行。先说清楚怎么读这张表 :魔数、格式、total/has/没 panic 这些是稳定的,照着跑一定一样;但 heap profile: 那行的对象数和字节数(12: 659456)、各路 bytes 计数是运行时快照,你跑出来必然是不同的数 ------分配多少、GC 到哪一轮都随运行波动,连多跑一遍都不重样。所以别拿具体数字对答案,要看的是结构。真正要解释的两个不变特征:heap/1048576 里的 1048576 恒等于 2×524288(文本头故意报两倍采样率),[...: 659457] 总比前面 659456 多 1 字节------这 1 字节是故意造的防误判暗号。
先看全程地图
这一趟一共九站。第一站到第三站是"请求怎么找到数据",第四到第六站是"数据怎么被整理",第七第八站是"怎么变成文件",终点是"工具怎么读回来"。
text
pprof.Lookup(name).WriteTo(w, debug)
│
【起点】查表 ────────────────────► profiles.m[name] → 一张 Profile 工单
│
第 1 站 分流 ────────────────────► p.write 空不空?
│ 非空→内置专属函数 / 空→通用漏斗
第 2 站 捞数 ────────────────────► 两段式:fetch(nil) 问条数 → 分配 n+余量 → 实取
│ (CPU 不走这里:它是录像,后台泵流式写)
第 3 站 扳道 ────────────────────► debug 决定出口:
│ heap: =0 proto / >0 文本+MemStats
│ goroutine: >=2 全文本短路 / 否则漏斗
│ block/mutex: <=0 两列 proto / >0 文本
第 4 站 贴签 ────────────────────► g.labels → profBuf.tags / labels[i] → sample.Label
│
第 5 站 去重 ────────────────────► 压 PC 指纹 → 计数 → 排序(通用漏斗 printCountProfile)
│
第 6 站 翻译 ────────────────────► 一串 PC → location ID(内联折成多 Line)
│
第 7 站 缩放 ────────────────────► 泊松补偿 / cycles→ns / 文本头两谎言 / MemStats
│
第 8 站 封包 ────────────────────► pbSample → startMessage/endMessage → b.build() → gzip
│
【终点】火焰图 ◄────────────────── 工具两跳查回:Sample → Location → Function

跟着这一行代码走一趟:请求怎么找到数据、数据怎么被整理、怎么变成文件,最后工具怎么读回来。
记住这张图。往后每站开头我都告诉你"我在哪一站",你随时能定位。
起点:一张工单从哪来
我在哪 :pprof.Lookup("heap") 这一句,还没到 WriteTo。
Lookup(pprof.go:271)做的第一件事是上锁查全局表 profiles.m,查不到就返回 nil------这就是实测里 lookup cpu != nil: false 的原因:CPU 压根没登记在这张表里 。它是流式的,走 StartCPUProfile / StopCPUProfile 专属 API,硬塞进"查一次出一份文件"的窗口模型不合适。
第一次查表会触发懒初始化,把六个内置窗口填进去(pprof.go:192-226)。它们都是同一个 Profile 结构:
go
type Profile struct { // pprof.go:178
name string
mu sync.Mutex
m map[any][]uintptr // 自定义窗口的"值 → 栈"表
count func() int // 内置窗口:去哪数条数
write func(io.Writer, int) error // 内置窗口:去哪写文件
}
五个字段,真正决定命运的是 count / write 两个函数指针空不空。六个内置窗口把它们填好:
go
var heapProfile = &Profile{
name: "heap",
count: countHeap, // → runtime.MemProfile(nil, true)
write: writeHeap, // → writeHeapInternal(w, debug, "")
}
var allocsProfile = &Profile{
name: "allocs",
count: countHeap, // ← 和 heap 共用
write: writeAlloc, // → writeHeapInternal(w, debug, "alloc_space")
}
两个细节先钉住:
- heap 和 allocs 是同一批数据 ,共用
countHeap,writeAlloc只比writeHeap多传一个"alloc_space",差别在默认视图,不用抓两遍。 - CPU 不在这张表里,前面说过。
这一站做了什么 :把字符串 "heap" 翻译成一张带 write 指针的工单。下一站,这个指针就要派上用场。
第 1 站 分流:门口那一刀
我在哪 :WriteTo,pprof.go:372。
go
func (p *Profile) WriteTo(w io.Writer, debug int) error {
if p.name == "" {
panic("pprof: use of zero Profile") // ← 374
}
if p.write != nil {
return p.write(w, debug) // ← 377:内置窗口到此转包
}
// ...下面是自定义窗口的路
}
从哪个函数进去 :WriteTo 开门见山。377 行那一刀,把世界劈成两半:
- 内置窗口 (
p.write != nil):heap→writeHeap、goroutine→writeGoroutine、block→writeBlock......各有专属写函数。主角heap走这条,后面那二十行的快照、排序、漏斗一行都不执行。 - 自定义窗口 (
p.write == nil):NewProfile建窗口时只填name和m(pprof.go:264),两个函数指针故意留空,于是往下走到通用漏斗。
这一站顺路把自定义窗口的半条命看清楚------实测程序开头那段就是它:
go
var openFiles = pprof.NewProfile("lab.openFiles")
openFiles.Add(f, 0) // 登记:抓当前栈(32 帧)存进 m[value]
openFiles.Count() // 数账本:内置窗口问 p.count(),自定义窗口 len(p.m)
openFiles.Remove(f) // 注销:delete(p.m, value)
openFiles.WriteTo(&b, 1) // 导出:走通用漏斗
m 是 map[any][]uintptr------"值 → 调用栈"的表。打开文件 Add 登记,关闭 Remove 划掉,忘了划掉的那行永远留在 profile 里,自然成了一份泄漏清单。这里有个文档和源码打架的地方,实测已经跑出来了:builtin heap Add -> panic,但 builtin heap Remove -> no panic。包文档说 Add/Remove 对内置窗口都 panic,可 1.24 的实现里 Remove 只是 delete(p.m, value),内置窗口的 m 是 nil,对 nil map 做 delete 是合法的 no-op------文档是线索,不是终审判决。
这一站做了什么 :heap 这行代码在 377 行被转包给 writeHeap 了。它没进漏斗。带着这个认知往下走------后面几站全是 writeHeap 内部的事。
第 2 站 捞数:先问条数,再多退一点
我在哪 :writeHeap → writeHeapInternal,pprof.go:592 / 602。
主角进了专属写函数。writeHeap 只是个三行的门面,真正的主角是 writeHeapInternal。它上来先干一件看似啰嗦的事------两段式捞数:
go
var memStats *runtime.MemStats
if debug != 0 {
memStats = new(runtime.MemStats) // ← 607:文本模式才读
runtime.ReadMemStats(memStats) // ← 608
}
var p []profilerecord.MemProfileRecord
n, ok := pprof_memProfileInternal(nil, true) // ← 619:第一段,只问条数
for {
p = make([]profilerecord.MemProfileRecord, n+50) // ← 624:多留 50 条
n, ok = pprof_memProfileInternal(p, true) // ← 625:第二段,实取
if ok {
p = p[0:n]
break
}
// 期间又冒出新记录,拿新的 n 重来
}
为什么两段式 :runtime 侧那排 *Internal 函数有个契约------"给的切片装不下,就一个字都不写,只如实告诉你真实条数 n"。写侧于是敢先 fetch(nil) 白问一次,再按 n+50 分配。从"问 n"到"真取",程序还在跑、heap 可能又长出新桶,+50 兜住这点增长,万一还是不够(局气不好),拿新的 n 重来。n 和 size 的单位都是条 ,不是字节------这是 runtime 侧那排 *Internal 函数统一的尺子,后面读到导出代码时还会再遇到它。
那一堆 pprof_*(pprof.go:977-999)是 8 条 linkname 声明 ,不是 7 条。它们绕开三件事:internal/profilerecord 的切片过不了导出 ABI、导出的栈数组只有 32 帧而后门拿到的是完整栈、runtime 直接写进调用方切片少一次复制。这一后门是理解了两条导出路径后才看得清的。
CPU 不在这站 :它是录像,不两段式。主角是"问一次捞一批",CPU 是"开一次信号、后台泵每 100ms 搬一段、StopCPUProfile 等最后一箱搬完":
go
func StartCPUProfile(w io.Writer) error { // ← 833
const hz = 100 // 硬编码 100Hz
runtime.SetCPUProfileRate(hz) // ← 855:开
go profileWriter(w) // ← 856:起后台泵
return nil // 立刻返回
}
func profileWriter(w io.Writer) { // ← 867
for {
time.Sleep(100 * time.Millisecond) // ← 871
data, tags, eof := readProfile() // 搬一段
b.addCPUData(data, tags) // 按 (栈, tag) 去重
if eof { break }
}
b.build() // 封包
cpu.done <- true // 发收工回执
}
func StopCPUProfile() { // ← 892
runtime.SetCPUProfileRate(0) // 关
<-cpu.done // ← 901:等泵写完
}
两个 100 不是一回事:100Hz 是采样频率(约每 10ms 一个样本),100ms 是泵的搬运周期。<-cpu.done 不能删------关信号只是停产,账本里还压着没搬完的;不等它,调用方的 defer f.Close() 会抢在泵前面关文件,gzip 包就坏了。

先白问一次条数,再多留 50 个位置去取------runtime 那排函数就是这么"先量后装"的。
这一站做了什么 :把 runtime 账本里的记录,捞成写侧手里的一批 MemProfileRecord。下一站,debug 要决定这批数据往哪个出口走。
第 3 站 扳道:debug 不是刻度,是岔道开关
我在哪 :writeHeapInternal 的出口判断,pprof.go:634。
很多人以为 debug 是"详细程度"的连续刻度------0 简略、1 详细、2 更详细。错。它是扳道器,切的是数据种类。同一份数据,不同 debug 拿到的是不同产物。
主角 debug=0,在 634 行直接转去 proto:
go
if debug == 0 {
return writeHeapProto(w, p, int64(runtime.MemProfileRate), defaultSampleType) // ← 634
}
// 下面全是 debug > 0 的文本路径
实测把这道扳道看得清清楚楚:
text
heap debug=1 head: heap profile: 12: 659456 [12: 659457] @ heap/1048576
heap debug=0 first bytes: 1f 8b (gzip=1f8b)
heap debug=1 has MemStats: true
heap debug=0 has MemStats: false
heap debug=1 bytes: 3313 debug=0 bytes: 2216
debug=1 是人读文本,带一整屏 runtime.MemStats;debug=0 是 gzip protobuf(魔数 1f 8b),一个 MemStats 字都没有。proto 路径干净得不像话------排序、文本头、MemStats 全是 debug>0 的事,一点不污染 proto 数字。
三种窗口,三套扳道规则,别记串:
| 窗口 | debug == 0 |
debug > 0 |
特殊档 |
|---|---|---|---|
| heap / allocs | writeHeapProto 四列 proto |
文本头 + MemStats | --- |
| goroutine | 漏斗 → proto | 漏斗 → 文本 | debug >= 2 短路到全文本 |
| threadcreate | 漏斗 → proto | 漏斗 → 文本 | ---(它直接转 writeRuntimeProfile,没有全文本分支) |
| block / mutex | 两列 proto(contentions/delay,含 cycles→ns 换算) |
文本(原始 cycles,不换算) | --- |
这里必须拆开讲:debug >= 2 的短路是 writeGoroutine 独有的 (pprof.go:751-755),源码里只有它先判 debug >= 2 再转 writeGoroutineStacks;threadcreate 的 writeThreadCreate(736 行)没有这道判断,直接把请求交给 writeRuntimeProfile------它不管 debug 多大都走漏斗。把两者并成一行说"都能短路到全文本"是错的。
另外留意 proto/文本的判定边界有三种写法,别记串:block/mutex 用 debug <= 0 走 proto (pprof.go:943),通用漏斗 printCountProfile 用 debug > 0 才写文本、否则写 proto (491 行)------这两者在"debug<=0 走 proto"上其实一致 。真正特殊的是 heap/allocs:它用 debug == 0 单独判定 proto(writeHeapInternal:634),传负数反而落进文本路径。

debug 不是"详细到什么程度",它是岔道开关:换个值,同一份数据走的是不同产物。
goroutine 那档 debug >= 2 走的是另一条路:它短路到 writeGoroutineStacks(w),用 runtime.Stack(buf, true) 抓 panic 同款全文本,逐 g 罗列、带 goid 和阻塞状态、全程 STW、64MB 封顶可截断。实测里 debug=2 的开头是 goroutine 1 [running]:,debug=1 的开头是 goroutine profile: total 1------一个是人读现场,一个是给工具的计数样本。
文本路径的两个善意谎言 (走到 debug=1 才看得到):
go
rate := 2 * runtime.MemProfileRate // ← 657:文本头报两倍
if inUseBytes == allocBytes {
allocBytes++ // ← 668:故意制造 1 字节差异
}
实测那行 heap profile: 12: 659456 [12: 659457] @ heap/1048576 全对上了:1048576 = 2×524288(默认 MemProfileRate=512KB=524288,报两倍是给老工具的礼貌值);659457 是 659456+1,故意让 alloc 和 inuse 不相等,避免老 pprof 误判成"两列 profile"。proto 路径用 Period=rate 的准确值,因为要拿真值算泊松补偿------这正是下一站要讲的那笔账。
这一站做了什么 :debug=0 把主角送进 writeHeapProto。但为了让这一趟覆盖全部工位,下一站我们绕去看"标签是怎么混进样本的"------它是所有窗口共用的一个维度。
第 4 站 贴签:标签不跟采样走,跟人走
我在哪:一条业务的"身份维度",怎么进到 profile 样本里。
pprof labels 要解决的问题:同一进程跑很多种请求,火焰图能不能按 route、tenant 重新聚合?难处是 CPU 采样发生在信号处理器里,那一刻手上没 ctx,只有一个被打断的 g。于是思路反过来------不是采样时找标签,是开工前把标签贴到人(goroutine)背上。
先看实测里的标签行为:
text
label route: /final true
for labels: env=prod,route=/final
WithLabels(ctx, Labels("route","/old","env","prod","route","/final")) 里 route 写了两次,最终是 /final(后值覆盖前值),ForLabels 按键升序吐出 env 在前、route 在后。这两条行为都来自 label.go 的"有序、不可变、双指针归并":
go
func WithLabels(ctx context.Context, labels LabelSet) context.Context {
parentLabels := labelValue(ctx)
return context.WithValue(ctx, labelContextKey{},
&labelMap{mergeLabelSets(parentLabels.LabelSet, labels)}) // ← 62
}
// mergeLabelSets 同 key 时:result = append(result, right.list[r]) ← 83:新压旧
名字骗了不少人:labelMap 底层是 []label 切片,不是 map。用切片是为了保序、按 key 归并去重------指纹要稳定,标签顺序就不能乱。
真正把标签钉到 g 身上的是 Do(runtime.go:47):
go
func Do(ctx context.Context, labels LabelSet, f func(context.Context)) {
defer SetGoroutineLabels(ctx) // ← 48:此刻就捕获了父 ctx!
ctx = WithLabels(ctx, labels)
SetGoroutineLabels(ctx) // 贴新的
f(ctx) // 这段时间被采样就带标签
} // 返回时 defer 把父标签贴回去
defer 的位置是正确性不是风格:Go 写到 defer 那行就求好了参数值,48 行捕获的是父 ctx,49 行才换子 ctx。挪到 49 行之后,还原就等于没还原。
有个曾经讲错过的地方值得钉死:这里不是 写屏障让 GC 看见 g.labels。runtime_setProfLabel 只建 race 同步(labelSync)再直接赋值;GC 安全来自两点------g.labels 是 g 结构里的可达指针,采样时抄进的是堆上分配 的 profBuf.tags,会被 GC 扫描。信号处理器里跑不了写屏障。

标签不跟采样走,跟人走------开工前贴到 g 背上;真正消费它的只有 CPU 和 goroutine 两条路。
谁真的带标签? 这是数据流的真实边界:
text
路 A:CPU
sigprof → cpuProfile.add(&g.labels, stk) → profBuf.tags
→ readProfile 返回 data + tags → addCPUData 用 (栈, tag) 去重 → pbLabel
路 B:goroutine(debug < 2)
pprof_goroutineProfileWithLabels → labels[i] = gp.labels
→ runtimeProfile.Label(i) → printCountProfile 的 labels 回调 → pbLabel
threadcreate 明确把 labels 参数写成 _(issue 6104 没解决,拿不到像样的栈);block / mutex 走无标签的两列 proto;自定义窗口的 stackProfile.Label(i) 恒返回 nil。所以包文档那句"目前只有 CPU 和 goroutine 消费 labels",是真的数据流边界,不是随口说的。
这一站做了什么 :搞清楚标签这条线只挂在 CPU 和 goroutine 两棵树上。主角 heap 这条路不带 pprof 标签------但它的样本里也有个 bytes 数值标签(第 7 站会讲),别和这套 g.labels 混了。
第 5 站 去重:一个漏斗,三招接口
我在哪 :通用漏斗 printCountProfile,pprof.go:461。主角 heap 不进这里,但 goroutine(debug=1)、threadcreate、自定义窗口都进,CPU 的 addCPUData 是它的近亲。这一站是把前面"贴签"和后面"翻译"串起来的枢纽。
漏斗能接收异构数据,靠一个只有三招的接口:
go
type countProfile interface { // ← 404
Len() int
Stack(i int) []uintptr
Label(i int) *labelMap
}
stackProfile(自定义窗口的 [][]uintptr)、runtimeProfile(goroutine 的 StackRecord + labels)各实现这三招,就能进同一个漏斗。Label(i) 那招正是上一站标签接进来的地方------runtimeProfile.Label(i) 把裸指针转回 *labelMap。

异构数据靠三招接口进同一个漏斗;100 个 g 卡在同一行,压成一条、count=100。
漏斗自己不输出,先干一件核心的事------指纹去重:
go
key := func(stk []uintptr, lbls *labelMap) string { // ← 464
buf.Reset()
fmt.Fprintf(&buf, "@")
for _, pc := range stk { fmt.Fprintf(&buf, " %#x", pc) } // PC 序列
if lbls != nil { // 有标签再挂一行
buf.WriteString("\n# labels: ")
buf.WriteString(lbls.String())
}
return buf.String()
}
count := map[string]int{}; index := map[string]int{}; var keys []string
for i := 0; i < p.Len(); i++ {
k := key(p.Stack(i), p.Label(i))
if count[k] == 0 { index[k] = i; keys = append(keys, k) }
count[k]++
}
sort.Sort(&keysByCount{keys, count}) // ← 489:次数降序,平手按 key 字典序
三个容器分工清楚:count 管次数、index 记住"回头去哪取栈"、keys 管输出顺序。100 个 goroutine 卡同一行,压成一条、count=100------这就是实测里 goroutine profile: total 1 的由来:程序里只剩 main,一条样本。标签进了指纹,所以同名函数、不同标签会分开计数。
排序之后才按 debug 分两个龙头:debug>0 写 tabwriter 文本(printStackRecord 把 PC 翻成函数+文件+行号),debug=0 写 protobuf(每条不同栈变成一个 Sample)。
打印前的隐藏工序 :expandInlinedFrames(pprof.go:413)用 runtime.CallersFrames 把 PC 展开成逻辑帧,并把 call PC 统一改成 return PC(dst[n] = f.PC + 1)------因为后面的消费者期望 return PC。注意它和 proto.go 里那套 expandFinalInlineFrame 不是一回事,后者是给 protobuf 的 location 表补内联尾帧的------名字像,干的不是一件事。
这一站做了什么:把一堆散样本压成"不同栈 + 次数"的清单,并按 debug 分岔。走 proto 的那些样本,下一步要把 PC 翻译成 location ID------那是全程最难的一站。
第 6 站 翻译:一串 PC 怎么变成 location ID
我在哪 :protobuf 编码器 appendLocsForStack,proto.go:403。这是整个 runtime/pprof 里最容易绕晕的一段,我们慢慢拆。
protobuf 里 Sample 不直接存 PC,存的是一串 location ID;每个 location 装"函数 + 文件 + 行号"。所以写 Sample 前得先把栈的 PC 翻成 ID。难在 Go 有内联------一个 PC 可能对应多层函数。
text
Sample.location = [7] ← pbSample 写进 protobuf
│ 一个 id 定位一个 Location
▼
Location #7 ← tagLocation_ID = 7
Address = 叶子 PC
Line ×3: funcID=2 / 3 / 4 ← 每条 Line 一个内联层
│ 每条 Line 的 funcID 再查一次
▼
Function 表: 2→main.a 3→main.b 4→main.main

Sample 里只存 ID,一个 ID 查到 Location,每条 Line 再查 Function------内联的一层函数调用就藏在这条链里。
开头两件事 :复位牌桌 b.deck.reset();stk = runtime_expandFinalInlineFrame(stk) 补全被栈深截断的最后一帧内联层。
主循环逐 PC:
- 命中缓存 (
b.locs[addr]):不能直接拿 ID 就走------要先做 fake PC 试探。tryAdd判断这个地址是不是当前内联链的延续:是就并进 deck、只跳 1 个 PC;不是就先emitLocation冲出 deck、记缓存 ID、整串跳过len(l.pcs)个。为什么这么绕?因为编译器内联会在外层函数插 NOP 当占位,runtime 生成的 "fake PC" 在一条栈里是独立叶子、在另一条栈里可能只是内联链中间层,缓存按地址索引记不住"这次它演什么角色"。 - 没命中 :
allFrames(addr)用runtime.CallersFrames把这个 PC 展开成一串Frame(一个 PC 展开成多帧 = 内联的那几层),deck.tryAdd试着并进当前牌桌。
tryAdd 的四个否决条件 (proto.go:552):只跟牌桌末尾那帧 比------①末尾是实体函数(Func != nil)→ 链到头;②Entry 为 0(非 Go 函数)→ 否决;③Entry 不同 → 不是同一函数;④函数名相同 → 疑似递归。四个都过,才确认"同一条内联链的延续层"。源码明说用了启发式------runtime 不直接暴露"是不是内联",这套判据是推断不是事实。
鸡蛋里挑骨头:第一条查的是 last(牌桌末尾帧)不是 newFrame(新来的帧)。源码的语义是"末尾帧得还是内联帧(Func == nil)才接得上"------Func 字段对完全内联的函数就是 nil(symtab.go:38)。所以判断键在 last;写成 newFrame.Func != nil 会把方向搞反。源码自己给的例子(proto.go:486-505)是 main→b→a 三层内联:前三次 tryAdd 依次把 a、b、main 并进 deck,第四次轮到 main.main 的调用者 时,因为 main.main 没有内联进它的调用者(那是一帧实体函数),last.Func != nil 命中否决、deck 结算,那个调用者另起一个 location。
顺路一个质量标记 :symbolizeResult 跟内联无关,它是 allFrames 符号化成功与否的 2 位标志(lookupTried / lookupFailed)。整条链按位或累积------一处失败则整体失败;最后经 emitLocation 汇进 memMap.funcs,build() 里 hasFunctions := m.funcs == lookupTried 才给模块写 HasFunctions=true。宁缺毋滥:一个函数符号化失败,整个模块的函数名都标成不可信。
emitLocation 不判定内联,只做编码合并:把 deck 里已确认同链的 N 帧写成一个 Location 的 N 条 Line:
go
b.pb.uint64Opt(tagLocation_ID, id)
b.pb.uint64Opt(tagLocation_Address, uint64(firstFrame.PC)) // 只写叶子 PC
for _, frame := range b.deck.frames {
funcID := ... // 按函数名去重,新函数攒进 newFuncs 延后写
b.pbLine(tagLocation_Line, funcID, int64(frame.Line)) // ← 在 if 外,每帧都写
}
三个坑:缓存整条链要深拷贝 (append([]uintptr{}, b.deck.pcs...)),否则 defer deck.reset() 复用底层数组会把缓存覆盖;pbLine 在 if 外面,分配完 funcID 照样写;Address 写 firstFrame.PC 而非 addr(符号化失败时 allFrames 会把 frame.PC 改成 addr-1)。Function 消息得延后写------protobuf 流式编码时 Location 和 Function 是同级 repeated 字段,不能在写 Location 的过程中插 Function。
这一站做了什么:把一个带内联的调用栈,压成一个 Location + 多条 Line + Function 表,交给编码器落笔。下一站是数字准不准的问题。
第 7 站 缩放:每一列数字都得还一笔账
我在哪 :writeHeapProto 的四列和它的补偿,protomem.go:16。
主角 debug=0 走的是 proto,样本按栈指纹去重后,每条要填四个值:
go
b.pbValueType(tagProfile_PeriodType, "space", "bytes")
b.pb.int64Opt(tagProfile_Period, rate) // ← 19:准确值,不是 2×
b.pbValueType(tagProfile_SampleType, "alloc_objects", "count") // ①
b.pbValueType(tagProfile_SampleType, "alloc_space", "bytes") // ②
b.pbValueType(tagProfile_SampleType, "inuse_objects", "count") // ③
b.pbValueType(tagProfile_SampleType, "inuse_space", "bytes") // ④
四个 pbValueType 就是 go tool pprof -sample_index 能切列的依据。heap 和 allocs 唯一的差异是 defaultSampleType:allocs 传 "alloc_space",于是默认视图不同,数据仍是同一份。
heap 的账要还 :它是抽样记账,累计分配字节跨过 R = MemProfileRate 才记一笔。大小 S 的一次分配至少被记一次的概率 p = 1-e^(-S/R)。我们只看得见被采中的样本,要还原期望总量就除以 p:
go
avgSize := float64(size) / float64(count)
scale := 1 / (1 - math.Exp(-avgSize/float64(rate))) // ← 91
| 场景 | S/R | p | scale | 直觉 |
|---|---|---|---|---|
| 大块 | 8 | 0.999665 | 1.0003 | 几乎必采,不用补 |
| 中块 | 1 | 0.632121 | 1.5820 | 六成被采,乘 1.58 |
| 小块 | 0.1 | 0.095161 | 10.5085 | 大多漏网,单个放大十倍 |
(这三个数是配套示例程序在 go1.24.0 上的实跑值:表格里的 S/R=0.1 是名义比值,程序里 size := int64(float64(rate)*ratio) 会把 524288×0.1 截成 52428,实际比值是 0.0999984741,所以 p 是 0.095161 而非拿精确 0.1 算出的 0.095163------差在这 1 字节的截断上。)
块越小漏得越多,系数越大。代码里还有个 bytes 数值标签,用的是未补偿 的平均块大小 AllocBytes/AllocObjects,和放大后的四列不是一回事。
block/mutex 欠的是另一种债:单位换算 (只发生在 debug=0 的 proto 路径,文本路径直接打原始 cycles)。runtime 记等待用 CPU tick(字段叫 Cycles),pprof 的 delay 列要纳秒:
go
cpuGHz := float64(pprof_cyclesPerSecond()) / 1e9 // ← 441
values[1] = int64(float64(r.Cycles) / cpuGHz) // ← 448
这里最容易读错数量级:cpuGHz 是"几"。源码里 pprof_cyclesPerSecond() 只是 return ticksPerSecond()(cpuprof.go:222)------这是 cputicks 时钟与 nanotime 时钟的换算率 (runtime.go:55),数值量级接近 CPU 主频(几乘以 1e9),但源码 TODO 明说它没考虑 CPU 频率缩放 ,所以严格讲不能和主频画等号;除以 1e9 后得个位数。漏掉 ÷cpuGHz 只是把 tick 当纳秒报出去、偏几倍;真正差十亿倍的是漏掉那个 /1e9、把 cyclesPerSecond 直接当 GHz 用。
别把两种除法混了 :scaleHeapSample 是统计补偿 (把漏采的量补回来),cycles ÷ GHz 是单位换算(tick 换纳秒)。长得像,欠的债完全不同。
debug>0 文本路径那一屏 MemStats 是哪来的 ?MemStats 自己不统计任何东西,它是张空表;数由 runtime 平时分散记在三本账里(分 P 的一致性账本、gcController 原子账、mstats 的 GC 字段),ReadMemStats 在 STW 下先结算 mcache、合并环形缓冲,再把累计量一减(Alloc = 总分配 − 总释放)、字段一填,抄成"调用这一刻"的快照。文本路径把它打出来给人看,pprof 工具其实忽略;proto 路径一行都不带。
这一站做了什么:把去重后的样本,按各自的采样模型把数字还原到可信量级。至此数据齐了,只差封包。
第 8 站 封包:先写内容,后补信封头
我在哪 :protobuf 构建器的落笔动作,proto.go + protobuf.go。
所有样本,不管来自主角 heap、来自漏斗、还是来自 CPU 后台泵,最后都交给同一个 profileBuilder,由 b.build() 统一补表、封包、gzip------前面几站写好的 payload 一直躺在这里,收尾就靠这个构建器。
落一条样本是 pbSample:
go
func (b *profileBuilder) pbSample(values []int64, locs []uint64, labels func()) {
start := b.pb.startMessage()
b.pb.int64s(tagSample_Value, values) // 四列值
b.pb.uint64s(tagSample_Location, locs) // location ID 串
if labels != nil { labels() } // 回调:往当前 Sample 塞 Label
b.pb.endMessage(tagProfile_Sample, start)
b.flush()
}
标签之所以包成回调,是因为 pbLabel 会往 Sample 消息里嵌子消息------必须在 startMessage/endMessage 之间写,不能提前。

protobuf 要 标签长度内容,可编码器只能往后写------解法是先写内容,最后把头插回开头。
startMessage / endMessage 是这一站最妙的地方 。protobuf 消息格式是 [标签][长度][内容],长度得写在内容前面;可流式编码器只能往后 append,写第一条字段时还不知道整条消息多长。解法是先写内容、最后把头部"插"回开头:
go
func (b *protobuf) endMessage(tag int, start msgOffset) {
n1 := int(start); n2 := len(b.data)
b.length(tag, n2-n1) // [tag][len] 追加到末尾
n3 := len(b.data)
copy(b.tmp[:], b.data[n2:n3]) // 暂存头部
copy(b.data[n1+(n3-n2):], b.data[n1:n2]) // payload 整体后移
copy(b.data[n1:], b.tmp[:n3-n2]) // 头部搬回开头
b.nest--
}
三段 copy 拼出 protobuf 要的 [tag][len][payload]。length() 里 varint(tag<<3 | 2) 的 2 是 wire type 2(length-delimited);varint 是变长编码、长度不固定------这正是不能预留固定空位、非要事后搬移的根因。startMessage 里的 nest++ 是给 flush() 看的门闩:消息写到一半、头还没回填时,绝不能把半截数据吐给 gzip。flush 的门槛是 nest==0 && len(data)>4096,攒够一批才压。
这里要说准一件事:b.build()(proto.go:348)不是 所有表的补全处。它写的是 profile 级头字段(TimeNanos、CPU 的 DurationNanos/Period)、Mapping 表、字符串表 StringTable,再 zw.Write + Close 拉上 gzip 落盘;HasFunctions 也是在这里按上一站的质量标记决定写不写(m.funcs == lookupTried,382 行);字符串只存一份、字段里存下标。Location 和 Function 不归 build() 管 ------那是第 6 站 emitLocation 逐条样本写 protobuf 时顺手写下的(先封口 Location,再补 Function),build() 不会重写一遍。别把"封包"理解成"从头重写":前几站写好的 payload 一直躺在 b.pb.data 里,build() 只往末尾追加这几张表和头字段,然后压缩落盘。实测里 debug=0 的输出开头是魔数 1f 8b,2216 字节------那就是这一站的成品。
CPU 的收尾也汇到这里:profileWriter 拉到 eof 才 b.build()、才 cpu.done <- true。录像和快照,绕了各自的路径,最后用的是同一个封箱工。
终点:火焰图上,我这行变成什么
九站走完,pprof.Lookup("heap").WriteTo(w, 0) 已经变成一份 gzip protobuf。但故事还没完------工具要读它,得两跳才能查回函数名:
- 第一跳 :
Sample.location = [7]→ 按 id 找到 Location #7(Address 是叶子 PC,Line 有 3 条)。 - 第二跳 :每条 Line 只有
funcID + 行号→ 拿 funcID 去 Function 表查2→main.a、3→main.b、4→main.main。
一个 id → 一条被折叠的内联链 → 多层函数名。id 是这份 profile 的局部编号 ,跨文件无意义;查找单向 Sample → Location → Function,Location 之间不靠 id 互相引用。而且 runtime/pprof 只是生产者,写这套表;真正拿 id 一层层查回去、画成火焰图的是消费端 go tool pprof------运行时自己从不回头查这些 id。

工具要两跳才查回函数名:先按 ID 找到 Location,再按 funcID 查 Function;runtime 自己从不回头查。
回头看实测那张表,每种导出落在全程地图的哪一段:
| 实测的那行 | 走过的站点 | 产物 |
|---|---|---|
heap debug=1 → heap profile: 12: ... |
起点→1→2→3(文本)→7(MemStats/两谎言) | 人读文本 + MemStats |
heap debug=0 → 1f 8b |
起点→1→2→3(proto)→6→7→8 | 四列 gzip protobuf |
goroutine debug=1 → total 1 |
起点→1→2→3→4(标签)→5(漏斗,文本出口) | count profile 文本(printStackRecord) |
goroutine debug=2 → goroutine 1 [running] |
起点→1→3 短路(跳过 2/4/5/6/7/8) | STW 全文本 dump |
block debug=1 → --- contention: |
起点→1→2→3(文本分支) | 两列文本(原始 cycles,不换算 ns) |
custom debug=1 → lab.openFiles profile: total 1 |
起点→1(漏斗路)→5(文本出口) | 自定义栈清单文本 |
这里最容易画错的一笔 :debug=1 的文本路径在漏斗里就被 printStackRecord 符号化、直接 tw.Flush() 返回了(pprof.go:491-500)------它不进 第 6 站(PC 翻 location ID)和第 8 站(gzip 封包),那两站是 debug=0 的 protobuf 专属。block/mutex 的文本分支同理:它打印的是原始 cycles (pprof.go:959,%v %v @ 的 r.Cycles),cycles→ns 换算只在 debug<=0 的 printCountCycleProfile(441/448 行)里做------文本路径压根不换算。
注意 goroutine debug=2 那一行------它在第 3 站就短路了,第 2、4、5、6、7、8 站一个都没进。这就是"debug 是扳道器"最直观的证据:同一行 WriteTo,换个 debug,走的是完全不同的路。
一路走来,每个工位的"身份卡"
跟完这一趟,把这一路见到的关键函数按它们在流水线上的位置钉成一张速查卡。这不是新知识点,只是把走过的路再摆一遍:
| 站 | 核心函数 | 一句话职责 |
|---|---|---|
| 起点 | Lookup / NewProfile / Profile |
查表拿工单;count/write 空不空定分流 |
| 1 分流 | WriteTo:377 |
内置转包专属函数,自定义走漏斗 |
| 2 捞数 | writeHeapInternal / writeRuntimeProfile / writeProfileInternal |
两段式 + 重试;CPU 是录像另走后台泵 |
| 2 后门 | 8 条 pprof_* linkname |
绕开 ABI、拿完整栈、少一次复制 |
| 3 扳道 | debug 判断 / writeGoroutineStacks |
debug 切数据种类,不是详细程度 |
| 4 贴签 | Do / SetGoroutineLabels / mergeLabelSets |
标签贴 g 背上;只有 CPU/goroutine 带 |
| 5 去重 | printCountProfile / countProfile |
压 PC 指纹、计数、排序、双出口 |
| 6 翻译 | appendLocsForStack / tryAdd / emitLocation |
PC 翻 ID,内联折成多 Line,函数延后写 |
| 6 封头 | startMessage / endMessage |
先写内容后补 [tag][len] 头,三段 copy |
| 7 缩放 | scaleHeapSample / cycles/GHz / ReadMemStats |
泊松补偿 / 单位换算 / 文本头两谎言 |
| 8 封包 | pbSample / b.build() / profileWriter |
落样本、补表、gzip;录像快照同一封箱工 |
| 终点 | 两跳查回 | Sample→Location→Function,工具端只读 |
写在最后
回头看这一趟:"我"是一行 pprof.Lookup("heap").WriteTo(w, 0)。我在起点被翻译成一张工单,在第 1 站被转包,第 2 站被两段式地从 runtime 账本里捞出来,第 3 站被 debug 扳到 proto 岔道,第 6 站把我的一串 PC 折成 location 和内联 line,第 7 站按泊松模型把我放大回可信量级,第 8 站被塞进信封、gzip 封包;最后 go tool pprof 两跳查回函数名,把我画成火焰图上的一行。
runtime/pprof 不是一堆孤立的函数。它只是把"查表 → 分流 → 捞数 → 扳道 → 贴签 → 去重 → 翻译 → 缩放 → 封包"这九件事,做成了一条流水线;每个窗口从这条线上取其所需------有的站必走(查表、分流、捞数),有的站分岔(debug 决定 proto 还是文本),有的站只有特定窗口才进(贴签只有 CPU/goroutine,漏斗只有 count 类)。 你把这一趟记住了,再回头看这里的任何一个函数,都知道它站在哪一站、上一站把什么交给它、它把什么交给下一站。
单个知识点你本来就懂。现在它们终于有了位置。