Debian Codegraph @

libgo/go/runtime/pprof/proto_test.go

raw
1 // Copyright 2016 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 package pprof
6
7 import (
8 "bytes"
9 "encoding/json"
10 "fmt"
11 "internal/abi"
12 "internal/profile"
13 "internal/testenv"
14 "os"
15 "os/exec"
16 "reflect"
17 "runtime"
18 "strings"
19 "testing"
20 "unsafe"
21 )
22
23 // translateCPUProfile parses binary CPU profiling stack trace data
24 // generated by runtime.CPUProfile() into a profile struct.
25 // This is only used for testing. Real conversions stream the
26 // data into the profileBuilder as it becomes available.
27 //
28 // count is the number of records in data.
29 func translateCPUProfile(data []uint64, count int) (*profile.Profile, error) {
30 var buf bytes.Buffer
31 b := newProfileBuilder(&buf)
32 tags := make([]unsafe.Pointer, count)
33 if err := b.addCPUData(data, tags); err != nil {
34 return nil, err
35 }
36 b.build()
37 return profile.Parse(&buf)
38 }
39
40 // fmtJSON returns a pretty-printed JSON form for x.
41 // It works reasonbly well for printing protocol-buffer
42 // data structures like profile.Profile.
43 func fmtJSON(x any) string {
44 js, _ := json.MarshalIndent(x, "", "\t")
45 return string(js)
46 }
47
48 func TestConvertCPUProfileEmpty(t *testing.T) {
49 // A test server with mock cpu profile data.
50 var buf bytes.Buffer
51
52 b := []uint64{3, 0, 500} // empty profile at 500 Hz (2ms sample period)
53 p, err := translateCPUProfile(b, 1)
54 if err != nil {
55 t.Fatalf("translateCPUProfile: %v", err)
56 }
57 if err := p.Write(&buf); err != nil {
58 t.Fatalf("writing profile: %v", err)
59 }
60
61 p, err = profile.Parse(&buf)
62 if err != nil {
63 t.Fatalf("profile.Parse: %v", err)
64 }
65
66 // Expected PeriodType and SampleType.
67 periodType := &profile.ValueType{Type: "cpu", Unit: "nanoseconds"}
68 sampleType := []*profile.ValueType{
69 {Type: "samples", Unit: "count"},
70 {Type: "cpu", Unit: "nanoseconds"},
71 }
72
73 checkProfile(t, p, 2000*1000, periodType, sampleType, nil, "")
74 }
75
76 // For gccgo make these functions different so that gccgo doesn't
77 // merge them with each other and with lostProfileEvent.
78 func f1(i int) { f1(i + 1) }
79 func f2(i int) { f2(i + 2) }
80
81 // testPCs returns two PCs and two corresponding memory mappings
82 // to use in test profiles.
83 func testPCs(t *testing.T) (addr1, addr2 uint64, map1, map2 *profile.Mapping) {
84 switch runtime.GOOS {
85 case "linux", "android", "netbsd":
86 // Figure out two addresses from /proc/self/maps.
87 mmap, err := os.ReadFile("/proc/self/maps")
88 if err != nil {
89 t.Fatal(err)
90 }
91 mprof := &profile.Profile{}
92 if err = mprof.ParseMemoryMap(bytes.NewReader(mmap)); err != nil {
93 t.Fatalf("parsing /proc/self/maps: %v", err)
94 }
95 if len(mprof.Mapping) < 2 {
96 // It is possible for a binary to only have 1 executable
97 // region of memory.
98 t.Skipf("need 2 or more mappings, got %v", len(mprof.Mapping))
99 }
100 addr1 = mprof.Mapping[0].Start
101 map1 = mprof.Mapping[0]
102 map1.BuildID, _ = elfBuildID(map1.File)
103 addr2 = mprof.Mapping[1].Start
104 map2 = mprof.Mapping[1]
105 map2.BuildID, _ = elfBuildID(map2.File)
106 case "js":
107 addr1 = uint64(abi.FuncPCABIInternal(f1))
108 addr2 = uint64(abi.FuncPCABIInternal(f2))
109 default:
110 addr1 = uint64(abi.FuncPCABIInternal(f1))
111 addr2 = uint64(abi.FuncPCABIInternal(f2))
112 // Fake mapping - HasFunctions will be true because two PCs from Go
113 // will be fully symbolized.
114 fake := &profile.Mapping{ID: 1, HasFunctions: true}
115 map1, map2 = fake, fake
116 }
117 return
118 }
119
120 func TestConvertCPUProfile(t *testing.T) {
121 addr1, addr2, map1, map2 := testPCs(t)
122
123 b := []uint64{
124 3, 0, 500, // hz = 500
125 5, 0, 10, uint64(addr1 + 1), uint64(addr1 + 2), // 10 samples in addr1
126 5, 0, 40, uint64(addr2 + 1), uint64(addr2 + 2), // 40 samples in addr2
127 5, 0, 10, uint64(addr1 + 1), uint64(addr1 + 2), // 10 samples in addr1
128 }
129 p, err := translateCPUProfile(b, 4)
130 if err != nil {
131 t.Fatalf("translating profile: %v", err)
132 }
133 period := int64(2000 * 1000)
134 periodType := &profile.ValueType{Type: "cpu", Unit: "nanoseconds"}
135 sampleType := []*profile.ValueType{
136 {Type: "samples", Unit: "count"},
137 {Type: "cpu", Unit: "nanoseconds"},
138 }
139 samples := []*profile.Sample{
140 {Value: []int64{20, 20 * 2000 * 1000}, Location: []*profile.Location{
141 {ID: 1, Mapping: map1, Address: addr1},
142 {ID: 2, Mapping: map1, Address: addr1 + 1},
143 }},
144 {Value: []int64{40, 40 * 2000 * 1000}, Location: []*profile.Location{
145 {ID: 3, Mapping: map2, Address: addr2},
146 {ID: 4, Mapping: map2, Address: addr2 + 1},
147 }},
148 }
149 checkProfile(t, p, period, periodType, sampleType, samples, "")
150 }
151
152 func checkProfile(t *testing.T, p *profile.Profile, period int64, periodType *profile.ValueType, sampleType []*profile.ValueType, samples []*profile.Sample, defaultSampleType string) {
153 t.Helper()
154
155 if p.Period != period {
156 t.Errorf("p.Period = %d, want %d", p.Period, period)
157 }
158 if !reflect.DeepEqual(p.PeriodType, periodType) {
159 t.Errorf("p.PeriodType = %v\nwant = %v", fmtJSON(p.PeriodType), fmtJSON(periodType))
160 }
161 if !reflect.DeepEqual(p.SampleType, sampleType) {
162 t.Errorf("p.SampleType = %v\nwant = %v", fmtJSON(p.SampleType), fmtJSON(sampleType))
163 }
164 if defaultSampleType != p.DefaultSampleType {
165 t.Errorf("p.DefaultSampleType = %v\nwant = %v", p.DefaultSampleType, defaultSampleType)
166 }
167 // Clear line info since it is not in the expected samples.
168 // If we used f1 and f2 above, then the samples will have line info.
169 for _, s := range p.Sample {
170 for _, l := range s.Location {
171 l.Line = nil
172 }
173 }
174 if fmtJSON(p.Sample) != fmtJSON(samples) { // ignore unexported fields
175 if len(p.Sample) == len(samples) {
176 for i := range p.Sample {
177 if !reflect.DeepEqual(p.Sample[i], samples[i]) {
178 t.Errorf("sample %d = %v\nwant = %v\n", i, fmtJSON(p.Sample[i]), fmtJSON(samples[i]))
179 }
180 }
181 if t.Failed() {
182 t.FailNow()
183 }
184 }
185 t.Fatalf("p.Sample = %v\nwant = %v", fmtJSON(p.Sample), fmtJSON(samples))
186 }
187 }
188
189 var profSelfMapsTests = `
190 00400000-0040b000 r-xp 00000000 fc:01 787766 /bin/cat
191 0060a000-0060b000 r--p 0000a000 fc:01 787766 /bin/cat
192 0060b000-0060c000 rw-p 0000b000 fc:01 787766 /bin/cat
193 014ab000-014cc000 rw-p 00000000 00:00 0 [heap]
194 7f7d76af8000-7f7d7797c000 r--p 00000000 fc:01 1318064 /usr/lib/locale/locale-archive
195 7f7d7797c000-7f7d77b36000 r-xp 00000000 fc:01 1180226 /lib/x86_64-linux-gnu/libc-2.19.so
196 7f7d77b36000-7f7d77d36000 ---p 001ba000 fc:01 1180226 /lib/x86_64-linux-gnu/libc-2.19.so
197 7f7d77d36000-7f7d77d3a000 r--p 001ba000 fc:01 1180226 /lib/x86_64-linux-gnu/libc-2.19.so
198 7f7d77d3a000-7f7d77d3c000 rw-p 001be000 fc:01 1180226 /lib/x86_64-linux-gnu/libc-2.19.so
199 7f7d77d3c000-7f7d77d41000 rw-p 00000000 00:00 0
200 7f7d77d41000-7f7d77d64000 r-xp 00000000 fc:01 1180217 /lib/x86_64-linux-gnu/ld-2.19.so
201 7f7d77f3f000-7f7d77f42000 rw-p 00000000 00:00 0
202 7f7d77f61000-7f7d77f63000 rw-p 00000000 00:00 0
203 7f7d77f63000-7f7d77f64000 r--p 00022000 fc:01 1180217 /lib/x86_64-linux-gnu/ld-2.19.so
204 7f7d77f64000-7f7d77f65000 rw-p 00023000 fc:01 1180217 /lib/x86_64-linux-gnu/ld-2.19.so
205 7f7d77f65000-7f7d77f66000 rw-p 00000000 00:00 0
206 7ffc342a2000-7ffc342c3000 rw-p 00000000 00:00 0 [stack]
207 7ffc34343000-7ffc34345000 r-xp 00000000 00:00 0 [vdso]
208 ffffffffff600000-ffffffffff601000 r-xp 00000090 00:00 0 [vsyscall]
209 ->
210 00400000 0040b000 00000000 /bin/cat
211 7f7d7797c000 7f7d77b36000 00000000 /lib/x86_64-linux-gnu/libc-2.19.so
212 7f7d77d41000 7f7d77d64000 00000000 /lib/x86_64-linux-gnu/ld-2.19.so
213 7ffc34343000 7ffc34345000 00000000 [vdso]
214 ffffffffff600000 ffffffffff601000 00000090 [vsyscall]
215
216 00400000-07000000 r-xp 00000000 00:00 0
217 07000000-07093000 r-xp 06c00000 00:2e 536754 /path/to/gobench_server_main
218 07093000-0722d000 rw-p 06c92000 00:2e 536754 /path/to/gobench_server_main
219 0722d000-07b21000 rw-p 00000000 00:00 0
220 c000000000-c000036000 rw-p 00000000 00:00 0
221 ->
222 07000000 07093000 06c00000 /path/to/gobench_server_main
223 `
224
225 var profSelfMapsTestsWithDeleted = `
226 00400000-0040b000 r-xp 00000000 fc:01 787766 /bin/cat (deleted)
227 0060a000-0060b000 r--p 0000a000 fc:01 787766 /bin/cat (deleted)
228 0060b000-0060c000 rw-p 0000b000 fc:01 787766 /bin/cat (deleted)
229 014ab000-014cc000 rw-p 00000000 00:00 0 [heap]
230 7f7d76af8000-7f7d7797c000 r--p 00000000 fc:01 1318064 /usr/lib/locale/locale-archive
231 7f7d7797c000-7f7d77b36000 r-xp 00000000 fc:01 1180226 /lib/x86_64-linux-gnu/libc-2.19.so
232 7f7d77b36000-7f7d77d36000 ---p 001ba000 fc:01 1180226 /lib/x86_64-linux-gnu/libc-2.19.so
233 7f7d77d36000-7f7d77d3a000 r--p 001ba000 fc:01 1180226 /lib/x86_64-linux-gnu/libc-2.19.so
234 7f7d77d3a000-7f7d77d3c000 rw-p 001be000 fc:01 1180226 /lib/x86_64-linux-gnu/libc-2.19.so
235 7f7d77d3c000-7f7d77d41000 rw-p 00000000 00:00 0
236 7f7d77d41000-7f7d77d64000 r-xp 00000000 fc:01 1180217 /lib/x86_64-linux-gnu/ld-2.19.so
237 7f7d77f3f000-7f7d77f42000 rw-p 00000000 00:00 0
238 7f7d77f61000-7f7d77f63000 rw-p 00000000 00:00 0
239 7f7d77f63000-7f7d77f64000 r--p 00022000 fc:01 1180217 /lib/x86_64-linux-gnu/ld-2.19.so
240 7f7d77f64000-7f7d77f65000 rw-p 00023000 fc:01 1180217 /lib/x86_64-linux-gnu/ld-2.19.so
241 7f7d77f65000-7f7d77f66000 rw-p 00000000 00:00 0
242 7ffc342a2000-7ffc342c3000 rw-p 00000000 00:00 0 [stack]
243 7ffc34343000-7ffc34345000 r-xp 00000000 00:00 0 [vdso]
244 ffffffffff600000-ffffffffff601000 r-xp 00000090 00:00 0 [vsyscall]
245 ->
246 00400000 0040b000 00000000 /bin/cat
247 7f7d7797c000 7f7d77b36000 00000000 /lib/x86_64-linux-gnu/libc-2.19.so
248 7f7d77d41000 7f7d77d64000 00000000 /lib/x86_64-linux-gnu/ld-2.19.so
249 7ffc34343000 7ffc34345000 00000000 [vdso]
250 ffffffffff600000 ffffffffff601000 00000090 [vsyscall]
251
252 00400000-0040b000 r-xp 00000000 fc:01 787766 /bin/cat with space
253 0060a000-0060b000 r--p 0000a000 fc:01 787766 /bin/cat with space
254 0060b000-0060c000 rw-p 0000b000 fc:01 787766 /bin/cat with space
255 014ab000-014cc000 rw-p 00000000 00:00 0 [heap]
256 7f7d76af8000-7f7d7797c000 r--p 00000000 fc:01 1318064 /usr/lib/locale/locale-archive
257 7f7d7797c000-7f7d77b36000 r-xp 00000000 fc:01 1180226 /lib/x86_64-linux-gnu/libc-2.19.so
258 7f7d77b36000-7f7d77d36000 ---p 001ba000 fc:01 1180226 /lib/x86_64-linux-gnu/libc-2.19.so
259 7f7d77d36000-7f7d77d3a000 r--p 001ba000 fc:01 1180226 /lib/x86_64-linux-gnu/libc-2.19.so
260 7f7d77d3a000-7f7d77d3c000 rw-p 001be000 fc:01 1180226 /lib/x86_64-linux-gnu/libc-2.19.so
261 7f7d77d3c000-7f7d77d41000 rw-p 00000000 00:00 0
262 7f7d77d41000-7f7d77d64000 r-xp 00000000 fc:01 1180217 /lib/x86_64-linux-gnu/ld-2.19.so
263 7f7d77f3f000-7f7d77f42000 rw-p 00000000 00:00 0
264 7f7d77f61000-7f7d77f63000 rw-p 00000000 00:00 0
265 7f7d77f63000-7f7d77f64000 r--p 00022000 fc:01 1180217 /lib/x86_64-linux-gnu/ld-2.19.so
266 7f7d77f64000-7f7d77f65000 rw-p 00023000 fc:01 1180217 /lib/x86_64-linux-gnu/ld-2.19.so
267 7f7d77f65000-7f7d77f66000 rw-p 00000000 00:00 0
268 7ffc342a2000-7ffc342c3000 rw-p 00000000 00:00 0 [stack]
269 7ffc34343000-7ffc34345000 r-xp 00000000 00:00 0 [vdso]
270 ffffffffff600000-ffffffffff601000 r-xp 00000090 00:00 0 [vsyscall]
271 ->
272 00400000 0040b000 00000000 /bin/cat with space
273 7f7d7797c000 7f7d77b36000 00000000 /lib/x86_64-linux-gnu/libc-2.19.so
274 7f7d77d41000 7f7d77d64000 00000000 /lib/x86_64-linux-gnu/ld-2.19.so
275 7ffc34343000 7ffc34345000 00000000 [vdso]
276 ffffffffff600000 ffffffffff601000 00000090 [vsyscall]
277 `
278
279 func TestProcSelfMaps(t *testing.T) {
280
281 f := func(t *testing.T, input string) {
282 for tx, tt := range strings.Split(input, "\n\n") {
283 in, out, ok := strings.Cut(tt, "->\n")
284 if !ok {
285 t.Fatal("malformed test case")
286 }
287 if len(out) > 0 && out[len(out)-1] != '\n' {
288 out += "\n"
289 }
290 var buf bytes.Buffer
291 parseProcSelfMaps([]byte(in), func(lo, hi, offset uint64, file, buildID string) {
292 fmt.Fprintf(&buf, "%08x %08x %08x %s\n", lo, hi, offset, file)
293 })
294 if buf.String() != out {
295 t.Errorf("#%d: have:\n%s\nwant:\n%s\n%q\n%q", tx, buf.String(), out, buf.String(), out)
296 }
297 }
298 }
299
300 t.Run("Normal", func(t *testing.T) {
301 f(t, profSelfMapsTests)
302 })
303
304 t.Run("WithDeletedFile", func(t *testing.T) {
305 f(t, profSelfMapsTestsWithDeleted)
306 })
307 }
308
309 // TestMapping checks the mapping section of CPU profiles
310 // has the HasFunctions field set correctly. If all PCs included
311 // in the samples are successfully symbolized, the corresponding
312 // mapping entry (in this test case, only one entry) should have
313 // its HasFunctions field set true.
314 // The test generates a CPU profile that includes PCs from C side
315 // that the runtime can't symbolize. See ./testdata/mappingtest.
316 func TestMapping(t *testing.T) {
317 testenv.MustHaveGoRun(t)
318 testenv.MustHaveCGO(t)
319
320 prog := "./testdata/mappingtest/main.go"
321
322 // GoOnly includes only Go symbols that runtime will symbolize.
323 // Go+C includes C symbols that runtime will not symbolize.
324 for _, traceback := range []string{"GoOnly", "Go+C"} {
325 t.Run("traceback"+traceback, func(t *testing.T) {
326 cmd := exec.Command(testenv.GoToolPath(t), "run", prog)
327 if traceback != "GoOnly" {
328 cmd.Env = append(os.Environ(), "SETCGOTRACEBACK=1")
329 }
330 cmd.Stderr = new(bytes.Buffer)
331
332 out, err := cmd.Output()
333 if err != nil {
334 t.Fatalf("failed to run the test program %q: %v\n%v", prog, err, cmd.Stderr)
335 }
336
337 prof, err := profile.Parse(bytes.NewReader(out))
338 if err != nil {
339 t.Fatalf("failed to parse the generated profile data: %v", err)
340 }
341 t.Logf("Profile: %s", prof)
342
343 hit := make(map[*profile.Mapping]bool)
344 miss := make(map[*profile.Mapping]bool)
345 for _, loc := range prof.Location {
346 if symbolized(loc) {
347 hit[loc.Mapping] = true
348 } else {
349 miss[loc.Mapping] = true
350 }
351 }
352 if len(miss) == 0 {
353 t.Log("no location with missing symbol info was sampled")
354 }
355
356 for _, m := range prof.Mapping {
357 if miss[m] && m.HasFunctions {
358 t.Errorf("mapping %+v has HasFunctions=true, but contains locations with failed symbolization", m)
359 continue
360 }
361 if !miss[m] && hit[m] && !m.HasFunctions {
362 t.Errorf("mapping %+v has HasFunctions=false, but all referenced locations from this lapping were symbolized successfully", m)
363 continue
364 }
365 }
366
367 if traceback == "Go+C" {
368 // The test code was arranged to have PCs from C and
369 // they are not symbolized.
370 // Check no Location containing those unsymbolized PCs contains multiple lines.
371 for i, loc := range prof.Location {
372 if !symbolized(loc) && len(loc.Line) > 1 {
373 t.Errorf("Location[%d] contains unsymbolized PCs and multiple lines: %v", i, loc)
374 }
375 }
376 }
377 })
378 }
379 }
380
381 func symbolized(loc *profile.Location) bool {
382 if len(loc.Line) == 0 {
383 return false
384 }
385 l := loc.Line[0]
386 f := l.Function
387 if l.Line == 0 || f == nil || f.Name == "" || f.Filename == "" {
388 return false
389 }
390 return true
391 }
392
393 // TestFakeMapping tests if at least one mapping exists
394 // (including a fake mapping), and their HasFunctions bits
395 // are set correctly.
396 func TestFakeMapping(t *testing.T) {
397 var buf bytes.Buffer
398 if err := Lookup("heap").WriteTo(&buf, 0); err != nil {
399 t.Fatalf("failed to write heap profile: %v", err)
400 }
401 prof, err := profile.Parse(&buf)
402 if err != nil {
403 t.Fatalf("failed to parse the generated profile data: %v", err)
404 }
405 t.Logf("Profile: %s", prof)
406 if len(prof.Mapping) == 0 {
407 t.Fatal("want profile with at least one mapping entry, got 0 mapping")
408 }
409
410 hit := make(map[*profile.Mapping]bool)
411 miss := make(map[*profile.Mapping]bool)
412 for _, loc := range prof.Location {
413 if symbolized(loc) {
414 hit[loc.Mapping] = true
415 } else {
416 miss[loc.Mapping] = true
417 }
418 }
419 for _, m := range prof.Mapping {
420 if miss[m] && m.HasFunctions {
421 t.Errorf("mapping %+v has HasFunctions=true, but contains locations with failed symbolization", m)
422 continue
423 }
424 if !miss[m] && hit[m] && !m.HasFunctions {
425 t.Errorf("mapping %+v has HasFunctions=false, but all referenced locations from this lapping were symbolized successfully", m)
426 continue
427 }
428 }
429 }
430
431 // Make sure the profiler can handle an empty stack trace.
432 // See issue 37967.
433 func TestEmptyStack(t *testing.T) {
434 b := []uint64{
435 3, 0, 500, // hz = 500
436 3, 0, 10, // 10 samples with an empty stack trace
437 }
438 _, err := translateCPUProfile(b, 2)
439 if err != nil {
440 t.Fatalf("translating profile: %v", err)
441 }
442 }