From 14a4649fe2c1cb90093e5a7653c95169cde6cc67 Mon Sep 17 00:00:00 2001 From: =?utf8?q?H=C3=A5vard=20Haugen?= Date: Fri, 9 Jan 2015 00:11:44 +0100 Subject: [PATCH] cmd/pprof: handle empty profile gracefully The command "go tool pprof -top $GOROOT/bin/go /dev/null" now logs that profile is empty instead of panicking. Fixes #9207 Change-Id: I3d55c179277cb19ad52c8f24f1aca85db53ee08d Reviewed-on: https://go-review.googlesource.com/2571 Run-TryBot: Brad Fitzpatrick Reviewed-by: Brad Fitzpatrick --- src/cmd/pprof/internal/driver/driver.go | 4 ++++ src/cmd/pprof/internal/profile/profile.go | 5 ++++ .../pprof/internal/profile/profile_test.go | 24 +++++++++++++++++++ 3 files changed, 33 insertions(+) create mode 100644 src/cmd/pprof/internal/profile/profile_test.go diff --git a/src/cmd/pprof/internal/driver/driver.go b/src/cmd/pprof/internal/driver/driver.go index 9703bafa63..acb29d13aa 100644 --- a/src/cmd/pprof/internal/driver/driver.go +++ b/src/cmd/pprof/internal/driver/driver.go @@ -1013,6 +1013,10 @@ func generate(interactive bool, prof *profile.Profile, obj plugin.ObjTool, ui pl w = outputFile } + if prof.Empty() { + return fmt.Errorf("profile is empty") + } + value, stype, unit := sampleFormat(prof, f) o.SampleType = stype rpt := report.New(prof, *o, value, unit) diff --git a/src/cmd/pprof/internal/profile/profile.go b/src/cmd/pprof/internal/profile/profile.go index 7ee58eee77..5eb641f7cd 100644 --- a/src/cmd/pprof/internal/profile/profile.go +++ b/src/cmd/pprof/internal/profile/profile.go @@ -565,3 +565,8 @@ func (p *Profile) Demangle(d Demangler) error { } return nil } + +// Empty returns true if the profile contains no samples. +func (p *Profile) Empty() bool { + return len(p.Sample) == 0 +} diff --git a/src/cmd/pprof/internal/profile/profile_test.go b/src/cmd/pprof/internal/profile/profile_test.go new file mode 100644 index 0000000000..09b11a456f --- /dev/null +++ b/src/cmd/pprof/internal/profile/profile_test.go @@ -0,0 +1,24 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package profile + +import ( + "bytes" + "testing" +) + +func TestEmptyProfile(t *testing.T) { + var buf bytes.Buffer + p, err := Parse(&buf) + if err != nil { + t.Error("Want no error, got", err) + } + if p == nil { + t.Fatal("Want a valid profile, got ") + } + if !p.Empty() { + t.Errorf("Profile should be empty, got %#v", p) + } +} -- 2.50.0