...
Run Format

Source file src/runtime/pprof/proto_test.go

Documentation: runtime/pprof

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

View as plain text