repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
sequence
docstring
stringlengths
6
2.61k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
85
252
partition
stringclasses
1 value
hashicorp/golang-lru
simplelru/lru.go
NewLRU
func NewLRU(size int, onEvict EvictCallback) (*LRU, error) { if size <= 0 { return nil, errors.New("Must provide a positive size") } c := &LRU{ size: size, evictList: list.New(), items: make(map[interface{}]*list.Element), onEvict: onEvict, } return c, nil }
go
func NewLRU(size int, onEvict EvictCallback) (*LRU, error) { if size <= 0 { return nil, errors.New("Must provide a positive size") } c := &LRU{ size: size, evictList: list.New(), items: make(map[interface{}]*list.Element), onEvict: onEvict, } return c, nil }
[ "func", "NewLRU", "(", "size", "int", ",", "onEvict", "EvictCallback", ")", "(", "*", "LRU", ",", "error", ")", "{", "if", "size", "<=", "0", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "c", ":=", "&", "LRU", "{", "size", ":", "size", ",", "evictList", ":", "list", ".", "New", "(", ")", ",", "items", ":", "make", "(", "map", "[", "interface", "{", "}", "]", "*", "list", ".", "Element", ")", ",", "onEvict", ":", "onEvict", ",", "}", "\n", "return", "c", ",", "nil", "\n", "}" ]
// NewLRU constructs an LRU of the given size
[ "NewLRU", "constructs", "an", "LRU", "of", "the", "given", "size" ]
7087cb70de9f7a8bc0a10c375cb0d2280a8edf9c
https://github.com/hashicorp/golang-lru/blob/7087cb70de9f7a8bc0a10c375cb0d2280a8edf9c/simplelru/lru.go#L26-L37
train
hashicorp/golang-lru
simplelru/lru.go
Remove
func (c *LRU) Remove(key interface{}) (present bool) { if ent, ok := c.items[key]; ok { c.removeElement(ent) return true } return false }
go
func (c *LRU) Remove(key interface{}) (present bool) { if ent, ok := c.items[key]; ok { c.removeElement(ent) return true } return false }
[ "func", "(", "c", "*", "LRU", ")", "Remove", "(", "key", "interface", "{", "}", ")", "(", "present", "bool", ")", "{", "if", "ent", ",", "ok", ":=", "c", ".", "items", "[", "key", "]", ";", "ok", "{", "c", ".", "removeElement", "(", "ent", ")", "\n", "return", "true", "\n", "}", "\n", "return", "false", "\n", "}" ]
// Remove removes the provided key from the cache, returning if the // key was contained.
[ "Remove", "removes", "the", "provided", "key", "from", "the", "cache", "returning", "if", "the", "key", "was", "contained", "." ]
7087cb70de9f7a8bc0a10c375cb0d2280a8edf9c
https://github.com/hashicorp/golang-lru/blob/7087cb70de9f7a8bc0a10c375cb0d2280a8edf9c/simplelru/lru.go#L100-L106
train
hashicorp/golang-lru
simplelru/lru.go
removeOldest
func (c *LRU) removeOldest() { ent := c.evictList.Back() if ent != nil { c.removeElement(ent) } }
go
func (c *LRU) removeOldest() { ent := c.evictList.Back() if ent != nil { c.removeElement(ent) } }
[ "func", "(", "c", "*", "LRU", ")", "removeOldest", "(", ")", "{", "ent", ":=", "c", ".", "evictList", ".", "Back", "(", ")", "\n", "if", "ent", "!=", "nil", "{", "c", ".", "removeElement", "(", "ent", ")", "\n", "}", "\n", "}" ]
// removeOldest removes the oldest item from the cache.
[ "removeOldest", "removes", "the", "oldest", "item", "from", "the", "cache", "." ]
7087cb70de9f7a8bc0a10c375cb0d2280a8edf9c
https://github.com/hashicorp/golang-lru/blob/7087cb70de9f7a8bc0a10c375cb0d2280a8edf9c/simplelru/lru.go#L146-L151
train
hashicorp/golang-lru
lru.go
NewWithEvict
func NewWithEvict(size int, onEvicted func(key interface{}, value interface{})) (*Cache, error) { lru, err := simplelru.NewLRU(size, simplelru.EvictCallback(onEvicted)) if err != nil { return nil, err } c := &Cache{ lru: lru, } return c, nil }
go
func NewWithEvict(size int, onEvicted func(key interface{}, value interface{})) (*Cache, error) { lru, err := simplelru.NewLRU(size, simplelru.EvictCallback(onEvicted)) if err != nil { return nil, err } c := &Cache{ lru: lru, } return c, nil }
[ "func", "NewWithEvict", "(", "size", "int", ",", "onEvicted", "func", "(", "key", "interface", "{", "}", ",", "value", "interface", "{", "}", ")", ")", "(", "*", "Cache", ",", "error", ")", "{", "lru", ",", "err", ":=", "simplelru", ".", "NewLRU", "(", "size", ",", "simplelru", ".", "EvictCallback", "(", "onEvicted", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "c", ":=", "&", "Cache", "{", "lru", ":", "lru", ",", "}", "\n", "return", "c", ",", "nil", "\n", "}" ]
// NewWithEvict constructs a fixed size cache with the given eviction // callback.
[ "NewWithEvict", "constructs", "a", "fixed", "size", "cache", "with", "the", "given", "eviction", "callback", "." ]
7087cb70de9f7a8bc0a10c375cb0d2280a8edf9c
https://github.com/hashicorp/golang-lru/blob/7087cb70de9f7a8bc0a10c375cb0d2280a8edf9c/lru.go#L22-L31
train
hashicorp/golang-lru
lru.go
ContainsOrAdd
func (c *Cache) ContainsOrAdd(key, value interface{}) (ok, evicted bool) { c.lock.Lock() defer c.lock.Unlock() if c.lru.Contains(key) { return true, false } evicted = c.lru.Add(key, value) return false, evicted }
go
func (c *Cache) ContainsOrAdd(key, value interface{}) (ok, evicted bool) { c.lock.Lock() defer c.lock.Unlock() if c.lru.Contains(key) { return true, false } evicted = c.lru.Add(key, value) return false, evicted }
[ "func", "(", "c", "*", "Cache", ")", "ContainsOrAdd", "(", "key", ",", "value", "interface", "{", "}", ")", "(", "ok", ",", "evicted", "bool", ")", "{", "c", ".", "lock", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "lock", ".", "Unlock", "(", ")", "\n\n", "if", "c", ".", "lru", ".", "Contains", "(", "key", ")", "{", "return", "true", ",", "false", "\n", "}", "\n", "evicted", "=", "c", ".", "lru", ".", "Add", "(", "key", ",", "value", ")", "\n", "return", "false", ",", "evicted", "\n", "}" ]
// ContainsOrAdd checks if a key is in the cache without updating the // recent-ness or deleting it for being stale, and if not, adds the value. // Returns whether found and whether an eviction occurred.
[ "ContainsOrAdd", "checks", "if", "a", "key", "is", "in", "the", "cache", "without", "updating", "the", "recent", "-", "ness", "or", "deleting", "it", "for", "being", "stale", "and", "if", "not", "adds", "the", "value", ".", "Returns", "whether", "found", "and", "whether", "an", "eviction", "occurred", "." ]
7087cb70de9f7a8bc0a10c375cb0d2280a8edf9c
https://github.com/hashicorp/golang-lru/blob/7087cb70de9f7a8bc0a10c375cb0d2280a8edf9c/lru.go#L77-L86
train
hashicorp/golang-lru
lru.go
Keys
func (c *Cache) Keys() []interface{} { c.lock.RLock() keys := c.lru.Keys() c.lock.RUnlock() return keys }
go
func (c *Cache) Keys() []interface{} { c.lock.RLock() keys := c.lru.Keys() c.lock.RUnlock() return keys }
[ "func", "(", "c", "*", "Cache", ")", "Keys", "(", ")", "[", "]", "interface", "{", "}", "{", "c", ".", "lock", ".", "RLock", "(", ")", "\n", "keys", ":=", "c", ".", "lru", ".", "Keys", "(", ")", "\n", "c", ".", "lock", ".", "RUnlock", "(", ")", "\n", "return", "keys", "\n", "}" ]
// Keys returns a slice of the keys in the cache, from oldest to newest.
[ "Keys", "returns", "a", "slice", "of", "the", "keys", "in", "the", "cache", "from", "oldest", "to", "newest", "." ]
7087cb70de9f7a8bc0a10c375cb0d2280a8edf9c
https://github.com/hashicorp/golang-lru/blob/7087cb70de9f7a8bc0a10c375cb0d2280a8edf9c/lru.go#L103-L108
train
google/pprof
internal/driver/webui.go
makeReport
func (ui *webInterface) makeReport(w http.ResponseWriter, req *http.Request, cmd []string, vars ...string) (*report.Report, []string) { v := varsFromURL(req.URL) for i := 0; i+1 < len(vars); i += 2 { v[vars[i]].value = vars[i+1] } catcher := &errorCatcher{UI: ui.options.UI} options := *ui.options options.UI = catcher _, rpt, err := generateRawReport(ui.prof, cmd, v, &options) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) ui.options.UI.PrintErr(err) return nil, nil } return rpt, catcher.errors }
go
func (ui *webInterface) makeReport(w http.ResponseWriter, req *http.Request, cmd []string, vars ...string) (*report.Report, []string) { v := varsFromURL(req.URL) for i := 0; i+1 < len(vars); i += 2 { v[vars[i]].value = vars[i+1] } catcher := &errorCatcher{UI: ui.options.UI} options := *ui.options options.UI = catcher _, rpt, err := generateRawReport(ui.prof, cmd, v, &options) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) ui.options.UI.PrintErr(err) return nil, nil } return rpt, catcher.errors }
[ "func", "(", "ui", "*", "webInterface", ")", "makeReport", "(", "w", "http", ".", "ResponseWriter", ",", "req", "*", "http", ".", "Request", ",", "cmd", "[", "]", "string", ",", "vars", "...", "string", ")", "(", "*", "report", ".", "Report", ",", "[", "]", "string", ")", "{", "v", ":=", "varsFromURL", "(", "req", ".", "URL", ")", "\n", "for", "i", ":=", "0", ";", "i", "+", "1", "<", "len", "(", "vars", ")", ";", "i", "+=", "2", "{", "v", "[", "vars", "[", "i", "]", "]", ".", "value", "=", "vars", "[", "i", "+", "1", "]", "\n", "}", "\n", "catcher", ":=", "&", "errorCatcher", "{", "UI", ":", "ui", ".", "options", ".", "UI", "}", "\n", "options", ":=", "*", "ui", ".", "options", "\n", "options", ".", "UI", "=", "catcher", "\n", "_", ",", "rpt", ",", "err", ":=", "generateRawReport", "(", "ui", ".", "prof", ",", "cmd", ",", "v", ",", "&", "options", ")", "\n", "if", "err", "!=", "nil", "{", "http", ".", "Error", "(", "w", ",", "err", ".", "Error", "(", ")", ",", "http", ".", "StatusBadRequest", ")", "\n", "ui", ".", "options", ".", "UI", ".", "PrintErr", "(", "err", ")", "\n", "return", "nil", ",", "nil", "\n", "}", "\n", "return", "rpt", ",", "catcher", ".", "errors", "\n", "}" ]
// makeReport generates a report for the specified command.
[ "makeReport", "generates", "a", "report", "for", "the", "specified", "command", "." ]
8358a9778bd1e48718ffcb96eb11ee061385bf62
https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/internal/driver/webui.go#L255-L271
train
google/pprof
internal/driver/webui.go
render
func (ui *webInterface) render(w http.ResponseWriter, tmpl string, rpt *report.Report, errList, legend []string, data webArgs) { file := getFromLegend(legend, "File: ", "unknown") profile := getFromLegend(legend, "Type: ", "unknown") data.Title = file + " " + profile data.Errors = errList data.Total = rpt.Total() data.SampleTypes = sampleTypes(ui.prof) data.Legend = legend data.Help = ui.help html := &bytes.Buffer{} if err := ui.templates.ExecuteTemplate(html, tmpl, data); err != nil { http.Error(w, "internal template error", http.StatusInternalServerError) ui.options.UI.PrintErr(err) return } w.Header().Set("Content-Type", "text/html") w.Write(html.Bytes()) }
go
func (ui *webInterface) render(w http.ResponseWriter, tmpl string, rpt *report.Report, errList, legend []string, data webArgs) { file := getFromLegend(legend, "File: ", "unknown") profile := getFromLegend(legend, "Type: ", "unknown") data.Title = file + " " + profile data.Errors = errList data.Total = rpt.Total() data.SampleTypes = sampleTypes(ui.prof) data.Legend = legend data.Help = ui.help html := &bytes.Buffer{} if err := ui.templates.ExecuteTemplate(html, tmpl, data); err != nil { http.Error(w, "internal template error", http.StatusInternalServerError) ui.options.UI.PrintErr(err) return } w.Header().Set("Content-Type", "text/html") w.Write(html.Bytes()) }
[ "func", "(", "ui", "*", "webInterface", ")", "render", "(", "w", "http", ".", "ResponseWriter", ",", "tmpl", "string", ",", "rpt", "*", "report", ".", "Report", ",", "errList", ",", "legend", "[", "]", "string", ",", "data", "webArgs", ")", "{", "file", ":=", "getFromLegend", "(", "legend", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "profile", ":=", "getFromLegend", "(", "legend", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "data", ".", "Title", "=", "file", "+", "\"", "\"", "+", "profile", "\n", "data", ".", "Errors", "=", "errList", "\n", "data", ".", "Total", "=", "rpt", ".", "Total", "(", ")", "\n", "data", ".", "SampleTypes", "=", "sampleTypes", "(", "ui", ".", "prof", ")", "\n", "data", ".", "Legend", "=", "legend", "\n", "data", ".", "Help", "=", "ui", ".", "help", "\n", "html", ":=", "&", "bytes", ".", "Buffer", "{", "}", "\n", "if", "err", ":=", "ui", ".", "templates", ".", "ExecuteTemplate", "(", "html", ",", "tmpl", ",", "data", ")", ";", "err", "!=", "nil", "{", "http", ".", "Error", "(", "w", ",", "\"", "\"", ",", "http", ".", "StatusInternalServerError", ")", "\n", "ui", ".", "options", ".", "UI", ".", "PrintErr", "(", "err", ")", "\n", "return", "\n", "}", "\n", "w", ".", "Header", "(", ")", ".", "Set", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "w", ".", "Write", "(", "html", ".", "Bytes", "(", ")", ")", "\n", "}" ]
// render generates html using the named template based on the contents of data.
[ "render", "generates", "html", "using", "the", "named", "template", "based", "on", "the", "contents", "of", "data", "." ]
8358a9778bd1e48718ffcb96eb11ee061385bf62
https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/internal/driver/webui.go#L274-L292
train
google/pprof
internal/driver/webui.go
dot
func (ui *webInterface) dot(w http.ResponseWriter, req *http.Request) { rpt, errList := ui.makeReport(w, req, []string{"svg"}) if rpt == nil { return // error already reported } // Generate dot graph. g, config := report.GetDOT(rpt) legend := config.Labels config.Labels = nil dot := &bytes.Buffer{} graph.ComposeDot(dot, g, &graph.DotAttributes{}, config) // Convert to svg. svg, err := dotToSvg(dot.Bytes()) if err != nil { http.Error(w, "Could not execute dot; may need to install graphviz.", http.StatusNotImplemented) ui.options.UI.PrintErr("Failed to execute dot. Is Graphviz installed?\n", err) return } // Get all node names into an array. nodes := []string{""} // dot starts with node numbered 1 for _, n := range g.Nodes { nodes = append(nodes, n.Info.Name) } ui.render(w, "graph", rpt, errList, legend, webArgs{ HTMLBody: template.HTML(string(svg)), Nodes: nodes, }) }
go
func (ui *webInterface) dot(w http.ResponseWriter, req *http.Request) { rpt, errList := ui.makeReport(w, req, []string{"svg"}) if rpt == nil { return // error already reported } // Generate dot graph. g, config := report.GetDOT(rpt) legend := config.Labels config.Labels = nil dot := &bytes.Buffer{} graph.ComposeDot(dot, g, &graph.DotAttributes{}, config) // Convert to svg. svg, err := dotToSvg(dot.Bytes()) if err != nil { http.Error(w, "Could not execute dot; may need to install graphviz.", http.StatusNotImplemented) ui.options.UI.PrintErr("Failed to execute dot. Is Graphviz installed?\n", err) return } // Get all node names into an array. nodes := []string{""} // dot starts with node numbered 1 for _, n := range g.Nodes { nodes = append(nodes, n.Info.Name) } ui.render(w, "graph", rpt, errList, legend, webArgs{ HTMLBody: template.HTML(string(svg)), Nodes: nodes, }) }
[ "func", "(", "ui", "*", "webInterface", ")", "dot", "(", "w", "http", ".", "ResponseWriter", ",", "req", "*", "http", ".", "Request", ")", "{", "rpt", ",", "errList", ":=", "ui", ".", "makeReport", "(", "w", ",", "req", ",", "[", "]", "string", "{", "\"", "\"", "}", ")", "\n", "if", "rpt", "==", "nil", "{", "return", "// error already reported", "\n", "}", "\n\n", "// Generate dot graph.", "g", ",", "config", ":=", "report", ".", "GetDOT", "(", "rpt", ")", "\n", "legend", ":=", "config", ".", "Labels", "\n", "config", ".", "Labels", "=", "nil", "\n", "dot", ":=", "&", "bytes", ".", "Buffer", "{", "}", "\n", "graph", ".", "ComposeDot", "(", "dot", ",", "g", ",", "&", "graph", ".", "DotAttributes", "{", "}", ",", "config", ")", "\n\n", "// Convert to svg.", "svg", ",", "err", ":=", "dotToSvg", "(", "dot", ".", "Bytes", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "http", ".", "Error", "(", "w", ",", "\"", "\"", ",", "http", ".", "StatusNotImplemented", ")", "\n", "ui", ".", "options", ".", "UI", ".", "PrintErr", "(", "\"", "\\n", "\"", ",", "err", ")", "\n", "return", "\n", "}", "\n\n", "// Get all node names into an array.", "nodes", ":=", "[", "]", "string", "{", "\"", "\"", "}", "// dot starts with node numbered 1", "\n", "for", "_", ",", "n", ":=", "range", "g", ".", "Nodes", "{", "nodes", "=", "append", "(", "nodes", ",", "n", ".", "Info", ".", "Name", ")", "\n", "}", "\n\n", "ui", ".", "render", "(", "w", ",", "\"", "\"", ",", "rpt", ",", "errList", ",", "legend", ",", "webArgs", "{", "HTMLBody", ":", "template", ".", "HTML", "(", "string", "(", "svg", ")", ")", ",", "Nodes", ":", "nodes", ",", "}", ")", "\n", "}" ]
// dot generates a web page containing an svg diagram.
[ "dot", "generates", "a", "web", "page", "containing", "an", "svg", "diagram", "." ]
8358a9778bd1e48718ffcb96eb11ee061385bf62
https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/internal/driver/webui.go#L295-L327
train
google/pprof
internal/driver/webui.go
disasm
func (ui *webInterface) disasm(w http.ResponseWriter, req *http.Request) { args := []string{"disasm", req.URL.Query().Get("f")} rpt, errList := ui.makeReport(w, req, args) if rpt == nil { return // error already reported } out := &bytes.Buffer{} if err := report.PrintAssembly(out, rpt, ui.options.Obj, maxEntries); err != nil { http.Error(w, err.Error(), http.StatusBadRequest) ui.options.UI.PrintErr(err) return } legend := report.ProfileLabels(rpt) ui.render(w, "plaintext", rpt, errList, legend, webArgs{ TextBody: out.String(), }) }
go
func (ui *webInterface) disasm(w http.ResponseWriter, req *http.Request) { args := []string{"disasm", req.URL.Query().Get("f")} rpt, errList := ui.makeReport(w, req, args) if rpt == nil { return // error already reported } out := &bytes.Buffer{} if err := report.PrintAssembly(out, rpt, ui.options.Obj, maxEntries); err != nil { http.Error(w, err.Error(), http.StatusBadRequest) ui.options.UI.PrintErr(err) return } legend := report.ProfileLabels(rpt) ui.render(w, "plaintext", rpt, errList, legend, webArgs{ TextBody: out.String(), }) }
[ "func", "(", "ui", "*", "webInterface", ")", "disasm", "(", "w", "http", ".", "ResponseWriter", ",", "req", "*", "http", ".", "Request", ")", "{", "args", ":=", "[", "]", "string", "{", "\"", "\"", ",", "req", ".", "URL", ".", "Query", "(", ")", ".", "Get", "(", "\"", "\"", ")", "}", "\n", "rpt", ",", "errList", ":=", "ui", ".", "makeReport", "(", "w", ",", "req", ",", "args", ")", "\n", "if", "rpt", "==", "nil", "{", "return", "// error already reported", "\n", "}", "\n\n", "out", ":=", "&", "bytes", ".", "Buffer", "{", "}", "\n", "if", "err", ":=", "report", ".", "PrintAssembly", "(", "out", ",", "rpt", ",", "ui", ".", "options", ".", "Obj", ",", "maxEntries", ")", ";", "err", "!=", "nil", "{", "http", ".", "Error", "(", "w", ",", "err", ".", "Error", "(", ")", ",", "http", ".", "StatusBadRequest", ")", "\n", "ui", ".", "options", ".", "UI", ".", "PrintErr", "(", "err", ")", "\n", "return", "\n", "}", "\n\n", "legend", ":=", "report", ".", "ProfileLabels", "(", "rpt", ")", "\n", "ui", ".", "render", "(", "w", ",", "\"", "\"", ",", "rpt", ",", "errList", ",", "legend", ",", "webArgs", "{", "TextBody", ":", "out", ".", "String", "(", ")", ",", "}", ")", "\n\n", "}" ]
// disasm generates a web page containing disassembly.
[ "disasm", "generates", "a", "web", "page", "containing", "disassembly", "." ]
8358a9778bd1e48718ffcb96eb11ee061385bf62
https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/internal/driver/webui.go#L365-L384
train
google/pprof
internal/driver/webui.go
source
func (ui *webInterface) source(w http.ResponseWriter, req *http.Request) { args := []string{"weblist", req.URL.Query().Get("f")} rpt, errList := ui.makeReport(w, req, args) if rpt == nil { return // error already reported } // Generate source listing. var body bytes.Buffer if err := report.PrintWebList(&body, rpt, ui.options.Obj, maxEntries); err != nil { http.Error(w, err.Error(), http.StatusBadRequest) ui.options.UI.PrintErr(err) return } legend := report.ProfileLabels(rpt) ui.render(w, "sourcelisting", rpt, errList, legend, webArgs{ HTMLBody: template.HTML(body.String()), }) }
go
func (ui *webInterface) source(w http.ResponseWriter, req *http.Request) { args := []string{"weblist", req.URL.Query().Get("f")} rpt, errList := ui.makeReport(w, req, args) if rpt == nil { return // error already reported } // Generate source listing. var body bytes.Buffer if err := report.PrintWebList(&body, rpt, ui.options.Obj, maxEntries); err != nil { http.Error(w, err.Error(), http.StatusBadRequest) ui.options.UI.PrintErr(err) return } legend := report.ProfileLabels(rpt) ui.render(w, "sourcelisting", rpt, errList, legend, webArgs{ HTMLBody: template.HTML(body.String()), }) }
[ "func", "(", "ui", "*", "webInterface", ")", "source", "(", "w", "http", ".", "ResponseWriter", ",", "req", "*", "http", ".", "Request", ")", "{", "args", ":=", "[", "]", "string", "{", "\"", "\"", ",", "req", ".", "URL", ".", "Query", "(", ")", ".", "Get", "(", "\"", "\"", ")", "}", "\n", "rpt", ",", "errList", ":=", "ui", ".", "makeReport", "(", "w", ",", "req", ",", "args", ")", "\n", "if", "rpt", "==", "nil", "{", "return", "// error already reported", "\n", "}", "\n\n", "// Generate source listing.", "var", "body", "bytes", ".", "Buffer", "\n", "if", "err", ":=", "report", ".", "PrintWebList", "(", "&", "body", ",", "rpt", ",", "ui", ".", "options", ".", "Obj", ",", "maxEntries", ")", ";", "err", "!=", "nil", "{", "http", ".", "Error", "(", "w", ",", "err", ".", "Error", "(", ")", ",", "http", ".", "StatusBadRequest", ")", "\n", "ui", ".", "options", ".", "UI", ".", "PrintErr", "(", "err", ")", "\n", "return", "\n", "}", "\n\n", "legend", ":=", "report", ".", "ProfileLabels", "(", "rpt", ")", "\n", "ui", ".", "render", "(", "w", ",", "\"", "\"", ",", "rpt", ",", "errList", ",", "legend", ",", "webArgs", "{", "HTMLBody", ":", "template", ".", "HTML", "(", "body", ".", "String", "(", ")", ")", ",", "}", ")", "\n", "}" ]
// source generates a web page containing source code annotated with profile // data.
[ "source", "generates", "a", "web", "page", "containing", "source", "code", "annotated", "with", "profile", "data", "." ]
8358a9778bd1e48718ffcb96eb11ee061385bf62
https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/internal/driver/webui.go#L388-L407
train
google/pprof
internal/driver/webui.go
getFromLegend
func getFromLegend(legend []string, param, def string) string { for _, s := range legend { if strings.HasPrefix(s, param) { return s[len(param):] } } return def }
go
func getFromLegend(legend []string, param, def string) string { for _, s := range legend { if strings.HasPrefix(s, param) { return s[len(param):] } } return def }
[ "func", "getFromLegend", "(", "legend", "[", "]", "string", ",", "param", ",", "def", "string", ")", "string", "{", "for", "_", ",", "s", ":=", "range", "legend", "{", "if", "strings", ".", "HasPrefix", "(", "s", ",", "param", ")", "{", "return", "s", "[", "len", "(", "param", ")", ":", "]", "\n", "}", "\n", "}", "\n", "return", "def", "\n", "}" ]
// getFromLegend returns the suffix of an entry in legend that starts // with param. It returns def if no such entry is found.
[ "getFromLegend", "returns", "the", "suffix", "of", "an", "entry", "in", "legend", "that", "starts", "with", "param", ".", "It", "returns", "def", "if", "no", "such", "entry", "is", "found", "." ]
8358a9778bd1e48718ffcb96eb11ee061385bf62
https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/internal/driver/webui.go#L432-L439
train
google/pprof
pprof.go
Print
func (r *readlineUI) Print(args ...interface{}) { text := fmt.Sprint(args...) if !strings.HasSuffix(text, "\n") { text += "\n" } fmt.Fprint(r.rl.Stderr(), text) }
go
func (r *readlineUI) Print(args ...interface{}) { text := fmt.Sprint(args...) if !strings.HasSuffix(text, "\n") { text += "\n" } fmt.Fprint(r.rl.Stderr(), text) }
[ "func", "(", "r", "*", "readlineUI", ")", "Print", "(", "args", "...", "interface", "{", "}", ")", "{", "text", ":=", "fmt", ".", "Sprint", "(", "args", "...", ")", "\n", "if", "!", "strings", ".", "HasSuffix", "(", "text", ",", "\"", "\\n", "\"", ")", "{", "text", "+=", "\"", "\\n", "\"", "\n", "}", "\n", "fmt", ".", "Fprint", "(", "r", ".", "rl", ".", "Stderr", "(", ")", ",", "text", ")", "\n", "}" ]
// Print shows a message to the user. // It is printed over stderr as stdout is reserved for regular output.
[ "Print", "shows", "a", "message", "to", "the", "user", ".", "It", "is", "printed", "over", "stderr", "as", "stdout", "is", "reserved", "for", "regular", "output", "." ]
8358a9778bd1e48718ffcb96eb11ee061385bf62
https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/pprof.go#L65-L71
train
google/pprof
pprof.go
PrintErr
func (r *readlineUI) PrintErr(args ...interface{}) { text := fmt.Sprint(args...) if !strings.HasSuffix(text, "\n") { text += "\n" } if readline.IsTerminal(int(syscall.Stderr)) { text = colorize(text) } fmt.Fprint(r.rl.Stderr(), text) }
go
func (r *readlineUI) PrintErr(args ...interface{}) { text := fmt.Sprint(args...) if !strings.HasSuffix(text, "\n") { text += "\n" } if readline.IsTerminal(int(syscall.Stderr)) { text = colorize(text) } fmt.Fprint(r.rl.Stderr(), text) }
[ "func", "(", "r", "*", "readlineUI", ")", "PrintErr", "(", "args", "...", "interface", "{", "}", ")", "{", "text", ":=", "fmt", ".", "Sprint", "(", "args", "...", ")", "\n", "if", "!", "strings", ".", "HasSuffix", "(", "text", ",", "\"", "\\n", "\"", ")", "{", "text", "+=", "\"", "\\n", "\"", "\n", "}", "\n", "if", "readline", ".", "IsTerminal", "(", "int", "(", "syscall", ".", "Stderr", ")", ")", "{", "text", "=", "colorize", "(", "text", ")", "\n", "}", "\n", "fmt", ".", "Fprint", "(", "r", ".", "rl", ".", "Stderr", "(", ")", ",", "text", ")", "\n", "}" ]
// PrintErr shows a message to the user, colored in red for emphasis. // It is printed over stderr as stdout is reserved for regular output.
[ "PrintErr", "shows", "a", "message", "to", "the", "user", "colored", "in", "red", "for", "emphasis", ".", "It", "is", "printed", "over", "stderr", "as", "stdout", "is", "reserved", "for", "regular", "output", "." ]
8358a9778bd1e48718ffcb96eb11ee061385bf62
https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/pprof.go#L75-L84
train
google/pprof
pprof.go
colorize
func colorize(msg string) string { var red = 31 var colorEscape = fmt.Sprintf("\033[0;%dm", red) var colorResetEscape = "\033[0m" return colorEscape + msg + colorResetEscape }
go
func colorize(msg string) string { var red = 31 var colorEscape = fmt.Sprintf("\033[0;%dm", red) var colorResetEscape = "\033[0m" return colorEscape + msg + colorResetEscape }
[ "func", "colorize", "(", "msg", "string", ")", "string", "{", "var", "red", "=", "31", "\n", "var", "colorEscape", "=", "fmt", ".", "Sprintf", "(", "\"", "\\033", "\"", ",", "red", ")", "\n", "var", "colorResetEscape", "=", "\"", "\\033", "\"", "\n", "return", "colorEscape", "+", "msg", "+", "colorResetEscape", "\n", "}" ]
// colorize the msg using ANSI color escapes.
[ "colorize", "the", "msg", "using", "ANSI", "color", "escapes", "." ]
8358a9778bd1e48718ffcb96eb11ee061385bf62
https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/pprof.go#L87-L92
train
google/pprof
internal/graph/dotgraph.go
ComposeDot
func ComposeDot(w io.Writer, g *Graph, a *DotAttributes, c *DotConfig) { builder := &builder{w, a, c} // Begin constructing DOT by adding a title and legend. builder.start() defer builder.finish() builder.addLegend() if len(g.Nodes) == 0 { return } // Preprocess graph to get id map and find max flat. nodeIDMap := make(map[*Node]int) hasNodelets := make(map[*Node]bool) maxFlat := float64(abs64(g.Nodes[0].FlatValue())) for i, n := range g.Nodes { nodeIDMap[n] = i + 1 if float64(abs64(n.FlatValue())) > maxFlat { maxFlat = float64(abs64(n.FlatValue())) } } edges := EdgeMap{} // Add nodes and nodelets to DOT builder. for _, n := range g.Nodes { builder.addNode(n, nodeIDMap[n], maxFlat) hasNodelets[n] = builder.addNodelets(n, nodeIDMap[n]) // Collect all edges. Use a fake node to support multiple incoming edges. for _, e := range n.Out { edges[&Node{}] = e } } // Add edges to DOT builder. Sort edges by frequency as a hint to the graph layout engine. for _, e := range edges.Sort() { builder.addEdge(e, nodeIDMap[e.Src], nodeIDMap[e.Dest], hasNodelets[e.Src]) } }
go
func ComposeDot(w io.Writer, g *Graph, a *DotAttributes, c *DotConfig) { builder := &builder{w, a, c} // Begin constructing DOT by adding a title and legend. builder.start() defer builder.finish() builder.addLegend() if len(g.Nodes) == 0 { return } // Preprocess graph to get id map and find max flat. nodeIDMap := make(map[*Node]int) hasNodelets := make(map[*Node]bool) maxFlat := float64(abs64(g.Nodes[0].FlatValue())) for i, n := range g.Nodes { nodeIDMap[n] = i + 1 if float64(abs64(n.FlatValue())) > maxFlat { maxFlat = float64(abs64(n.FlatValue())) } } edges := EdgeMap{} // Add nodes and nodelets to DOT builder. for _, n := range g.Nodes { builder.addNode(n, nodeIDMap[n], maxFlat) hasNodelets[n] = builder.addNodelets(n, nodeIDMap[n]) // Collect all edges. Use a fake node to support multiple incoming edges. for _, e := range n.Out { edges[&Node{}] = e } } // Add edges to DOT builder. Sort edges by frequency as a hint to the graph layout engine. for _, e := range edges.Sort() { builder.addEdge(e, nodeIDMap[e.Src], nodeIDMap[e.Dest], hasNodelets[e.Src]) } }
[ "func", "ComposeDot", "(", "w", "io", ".", "Writer", ",", "g", "*", "Graph", ",", "a", "*", "DotAttributes", ",", "c", "*", "DotConfig", ")", "{", "builder", ":=", "&", "builder", "{", "w", ",", "a", ",", "c", "}", "\n\n", "// Begin constructing DOT by adding a title and legend.", "builder", ".", "start", "(", ")", "\n", "defer", "builder", ".", "finish", "(", ")", "\n", "builder", ".", "addLegend", "(", ")", "\n\n", "if", "len", "(", "g", ".", "Nodes", ")", "==", "0", "{", "return", "\n", "}", "\n\n", "// Preprocess graph to get id map and find max flat.", "nodeIDMap", ":=", "make", "(", "map", "[", "*", "Node", "]", "int", ")", "\n", "hasNodelets", ":=", "make", "(", "map", "[", "*", "Node", "]", "bool", ")", "\n\n", "maxFlat", ":=", "float64", "(", "abs64", "(", "g", ".", "Nodes", "[", "0", "]", ".", "FlatValue", "(", ")", ")", ")", "\n", "for", "i", ",", "n", ":=", "range", "g", ".", "Nodes", "{", "nodeIDMap", "[", "n", "]", "=", "i", "+", "1", "\n", "if", "float64", "(", "abs64", "(", "n", ".", "FlatValue", "(", ")", ")", ")", ">", "maxFlat", "{", "maxFlat", "=", "float64", "(", "abs64", "(", "n", ".", "FlatValue", "(", ")", ")", ")", "\n", "}", "\n", "}", "\n\n", "edges", ":=", "EdgeMap", "{", "}", "\n\n", "// Add nodes and nodelets to DOT builder.", "for", "_", ",", "n", ":=", "range", "g", ".", "Nodes", "{", "builder", ".", "addNode", "(", "n", ",", "nodeIDMap", "[", "n", "]", ",", "maxFlat", ")", "\n", "hasNodelets", "[", "n", "]", "=", "builder", ".", "addNodelets", "(", "n", ",", "nodeIDMap", "[", "n", "]", ")", "\n\n", "// Collect all edges. Use a fake node to support multiple incoming edges.", "for", "_", ",", "e", ":=", "range", "n", ".", "Out", "{", "edges", "[", "&", "Node", "{", "}", "]", "=", "e", "\n", "}", "\n", "}", "\n\n", "// Add edges to DOT builder. Sort edges by frequency as a hint to the graph layout engine.", "for", "_", ",", "e", ":=", "range", "edges", ".", "Sort", "(", ")", "{", "builder", ".", "addEdge", "(", "e", ",", "nodeIDMap", "[", "e", ".", "Src", "]", ",", "nodeIDMap", "[", "e", ".", "Dest", "]", ",", "hasNodelets", "[", "e", ".", "Src", "]", ")", "\n", "}", "\n", "}" ]
// ComposeDot creates and writes a in the DOT format to the writer, using // the configurations given.
[ "ComposeDot", "creates", "and", "writes", "a", "in", "the", "DOT", "format", "to", "the", "writer", "using", "the", "configurations", "given", "." ]
8358a9778bd1e48718ffcb96eb11ee061385bf62
https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/internal/graph/dotgraph.go#L57-L98
train
google/pprof
internal/graph/dotgraph.go
start
func (b *builder) start() { graphname := "unnamed" if b.config.Title != "" { graphname = b.config.Title } fmt.Fprintln(b, `digraph "`+graphname+`" {`) fmt.Fprintln(b, `node [style=filled fillcolor="#f8f8f8"]`) }
go
func (b *builder) start() { graphname := "unnamed" if b.config.Title != "" { graphname = b.config.Title } fmt.Fprintln(b, `digraph "`+graphname+`" {`) fmt.Fprintln(b, `node [style=filled fillcolor="#f8f8f8"]`) }
[ "func", "(", "b", "*", "builder", ")", "start", "(", ")", "{", "graphname", ":=", "\"", "\"", "\n", "if", "b", ".", "config", ".", "Title", "!=", "\"", "\"", "{", "graphname", "=", "b", ".", "config", ".", "Title", "\n", "}", "\n", "fmt", ".", "Fprintln", "(", "b", ",", "`digraph \"`", "+", "graphname", "+", "`\" {`", ")", "\n", "fmt", ".", "Fprintln", "(", "b", ",", "`node [style=filled fillcolor=\"#f8f8f8\"]`", ")", "\n", "}" ]
// start generates a title and initial node in DOT format.
[ "start", "generates", "a", "title", "and", "initial", "node", "in", "DOT", "format", "." ]
8358a9778bd1e48718ffcb96eb11ee061385bf62
https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/internal/graph/dotgraph.go#L108-L115
train
google/pprof
internal/graph/dotgraph.go
addLegend
func (b *builder) addLegend() { labels := b.config.Labels if len(labels) == 0 { return } title := labels[0] fmt.Fprintf(b, `subgraph cluster_L { "%s" [shape=box fontsize=16`, title) fmt.Fprintf(b, ` label="%s\l"`, strings.Join(labels, `\l`)) if b.config.LegendURL != "" { fmt.Fprintf(b, ` URL="%s" target="_blank"`, b.config.LegendURL) } if b.config.Title != "" { fmt.Fprintf(b, ` tooltip="%s"`, b.config.Title) } fmt.Fprintf(b, "] }\n") }
go
func (b *builder) addLegend() { labels := b.config.Labels if len(labels) == 0 { return } title := labels[0] fmt.Fprintf(b, `subgraph cluster_L { "%s" [shape=box fontsize=16`, title) fmt.Fprintf(b, ` label="%s\l"`, strings.Join(labels, `\l`)) if b.config.LegendURL != "" { fmt.Fprintf(b, ` URL="%s" target="_blank"`, b.config.LegendURL) } if b.config.Title != "" { fmt.Fprintf(b, ` tooltip="%s"`, b.config.Title) } fmt.Fprintf(b, "] }\n") }
[ "func", "(", "b", "*", "builder", ")", "addLegend", "(", ")", "{", "labels", ":=", "b", ".", "config", ".", "Labels", "\n", "if", "len", "(", "labels", ")", "==", "0", "{", "return", "\n", "}", "\n", "title", ":=", "labels", "[", "0", "]", "\n", "fmt", ".", "Fprintf", "(", "b", ",", "`subgraph cluster_L { \"%s\" [shape=box fontsize=16`", ",", "title", ")", "\n", "fmt", ".", "Fprintf", "(", "b", ",", "` label=\"%s\\l\"`", ",", "strings", ".", "Join", "(", "labels", ",", "`\\l`", ")", ")", "\n", "if", "b", ".", "config", ".", "LegendURL", "!=", "\"", "\"", "{", "fmt", ".", "Fprintf", "(", "b", ",", "` URL=\"%s\" target=\"_blank\"`", ",", "b", ".", "config", ".", "LegendURL", ")", "\n", "}", "\n", "if", "b", ".", "config", ".", "Title", "!=", "\"", "\"", "{", "fmt", ".", "Fprintf", "(", "b", ",", "` tooltip=\"%s\"`", ",", "b", ".", "config", ".", "Title", ")", "\n", "}", "\n", "fmt", ".", "Fprintf", "(", "b", ",", "\"", "\\n", "\"", ")", "\n", "}" ]
// addLegend generates a legend in DOT format.
[ "addLegend", "generates", "a", "legend", "in", "DOT", "format", "." ]
8358a9778bd1e48718ffcb96eb11ee061385bf62
https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/internal/graph/dotgraph.go#L123-L138
train
google/pprof
internal/graph/dotgraph.go
addNode
func (b *builder) addNode(node *Node, nodeID int, maxFlat float64) { flat, cum := node.FlatValue(), node.CumValue() attrs := b.attributes.Nodes[node] // Populate label for node. var label string if attrs != nil && attrs.Formatter != nil { label = attrs.Formatter(&node.Info) } else { label = multilinePrintableName(&node.Info) } flatValue := b.config.FormatValue(flat) if flat != 0 { label = label + fmt.Sprintf(`%s (%s)`, flatValue, strings.TrimSpace(measurement.Percentage(flat, b.config.Total))) } else { label = label + "0" } cumValue := flatValue if cum != flat { if flat != 0 { label = label + `\n` } else { label = label + " " } cumValue = b.config.FormatValue(cum) label = label + fmt.Sprintf(`of %s (%s)`, cumValue, strings.TrimSpace(measurement.Percentage(cum, b.config.Total))) } // Scale font sizes from 8 to 24 based on percentage of flat frequency. // Use non linear growth to emphasize the size difference. baseFontSize, maxFontGrowth := 8, 16.0 fontSize := baseFontSize if maxFlat != 0 && flat != 0 && float64(abs64(flat)) <= maxFlat { fontSize += int(math.Ceil(maxFontGrowth * math.Sqrt(float64(abs64(flat))/maxFlat))) } // Determine node shape. shape := "box" if attrs != nil && attrs.Shape != "" { shape = attrs.Shape } // Create DOT attribute for node. attr := fmt.Sprintf(`label="%s" id="node%d" fontsize=%d shape=%s tooltip="%s (%s)" color="%s" fillcolor="%s"`, label, nodeID, fontSize, shape, node.Info.PrintableName(), cumValue, dotColor(float64(node.CumValue())/float64(abs64(b.config.Total)), false), dotColor(float64(node.CumValue())/float64(abs64(b.config.Total)), true)) // Add on extra attributes if provided. if attrs != nil { // Make bold if specified. if attrs.Bold { attr += ` style="bold,filled"` } // Add peripheries if specified. if attrs.Peripheries != 0 { attr += fmt.Sprintf(` peripheries=%d`, attrs.Peripheries) } // Add URL if specified. target="_blank" forces the link to open in a new tab. if attrs.URL != "" { attr += fmt.Sprintf(` URL="%s" target="_blank"`, attrs.URL) } } fmt.Fprintf(b, "N%d [%s]\n", nodeID, attr) }
go
func (b *builder) addNode(node *Node, nodeID int, maxFlat float64) { flat, cum := node.FlatValue(), node.CumValue() attrs := b.attributes.Nodes[node] // Populate label for node. var label string if attrs != nil && attrs.Formatter != nil { label = attrs.Formatter(&node.Info) } else { label = multilinePrintableName(&node.Info) } flatValue := b.config.FormatValue(flat) if flat != 0 { label = label + fmt.Sprintf(`%s (%s)`, flatValue, strings.TrimSpace(measurement.Percentage(flat, b.config.Total))) } else { label = label + "0" } cumValue := flatValue if cum != flat { if flat != 0 { label = label + `\n` } else { label = label + " " } cumValue = b.config.FormatValue(cum) label = label + fmt.Sprintf(`of %s (%s)`, cumValue, strings.TrimSpace(measurement.Percentage(cum, b.config.Total))) } // Scale font sizes from 8 to 24 based on percentage of flat frequency. // Use non linear growth to emphasize the size difference. baseFontSize, maxFontGrowth := 8, 16.0 fontSize := baseFontSize if maxFlat != 0 && flat != 0 && float64(abs64(flat)) <= maxFlat { fontSize += int(math.Ceil(maxFontGrowth * math.Sqrt(float64(abs64(flat))/maxFlat))) } // Determine node shape. shape := "box" if attrs != nil && attrs.Shape != "" { shape = attrs.Shape } // Create DOT attribute for node. attr := fmt.Sprintf(`label="%s" id="node%d" fontsize=%d shape=%s tooltip="%s (%s)" color="%s" fillcolor="%s"`, label, nodeID, fontSize, shape, node.Info.PrintableName(), cumValue, dotColor(float64(node.CumValue())/float64(abs64(b.config.Total)), false), dotColor(float64(node.CumValue())/float64(abs64(b.config.Total)), true)) // Add on extra attributes if provided. if attrs != nil { // Make bold if specified. if attrs.Bold { attr += ` style="bold,filled"` } // Add peripheries if specified. if attrs.Peripheries != 0 { attr += fmt.Sprintf(` peripheries=%d`, attrs.Peripheries) } // Add URL if specified. target="_blank" forces the link to open in a new tab. if attrs.URL != "" { attr += fmt.Sprintf(` URL="%s" target="_blank"`, attrs.URL) } } fmt.Fprintf(b, "N%d [%s]\n", nodeID, attr) }
[ "func", "(", "b", "*", "builder", ")", "addNode", "(", "node", "*", "Node", ",", "nodeID", "int", ",", "maxFlat", "float64", ")", "{", "flat", ",", "cum", ":=", "node", ".", "FlatValue", "(", ")", ",", "node", ".", "CumValue", "(", ")", "\n", "attrs", ":=", "b", ".", "attributes", ".", "Nodes", "[", "node", "]", "\n\n", "// Populate label for node.", "var", "label", "string", "\n", "if", "attrs", "!=", "nil", "&&", "attrs", ".", "Formatter", "!=", "nil", "{", "label", "=", "attrs", ".", "Formatter", "(", "&", "node", ".", "Info", ")", "\n", "}", "else", "{", "label", "=", "multilinePrintableName", "(", "&", "node", ".", "Info", ")", "\n", "}", "\n\n", "flatValue", ":=", "b", ".", "config", ".", "FormatValue", "(", "flat", ")", "\n", "if", "flat", "!=", "0", "{", "label", "=", "label", "+", "fmt", ".", "Sprintf", "(", "`%s (%s)`", ",", "flatValue", ",", "strings", ".", "TrimSpace", "(", "measurement", ".", "Percentage", "(", "flat", ",", "b", ".", "config", ".", "Total", ")", ")", ")", "\n", "}", "else", "{", "label", "=", "label", "+", "\"", "\"", "\n", "}", "\n", "cumValue", ":=", "flatValue", "\n", "if", "cum", "!=", "flat", "{", "if", "flat", "!=", "0", "{", "label", "=", "label", "+", "`\\n`", "\n", "}", "else", "{", "label", "=", "label", "+", "\"", "\"", "\n", "}", "\n", "cumValue", "=", "b", ".", "config", ".", "FormatValue", "(", "cum", ")", "\n", "label", "=", "label", "+", "fmt", ".", "Sprintf", "(", "`of %s (%s)`", ",", "cumValue", ",", "strings", ".", "TrimSpace", "(", "measurement", ".", "Percentage", "(", "cum", ",", "b", ".", "config", ".", "Total", ")", ")", ")", "\n", "}", "\n\n", "// Scale font sizes from 8 to 24 based on percentage of flat frequency.", "// Use non linear growth to emphasize the size difference.", "baseFontSize", ",", "maxFontGrowth", ":=", "8", ",", "16.0", "\n", "fontSize", ":=", "baseFontSize", "\n", "if", "maxFlat", "!=", "0", "&&", "flat", "!=", "0", "&&", "float64", "(", "abs64", "(", "flat", ")", ")", "<=", "maxFlat", "{", "fontSize", "+=", "int", "(", "math", ".", "Ceil", "(", "maxFontGrowth", "*", "math", ".", "Sqrt", "(", "float64", "(", "abs64", "(", "flat", ")", ")", "/", "maxFlat", ")", ")", ")", "\n", "}", "\n\n", "// Determine node shape.", "shape", ":=", "\"", "\"", "\n", "if", "attrs", "!=", "nil", "&&", "attrs", ".", "Shape", "!=", "\"", "\"", "{", "shape", "=", "attrs", ".", "Shape", "\n", "}", "\n\n", "// Create DOT attribute for node.", "attr", ":=", "fmt", ".", "Sprintf", "(", "`label=\"%s\" id=\"node%d\" fontsize=%d shape=%s tooltip=\"%s (%s)\" color=\"%s\" fillcolor=\"%s\"`", ",", "label", ",", "nodeID", ",", "fontSize", ",", "shape", ",", "node", ".", "Info", ".", "PrintableName", "(", ")", ",", "cumValue", ",", "dotColor", "(", "float64", "(", "node", ".", "CumValue", "(", ")", ")", "/", "float64", "(", "abs64", "(", "b", ".", "config", ".", "Total", ")", ")", ",", "false", ")", ",", "dotColor", "(", "float64", "(", "node", ".", "CumValue", "(", ")", ")", "/", "float64", "(", "abs64", "(", "b", ".", "config", ".", "Total", ")", ")", ",", "true", ")", ")", "\n\n", "// Add on extra attributes if provided.", "if", "attrs", "!=", "nil", "{", "// Make bold if specified.", "if", "attrs", ".", "Bold", "{", "attr", "+=", "` style=\"bold,filled\"`", "\n", "}", "\n\n", "// Add peripheries if specified.", "if", "attrs", ".", "Peripheries", "!=", "0", "{", "attr", "+=", "fmt", ".", "Sprintf", "(", "` peripheries=%d`", ",", "attrs", ".", "Peripheries", ")", "\n", "}", "\n\n", "// Add URL if specified. target=\"_blank\" forces the link to open in a new tab.", "if", "attrs", ".", "URL", "!=", "\"", "\"", "{", "attr", "+=", "fmt", ".", "Sprintf", "(", "` URL=\"%s\" target=\"_blank\"`", ",", "attrs", ".", "URL", ")", "\n", "}", "\n", "}", "\n\n", "fmt", ".", "Fprintf", "(", "b", ",", "\"", "\\n", "\"", ",", "nodeID", ",", "attr", ")", "\n", "}" ]
// addNode generates a graph node in DOT format.
[ "addNode", "generates", "a", "graph", "node", "in", "DOT", "format", "." ]
8358a9778bd1e48718ffcb96eb11ee061385bf62
https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/internal/graph/dotgraph.go#L141-L213
train
google/pprof
internal/graph/dotgraph.go
addNodelets
func (b *builder) addNodelets(node *Node, nodeID int) bool { var nodelets string // Populate two Tag slices, one for LabelTags and one for NumericTags. var ts []*Tag lnts := make(map[string][]*Tag) for _, t := range node.LabelTags { ts = append(ts, t) } for l, tm := range node.NumericTags { for _, t := range tm { lnts[l] = append(lnts[l], t) } } // For leaf nodes, print cumulative tags (includes weight from // children that have been deleted). // For internal nodes, print only flat tags. flatTags := len(node.Out) > 0 // Select the top maxNodelets alphanumeric labels by weight. SortTags(ts, flatTags) if len(ts) > maxNodelets { ts = ts[:maxNodelets] } for i, t := range ts { w := t.CumValue() if flatTags { w = t.FlatValue() } if w == 0 { continue } weight := b.config.FormatValue(w) nodelets += fmt.Sprintf(`N%d_%d [label = "%s" id="N%d_%d" fontsize=8 shape=box3d tooltip="%s"]`+"\n", nodeID, i, t.Name, nodeID, i, weight) nodelets += fmt.Sprintf(`N%d -> N%d_%d [label=" %s" weight=100 tooltip="%s" labeltooltip="%s"]`+"\n", nodeID, nodeID, i, weight, weight, weight) if nts := lnts[t.Name]; nts != nil { nodelets += b.numericNodelets(nts, maxNodelets, flatTags, fmt.Sprintf(`N%d_%d`, nodeID, i)) } } if nts := lnts[""]; nts != nil { nodelets += b.numericNodelets(nts, maxNodelets, flatTags, fmt.Sprintf(`N%d`, nodeID)) } fmt.Fprint(b, nodelets) return nodelets != "" }
go
func (b *builder) addNodelets(node *Node, nodeID int) bool { var nodelets string // Populate two Tag slices, one for LabelTags and one for NumericTags. var ts []*Tag lnts := make(map[string][]*Tag) for _, t := range node.LabelTags { ts = append(ts, t) } for l, tm := range node.NumericTags { for _, t := range tm { lnts[l] = append(lnts[l], t) } } // For leaf nodes, print cumulative tags (includes weight from // children that have been deleted). // For internal nodes, print only flat tags. flatTags := len(node.Out) > 0 // Select the top maxNodelets alphanumeric labels by weight. SortTags(ts, flatTags) if len(ts) > maxNodelets { ts = ts[:maxNodelets] } for i, t := range ts { w := t.CumValue() if flatTags { w = t.FlatValue() } if w == 0 { continue } weight := b.config.FormatValue(w) nodelets += fmt.Sprintf(`N%d_%d [label = "%s" id="N%d_%d" fontsize=8 shape=box3d tooltip="%s"]`+"\n", nodeID, i, t.Name, nodeID, i, weight) nodelets += fmt.Sprintf(`N%d -> N%d_%d [label=" %s" weight=100 tooltip="%s" labeltooltip="%s"]`+"\n", nodeID, nodeID, i, weight, weight, weight) if nts := lnts[t.Name]; nts != nil { nodelets += b.numericNodelets(nts, maxNodelets, flatTags, fmt.Sprintf(`N%d_%d`, nodeID, i)) } } if nts := lnts[""]; nts != nil { nodelets += b.numericNodelets(nts, maxNodelets, flatTags, fmt.Sprintf(`N%d`, nodeID)) } fmt.Fprint(b, nodelets) return nodelets != "" }
[ "func", "(", "b", "*", "builder", ")", "addNodelets", "(", "node", "*", "Node", ",", "nodeID", "int", ")", "bool", "{", "var", "nodelets", "string", "\n\n", "// Populate two Tag slices, one for LabelTags and one for NumericTags.", "var", "ts", "[", "]", "*", "Tag", "\n", "lnts", ":=", "make", "(", "map", "[", "string", "]", "[", "]", "*", "Tag", ")", "\n", "for", "_", ",", "t", ":=", "range", "node", ".", "LabelTags", "{", "ts", "=", "append", "(", "ts", ",", "t", ")", "\n", "}", "\n", "for", "l", ",", "tm", ":=", "range", "node", ".", "NumericTags", "{", "for", "_", ",", "t", ":=", "range", "tm", "{", "lnts", "[", "l", "]", "=", "append", "(", "lnts", "[", "l", "]", ",", "t", ")", "\n", "}", "\n", "}", "\n\n", "// For leaf nodes, print cumulative tags (includes weight from", "// children that have been deleted).", "// For internal nodes, print only flat tags.", "flatTags", ":=", "len", "(", "node", ".", "Out", ")", ">", "0", "\n\n", "// Select the top maxNodelets alphanumeric labels by weight.", "SortTags", "(", "ts", ",", "flatTags", ")", "\n", "if", "len", "(", "ts", ")", ">", "maxNodelets", "{", "ts", "=", "ts", "[", ":", "maxNodelets", "]", "\n", "}", "\n", "for", "i", ",", "t", ":=", "range", "ts", "{", "w", ":=", "t", ".", "CumValue", "(", ")", "\n", "if", "flatTags", "{", "w", "=", "t", ".", "FlatValue", "(", ")", "\n", "}", "\n", "if", "w", "==", "0", "{", "continue", "\n", "}", "\n", "weight", ":=", "b", ".", "config", ".", "FormatValue", "(", "w", ")", "\n", "nodelets", "+=", "fmt", ".", "Sprintf", "(", "`N%d_%d [label = \"%s\" id=\"N%d_%d\" fontsize=8 shape=box3d tooltip=\"%s\"]`", "+", "\"", "\\n", "\"", ",", "nodeID", ",", "i", ",", "t", ".", "Name", ",", "nodeID", ",", "i", ",", "weight", ")", "\n", "nodelets", "+=", "fmt", ".", "Sprintf", "(", "`N%d -> N%d_%d [label=\" %s\" weight=100 tooltip=\"%s\" labeltooltip=\"%s\"]`", "+", "\"", "\\n", "\"", ",", "nodeID", ",", "nodeID", ",", "i", ",", "weight", ",", "weight", ",", "weight", ")", "\n", "if", "nts", ":=", "lnts", "[", "t", ".", "Name", "]", ";", "nts", "!=", "nil", "{", "nodelets", "+=", "b", ".", "numericNodelets", "(", "nts", ",", "maxNodelets", ",", "flatTags", ",", "fmt", ".", "Sprintf", "(", "`N%d_%d`", ",", "nodeID", ",", "i", ")", ")", "\n", "}", "\n", "}", "\n\n", "if", "nts", ":=", "lnts", "[", "\"", "\"", "]", ";", "nts", "!=", "nil", "{", "nodelets", "+=", "b", ".", "numericNodelets", "(", "nts", ",", "maxNodelets", ",", "flatTags", ",", "fmt", ".", "Sprintf", "(", "`N%d`", ",", "nodeID", ")", ")", "\n", "}", "\n\n", "fmt", ".", "Fprint", "(", "b", ",", "nodelets", ")", "\n", "return", "nodelets", "!=", "\"", "\"", "\n", "}" ]
// addNodelets generates the DOT boxes for the node tags if they exist.
[ "addNodelets", "generates", "the", "DOT", "boxes", "for", "the", "node", "tags", "if", "they", "exist", "." ]
8358a9778bd1e48718ffcb96eb11ee061385bf62
https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/internal/graph/dotgraph.go#L216-L263
train
google/pprof
internal/graph/dotgraph.go
addEdge
func (b *builder) addEdge(edge *Edge, from, to int, hasNodelets bool) { var inline string if edge.Inline { inline = `\n (inline)` } w := b.config.FormatValue(edge.WeightValue()) attr := fmt.Sprintf(`label=" %s%s"`, w, inline) if b.config.Total != 0 { // Note: edge.weight > b.config.Total is possible for profile diffs. if weight := 1 + int(min64(abs64(edge.WeightValue()*100/b.config.Total), 100)); weight > 1 { attr = fmt.Sprintf(`%s weight=%d`, attr, weight) } if width := 1 + int(min64(abs64(edge.WeightValue()*5/b.config.Total), 5)); width > 1 { attr = fmt.Sprintf(`%s penwidth=%d`, attr, width) } attr = fmt.Sprintf(`%s color="%s"`, attr, dotColor(float64(edge.WeightValue())/float64(abs64(b.config.Total)), false)) } arrow := "->" if edge.Residual { arrow = "..." } tooltip := fmt.Sprintf(`"%s %s %s (%s)"`, edge.Src.Info.PrintableName(), arrow, edge.Dest.Info.PrintableName(), w) attr = fmt.Sprintf(`%s tooltip=%s labeltooltip=%s`, attr, tooltip, tooltip) if edge.Residual { attr = attr + ` style="dotted"` } if hasNodelets { // Separate children further if source has tags. attr = attr + " minlen=2" } fmt.Fprintf(b, "N%d -> N%d [%s]\n", from, to, attr) }
go
func (b *builder) addEdge(edge *Edge, from, to int, hasNodelets bool) { var inline string if edge.Inline { inline = `\n (inline)` } w := b.config.FormatValue(edge.WeightValue()) attr := fmt.Sprintf(`label=" %s%s"`, w, inline) if b.config.Total != 0 { // Note: edge.weight > b.config.Total is possible for profile diffs. if weight := 1 + int(min64(abs64(edge.WeightValue()*100/b.config.Total), 100)); weight > 1 { attr = fmt.Sprintf(`%s weight=%d`, attr, weight) } if width := 1 + int(min64(abs64(edge.WeightValue()*5/b.config.Total), 5)); width > 1 { attr = fmt.Sprintf(`%s penwidth=%d`, attr, width) } attr = fmt.Sprintf(`%s color="%s"`, attr, dotColor(float64(edge.WeightValue())/float64(abs64(b.config.Total)), false)) } arrow := "->" if edge.Residual { arrow = "..." } tooltip := fmt.Sprintf(`"%s %s %s (%s)"`, edge.Src.Info.PrintableName(), arrow, edge.Dest.Info.PrintableName(), w) attr = fmt.Sprintf(`%s tooltip=%s labeltooltip=%s`, attr, tooltip, tooltip) if edge.Residual { attr = attr + ` style="dotted"` } if hasNodelets { // Separate children further if source has tags. attr = attr + " minlen=2" } fmt.Fprintf(b, "N%d -> N%d [%s]\n", from, to, attr) }
[ "func", "(", "b", "*", "builder", ")", "addEdge", "(", "edge", "*", "Edge", ",", "from", ",", "to", "int", ",", "hasNodelets", "bool", ")", "{", "var", "inline", "string", "\n", "if", "edge", ".", "Inline", "{", "inline", "=", "`\\n (inline)`", "\n", "}", "\n", "w", ":=", "b", ".", "config", ".", "FormatValue", "(", "edge", ".", "WeightValue", "(", ")", ")", "\n", "attr", ":=", "fmt", ".", "Sprintf", "(", "`label=\" %s%s\"`", ",", "w", ",", "inline", ")", "\n", "if", "b", ".", "config", ".", "Total", "!=", "0", "{", "// Note: edge.weight > b.config.Total is possible for profile diffs.", "if", "weight", ":=", "1", "+", "int", "(", "min64", "(", "abs64", "(", "edge", ".", "WeightValue", "(", ")", "*", "100", "/", "b", ".", "config", ".", "Total", ")", ",", "100", ")", ")", ";", "weight", ">", "1", "{", "attr", "=", "fmt", ".", "Sprintf", "(", "`%s weight=%d`", ",", "attr", ",", "weight", ")", "\n", "}", "\n", "if", "width", ":=", "1", "+", "int", "(", "min64", "(", "abs64", "(", "edge", ".", "WeightValue", "(", ")", "*", "5", "/", "b", ".", "config", ".", "Total", ")", ",", "5", ")", ")", ";", "width", ">", "1", "{", "attr", "=", "fmt", ".", "Sprintf", "(", "`%s penwidth=%d`", ",", "attr", ",", "width", ")", "\n", "}", "\n", "attr", "=", "fmt", ".", "Sprintf", "(", "`%s color=\"%s\"`", ",", "attr", ",", "dotColor", "(", "float64", "(", "edge", ".", "WeightValue", "(", ")", ")", "/", "float64", "(", "abs64", "(", "b", ".", "config", ".", "Total", ")", ")", ",", "false", ")", ")", "\n", "}", "\n", "arrow", ":=", "\"", "\"", "\n", "if", "edge", ".", "Residual", "{", "arrow", "=", "\"", "\"", "\n", "}", "\n", "tooltip", ":=", "fmt", ".", "Sprintf", "(", "`\"%s %s %s (%s)\"`", ",", "edge", ".", "Src", ".", "Info", ".", "PrintableName", "(", ")", ",", "arrow", ",", "edge", ".", "Dest", ".", "Info", ".", "PrintableName", "(", ")", ",", "w", ")", "\n", "attr", "=", "fmt", ".", "Sprintf", "(", "`%s tooltip=%s labeltooltip=%s`", ",", "attr", ",", "tooltip", ",", "tooltip", ")", "\n\n", "if", "edge", ".", "Residual", "{", "attr", "=", "attr", "+", "` style=\"dotted\"`", "\n", "}", "\n\n", "if", "hasNodelets", "{", "// Separate children further if source has tags.", "attr", "=", "attr", "+", "\"", "\"", "\n", "}", "\n\n", "fmt", ".", "Fprintf", "(", "b", ",", "\"", "\\n", "\"", ",", "from", ",", "to", ",", "attr", ")", "\n", "}" ]
// addEdge generates a graph edge in DOT format.
[ "addEdge", "generates", "a", "graph", "edge", "in", "DOT", "format", "." ]
8358a9778bd1e48718ffcb96eb11ee061385bf62
https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/internal/graph/dotgraph.go#L285-L321
train
google/pprof
internal/graph/dotgraph.go
collapsedTags
func (b *builder) collapsedTags(ts []*Tag, count int, flatTags bool) []*Tag { ts = SortTags(ts, flatTags) if len(ts) <= count { return ts } tagGroups := make([][]*Tag, count) for i, t := range (ts)[:count] { tagGroups[i] = []*Tag{t} } for _, t := range (ts)[count:] { g, d := 0, tagDistance(t, tagGroups[0][0]) for i := 1; i < count; i++ { if nd := tagDistance(t, tagGroups[i][0]); nd < d { g, d = i, nd } } tagGroups[g] = append(tagGroups[g], t) } var nts []*Tag for _, g := range tagGroups { l, w, c := b.tagGroupLabel(g) nts = append(nts, &Tag{ Name: l, Flat: w, Cum: c, }) } return SortTags(nts, flatTags) }
go
func (b *builder) collapsedTags(ts []*Tag, count int, flatTags bool) []*Tag { ts = SortTags(ts, flatTags) if len(ts) <= count { return ts } tagGroups := make([][]*Tag, count) for i, t := range (ts)[:count] { tagGroups[i] = []*Tag{t} } for _, t := range (ts)[count:] { g, d := 0, tagDistance(t, tagGroups[0][0]) for i := 1; i < count; i++ { if nd := tagDistance(t, tagGroups[i][0]); nd < d { g, d = i, nd } } tagGroups[g] = append(tagGroups[g], t) } var nts []*Tag for _, g := range tagGroups { l, w, c := b.tagGroupLabel(g) nts = append(nts, &Tag{ Name: l, Flat: w, Cum: c, }) } return SortTags(nts, flatTags) }
[ "func", "(", "b", "*", "builder", ")", "collapsedTags", "(", "ts", "[", "]", "*", "Tag", ",", "count", "int", ",", "flatTags", "bool", ")", "[", "]", "*", "Tag", "{", "ts", "=", "SortTags", "(", "ts", ",", "flatTags", ")", "\n", "if", "len", "(", "ts", ")", "<=", "count", "{", "return", "ts", "\n", "}", "\n\n", "tagGroups", ":=", "make", "(", "[", "]", "[", "]", "*", "Tag", ",", "count", ")", "\n", "for", "i", ",", "t", ":=", "range", "(", "ts", ")", "[", ":", "count", "]", "{", "tagGroups", "[", "i", "]", "=", "[", "]", "*", "Tag", "{", "t", "}", "\n", "}", "\n", "for", "_", ",", "t", ":=", "range", "(", "ts", ")", "[", "count", ":", "]", "{", "g", ",", "d", ":=", "0", ",", "tagDistance", "(", "t", ",", "tagGroups", "[", "0", "]", "[", "0", "]", ")", "\n", "for", "i", ":=", "1", ";", "i", "<", "count", ";", "i", "++", "{", "if", "nd", ":=", "tagDistance", "(", "t", ",", "tagGroups", "[", "i", "]", "[", "0", "]", ")", ";", "nd", "<", "d", "{", "g", ",", "d", "=", "i", ",", "nd", "\n", "}", "\n", "}", "\n", "tagGroups", "[", "g", "]", "=", "append", "(", "tagGroups", "[", "g", "]", ",", "t", ")", "\n", "}", "\n\n", "var", "nts", "[", "]", "*", "Tag", "\n", "for", "_", ",", "g", ":=", "range", "tagGroups", "{", "l", ",", "w", ",", "c", ":=", "b", ".", "tagGroupLabel", "(", "g", ")", "\n", "nts", "=", "append", "(", "nts", ",", "&", "Tag", "{", "Name", ":", "l", ",", "Flat", ":", "w", ",", "Cum", ":", "c", ",", "}", ")", "\n", "}", "\n", "return", "SortTags", "(", "nts", ",", "flatTags", ")", "\n", "}" ]
// collapsedTags trims and sorts a slice of tags.
[ "collapsedTags", "trims", "and", "sorts", "a", "slice", "of", "tags", "." ]
8358a9778bd1e48718ffcb96eb11ee061385bf62
https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/internal/graph/dotgraph.go#L395-L425
train
google/pprof
internal/report/report.go
newTrimmedGraph
func (rpt *Report) newTrimmedGraph() (g *graph.Graph, origCount, droppedNodes, droppedEdges int) { o := rpt.options // Build a graph and refine it. On each refinement step we must rebuild the graph from the samples, // as the graph itself doesn't contain enough information to preserve full precision. visualMode := o.OutputFormat == Dot cumSort := o.CumSort // The call_tree option is only honored when generating visual representations of the callgraph. callTree := o.CallTree && (o.OutputFormat == Dot || o.OutputFormat == Callgrind) // First step: Build complete graph to identify low frequency nodes, based on their cum weight. g = rpt.newGraph(nil) totalValue, _ := g.Nodes.Sum() nodeCutoff := abs64(int64(float64(totalValue) * o.NodeFraction)) edgeCutoff := abs64(int64(float64(totalValue) * o.EdgeFraction)) // Filter out nodes with cum value below nodeCutoff. if nodeCutoff > 0 { if callTree { if nodesKept := g.DiscardLowFrequencyNodePtrs(nodeCutoff); len(g.Nodes) != len(nodesKept) { droppedNodes = len(g.Nodes) - len(nodesKept) g.TrimTree(nodesKept) } } else { if nodesKept := g.DiscardLowFrequencyNodes(nodeCutoff); len(g.Nodes) != len(nodesKept) { droppedNodes = len(g.Nodes) - len(nodesKept) g = rpt.newGraph(nodesKept) } } } origCount = len(g.Nodes) // Second step: Limit the total number of nodes. Apply specialized heuristics to improve // visualization when generating dot output. g.SortNodes(cumSort, visualMode) if nodeCount := o.NodeCount; nodeCount > 0 { // Remove low frequency tags and edges as they affect selection. g.TrimLowFrequencyTags(nodeCutoff) g.TrimLowFrequencyEdges(edgeCutoff) if callTree { if nodesKept := g.SelectTopNodePtrs(nodeCount, visualMode); len(g.Nodes) != len(nodesKept) { g.TrimTree(nodesKept) g.SortNodes(cumSort, visualMode) } } else { if nodesKept := g.SelectTopNodes(nodeCount, visualMode); len(g.Nodes) != len(nodesKept) { g = rpt.newGraph(nodesKept) g.SortNodes(cumSort, visualMode) } } } // Final step: Filter out low frequency tags and edges, and remove redundant edges that clutter // the graph. g.TrimLowFrequencyTags(nodeCutoff) droppedEdges = g.TrimLowFrequencyEdges(edgeCutoff) if visualMode { g.RemoveRedundantEdges() } return }
go
func (rpt *Report) newTrimmedGraph() (g *graph.Graph, origCount, droppedNodes, droppedEdges int) { o := rpt.options // Build a graph and refine it. On each refinement step we must rebuild the graph from the samples, // as the graph itself doesn't contain enough information to preserve full precision. visualMode := o.OutputFormat == Dot cumSort := o.CumSort // The call_tree option is only honored when generating visual representations of the callgraph. callTree := o.CallTree && (o.OutputFormat == Dot || o.OutputFormat == Callgrind) // First step: Build complete graph to identify low frequency nodes, based on their cum weight. g = rpt.newGraph(nil) totalValue, _ := g.Nodes.Sum() nodeCutoff := abs64(int64(float64(totalValue) * o.NodeFraction)) edgeCutoff := abs64(int64(float64(totalValue) * o.EdgeFraction)) // Filter out nodes with cum value below nodeCutoff. if nodeCutoff > 0 { if callTree { if nodesKept := g.DiscardLowFrequencyNodePtrs(nodeCutoff); len(g.Nodes) != len(nodesKept) { droppedNodes = len(g.Nodes) - len(nodesKept) g.TrimTree(nodesKept) } } else { if nodesKept := g.DiscardLowFrequencyNodes(nodeCutoff); len(g.Nodes) != len(nodesKept) { droppedNodes = len(g.Nodes) - len(nodesKept) g = rpt.newGraph(nodesKept) } } } origCount = len(g.Nodes) // Second step: Limit the total number of nodes. Apply specialized heuristics to improve // visualization when generating dot output. g.SortNodes(cumSort, visualMode) if nodeCount := o.NodeCount; nodeCount > 0 { // Remove low frequency tags and edges as they affect selection. g.TrimLowFrequencyTags(nodeCutoff) g.TrimLowFrequencyEdges(edgeCutoff) if callTree { if nodesKept := g.SelectTopNodePtrs(nodeCount, visualMode); len(g.Nodes) != len(nodesKept) { g.TrimTree(nodesKept) g.SortNodes(cumSort, visualMode) } } else { if nodesKept := g.SelectTopNodes(nodeCount, visualMode); len(g.Nodes) != len(nodesKept) { g = rpt.newGraph(nodesKept) g.SortNodes(cumSort, visualMode) } } } // Final step: Filter out low frequency tags and edges, and remove redundant edges that clutter // the graph. g.TrimLowFrequencyTags(nodeCutoff) droppedEdges = g.TrimLowFrequencyEdges(edgeCutoff) if visualMode { g.RemoveRedundantEdges() } return }
[ "func", "(", "rpt", "*", "Report", ")", "newTrimmedGraph", "(", ")", "(", "g", "*", "graph", ".", "Graph", ",", "origCount", ",", "droppedNodes", ",", "droppedEdges", "int", ")", "{", "o", ":=", "rpt", ".", "options", "\n\n", "// Build a graph and refine it. On each refinement step we must rebuild the graph from the samples,", "// as the graph itself doesn't contain enough information to preserve full precision.", "visualMode", ":=", "o", ".", "OutputFormat", "==", "Dot", "\n", "cumSort", ":=", "o", ".", "CumSort", "\n\n", "// The call_tree option is only honored when generating visual representations of the callgraph.", "callTree", ":=", "o", ".", "CallTree", "&&", "(", "o", ".", "OutputFormat", "==", "Dot", "||", "o", ".", "OutputFormat", "==", "Callgrind", ")", "\n\n", "// First step: Build complete graph to identify low frequency nodes, based on their cum weight.", "g", "=", "rpt", ".", "newGraph", "(", "nil", ")", "\n", "totalValue", ",", "_", ":=", "g", ".", "Nodes", ".", "Sum", "(", ")", "\n", "nodeCutoff", ":=", "abs64", "(", "int64", "(", "float64", "(", "totalValue", ")", "*", "o", ".", "NodeFraction", ")", ")", "\n", "edgeCutoff", ":=", "abs64", "(", "int64", "(", "float64", "(", "totalValue", ")", "*", "o", ".", "EdgeFraction", ")", ")", "\n\n", "// Filter out nodes with cum value below nodeCutoff.", "if", "nodeCutoff", ">", "0", "{", "if", "callTree", "{", "if", "nodesKept", ":=", "g", ".", "DiscardLowFrequencyNodePtrs", "(", "nodeCutoff", ")", ";", "len", "(", "g", ".", "Nodes", ")", "!=", "len", "(", "nodesKept", ")", "{", "droppedNodes", "=", "len", "(", "g", ".", "Nodes", ")", "-", "len", "(", "nodesKept", ")", "\n", "g", ".", "TrimTree", "(", "nodesKept", ")", "\n", "}", "\n", "}", "else", "{", "if", "nodesKept", ":=", "g", ".", "DiscardLowFrequencyNodes", "(", "nodeCutoff", ")", ";", "len", "(", "g", ".", "Nodes", ")", "!=", "len", "(", "nodesKept", ")", "{", "droppedNodes", "=", "len", "(", "g", ".", "Nodes", ")", "-", "len", "(", "nodesKept", ")", "\n", "g", "=", "rpt", ".", "newGraph", "(", "nodesKept", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "origCount", "=", "len", "(", "g", ".", "Nodes", ")", "\n\n", "// Second step: Limit the total number of nodes. Apply specialized heuristics to improve", "// visualization when generating dot output.", "g", ".", "SortNodes", "(", "cumSort", ",", "visualMode", ")", "\n", "if", "nodeCount", ":=", "o", ".", "NodeCount", ";", "nodeCount", ">", "0", "{", "// Remove low frequency tags and edges as they affect selection.", "g", ".", "TrimLowFrequencyTags", "(", "nodeCutoff", ")", "\n", "g", ".", "TrimLowFrequencyEdges", "(", "edgeCutoff", ")", "\n", "if", "callTree", "{", "if", "nodesKept", ":=", "g", ".", "SelectTopNodePtrs", "(", "nodeCount", ",", "visualMode", ")", ";", "len", "(", "g", ".", "Nodes", ")", "!=", "len", "(", "nodesKept", ")", "{", "g", ".", "TrimTree", "(", "nodesKept", ")", "\n", "g", ".", "SortNodes", "(", "cumSort", ",", "visualMode", ")", "\n", "}", "\n", "}", "else", "{", "if", "nodesKept", ":=", "g", ".", "SelectTopNodes", "(", "nodeCount", ",", "visualMode", ")", ";", "len", "(", "g", ".", "Nodes", ")", "!=", "len", "(", "nodesKept", ")", "{", "g", "=", "rpt", ".", "newGraph", "(", "nodesKept", ")", "\n", "g", ".", "SortNodes", "(", "cumSort", ",", "visualMode", ")", "\n", "}", "\n", "}", "\n", "}", "\n\n", "// Final step: Filter out low frequency tags and edges, and remove redundant edges that clutter", "// the graph.", "g", ".", "TrimLowFrequencyTags", "(", "nodeCutoff", ")", "\n", "droppedEdges", "=", "g", ".", "TrimLowFrequencyEdges", "(", "edgeCutoff", ")", "\n", "if", "visualMode", "{", "g", ".", "RemoveRedundantEdges", "(", ")", "\n", "}", "\n", "return", "\n", "}" ]
// newTrimmedGraph creates a graph for this report, trimmed according // to the report options.
[ "newTrimmedGraph", "creates", "a", "graph", "for", "this", "report", "trimmed", "according", "to", "the", "report", "options", "." ]
8358a9778bd1e48718ffcb96eb11ee061385bf62
https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/internal/report/report.go#L122-L183
train
google/pprof
internal/report/report.go
newGraph
func (rpt *Report) newGraph(nodes graph.NodeSet) *graph.Graph { o := rpt.options // Clean up file paths using heuristics. prof := rpt.prof for _, f := range prof.Function { f.Filename = trimPath(f.Filename, o.TrimPath, o.SourcePath) } // Removes all numeric tags except for the bytes tag prior // to making graph. // TODO: modify to select first numeric tag if no bytes tag for _, s := range prof.Sample { numLabels := make(map[string][]int64, len(s.NumLabel)) numUnits := make(map[string][]string, len(s.NumLabel)) for k, vs := range s.NumLabel { if k == "bytes" { unit := o.NumLabelUnits[k] numValues := make([]int64, len(vs)) numUnit := make([]string, len(vs)) for i, v := range vs { numValues[i] = v numUnit[i] = unit } numLabels[k] = append(numLabels[k], numValues...) numUnits[k] = append(numUnits[k], numUnit...) } } s.NumLabel = numLabels s.NumUnit = numUnits } // Remove label marking samples from the base profiles, so it does not appear // as a nodelet in the graph view. prof.RemoveLabel("pprof::base") formatTag := func(v int64, key string) string { return measurement.ScaledLabel(v, key, o.OutputUnit) } gopt := &graph.Options{ SampleValue: o.SampleValue, SampleMeanDivisor: o.SampleMeanDivisor, FormatTag: formatTag, CallTree: o.CallTree && (o.OutputFormat == Dot || o.OutputFormat == Callgrind), DropNegative: o.DropNegative, KeptNodes: nodes, } // Only keep binary names for disassembly-based reports, otherwise // remove it to allow merging of functions across binaries. switch o.OutputFormat { case Raw, List, WebList, Dis, Callgrind: gopt.ObjNames = true } return graph.New(rpt.prof, gopt) }
go
func (rpt *Report) newGraph(nodes graph.NodeSet) *graph.Graph { o := rpt.options // Clean up file paths using heuristics. prof := rpt.prof for _, f := range prof.Function { f.Filename = trimPath(f.Filename, o.TrimPath, o.SourcePath) } // Removes all numeric tags except for the bytes tag prior // to making graph. // TODO: modify to select first numeric tag if no bytes tag for _, s := range prof.Sample { numLabels := make(map[string][]int64, len(s.NumLabel)) numUnits := make(map[string][]string, len(s.NumLabel)) for k, vs := range s.NumLabel { if k == "bytes" { unit := o.NumLabelUnits[k] numValues := make([]int64, len(vs)) numUnit := make([]string, len(vs)) for i, v := range vs { numValues[i] = v numUnit[i] = unit } numLabels[k] = append(numLabels[k], numValues...) numUnits[k] = append(numUnits[k], numUnit...) } } s.NumLabel = numLabels s.NumUnit = numUnits } // Remove label marking samples from the base profiles, so it does not appear // as a nodelet in the graph view. prof.RemoveLabel("pprof::base") formatTag := func(v int64, key string) string { return measurement.ScaledLabel(v, key, o.OutputUnit) } gopt := &graph.Options{ SampleValue: o.SampleValue, SampleMeanDivisor: o.SampleMeanDivisor, FormatTag: formatTag, CallTree: o.CallTree && (o.OutputFormat == Dot || o.OutputFormat == Callgrind), DropNegative: o.DropNegative, KeptNodes: nodes, } // Only keep binary names for disassembly-based reports, otherwise // remove it to allow merging of functions across binaries. switch o.OutputFormat { case Raw, List, WebList, Dis, Callgrind: gopt.ObjNames = true } return graph.New(rpt.prof, gopt) }
[ "func", "(", "rpt", "*", "Report", ")", "newGraph", "(", "nodes", "graph", ".", "NodeSet", ")", "*", "graph", ".", "Graph", "{", "o", ":=", "rpt", ".", "options", "\n\n", "// Clean up file paths using heuristics.", "prof", ":=", "rpt", ".", "prof", "\n", "for", "_", ",", "f", ":=", "range", "prof", ".", "Function", "{", "f", ".", "Filename", "=", "trimPath", "(", "f", ".", "Filename", ",", "o", ".", "TrimPath", ",", "o", ".", "SourcePath", ")", "\n", "}", "\n", "// Removes all numeric tags except for the bytes tag prior", "// to making graph.", "// TODO: modify to select first numeric tag if no bytes tag", "for", "_", ",", "s", ":=", "range", "prof", ".", "Sample", "{", "numLabels", ":=", "make", "(", "map", "[", "string", "]", "[", "]", "int64", ",", "len", "(", "s", ".", "NumLabel", ")", ")", "\n", "numUnits", ":=", "make", "(", "map", "[", "string", "]", "[", "]", "string", ",", "len", "(", "s", ".", "NumLabel", ")", ")", "\n", "for", "k", ",", "vs", ":=", "range", "s", ".", "NumLabel", "{", "if", "k", "==", "\"", "\"", "{", "unit", ":=", "o", ".", "NumLabelUnits", "[", "k", "]", "\n", "numValues", ":=", "make", "(", "[", "]", "int64", ",", "len", "(", "vs", ")", ")", "\n", "numUnit", ":=", "make", "(", "[", "]", "string", ",", "len", "(", "vs", ")", ")", "\n", "for", "i", ",", "v", ":=", "range", "vs", "{", "numValues", "[", "i", "]", "=", "v", "\n", "numUnit", "[", "i", "]", "=", "unit", "\n", "}", "\n", "numLabels", "[", "k", "]", "=", "append", "(", "numLabels", "[", "k", "]", ",", "numValues", "...", ")", "\n", "numUnits", "[", "k", "]", "=", "append", "(", "numUnits", "[", "k", "]", ",", "numUnit", "...", ")", "\n", "}", "\n", "}", "\n", "s", ".", "NumLabel", "=", "numLabels", "\n", "s", ".", "NumUnit", "=", "numUnits", "\n", "}", "\n\n", "// Remove label marking samples from the base profiles, so it does not appear", "// as a nodelet in the graph view.", "prof", ".", "RemoveLabel", "(", "\"", "\"", ")", "\n\n", "formatTag", ":=", "func", "(", "v", "int64", ",", "key", "string", ")", "string", "{", "return", "measurement", ".", "ScaledLabel", "(", "v", ",", "key", ",", "o", ".", "OutputUnit", ")", "\n", "}", "\n\n", "gopt", ":=", "&", "graph", ".", "Options", "{", "SampleValue", ":", "o", ".", "SampleValue", ",", "SampleMeanDivisor", ":", "o", ".", "SampleMeanDivisor", ",", "FormatTag", ":", "formatTag", ",", "CallTree", ":", "o", ".", "CallTree", "&&", "(", "o", ".", "OutputFormat", "==", "Dot", "||", "o", ".", "OutputFormat", "==", "Callgrind", ")", ",", "DropNegative", ":", "o", ".", "DropNegative", ",", "KeptNodes", ":", "nodes", ",", "}", "\n\n", "// Only keep binary names for disassembly-based reports, otherwise", "// remove it to allow merging of functions across binaries.", "switch", "o", ".", "OutputFormat", "{", "case", "Raw", ",", "List", ",", "WebList", ",", "Dis", ",", "Callgrind", ":", "gopt", ".", "ObjNames", "=", "true", "\n", "}", "\n\n", "return", "graph", ".", "New", "(", "rpt", ".", "prof", ",", "gopt", ")", "\n", "}" ]
// newGraph creates a new graph for this report. If nodes is non-nil, // only nodes whose info matches are included. Otherwise, all nodes // are included, without trimming.
[ "newGraph", "creates", "a", "new", "graph", "for", "this", "report", ".", "If", "nodes", "is", "non", "-", "nil", "only", "nodes", "whose", "info", "matches", "are", "included", ".", "Otherwise", "all", "nodes", "are", "included", "without", "trimming", "." ]
8358a9778bd1e48718ffcb96eb11ee061385bf62
https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/internal/report/report.go#L236-L292
train
google/pprof
internal/report/report.go
findOrAdd
func (fm functionMap) findOrAdd(ni graph.NodeInfo) (*profile.Function, bool) { fName := fmt.Sprintf("%q%q%q%d", ni.Name, ni.OrigName, ni.File, ni.StartLine) if f := fm[fName]; f != nil { return f, false } f := &profile.Function{ ID: uint64(len(fm) + 1), Name: ni.Name, SystemName: ni.OrigName, Filename: ni.File, StartLine: int64(ni.StartLine), } fm[fName] = f return f, true }
go
func (fm functionMap) findOrAdd(ni graph.NodeInfo) (*profile.Function, bool) { fName := fmt.Sprintf("%q%q%q%d", ni.Name, ni.OrigName, ni.File, ni.StartLine) if f := fm[fName]; f != nil { return f, false } f := &profile.Function{ ID: uint64(len(fm) + 1), Name: ni.Name, SystemName: ni.OrigName, Filename: ni.File, StartLine: int64(ni.StartLine), } fm[fName] = f return f, true }
[ "func", "(", "fm", "functionMap", ")", "findOrAdd", "(", "ni", "graph", ".", "NodeInfo", ")", "(", "*", "profile", ".", "Function", ",", "bool", ")", "{", "fName", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "ni", ".", "Name", ",", "ni", ".", "OrigName", ",", "ni", ".", "File", ",", "ni", ".", "StartLine", ")", "\n\n", "if", "f", ":=", "fm", "[", "fName", "]", ";", "f", "!=", "nil", "{", "return", "f", ",", "false", "\n", "}", "\n\n", "f", ":=", "&", "profile", ".", "Function", "{", "ID", ":", "uint64", "(", "len", "(", "fm", ")", "+", "1", ")", ",", "Name", ":", "ni", ".", "Name", ",", "SystemName", ":", "ni", ".", "OrigName", ",", "Filename", ":", "ni", ".", "File", ",", "StartLine", ":", "int64", "(", "ni", ".", "StartLine", ")", ",", "}", "\n", "fm", "[", "fName", "]", "=", "f", "\n", "return", "f", ",", "true", "\n", "}" ]
// findOrAdd takes a node representing a function, adds the function // represented by the node to the map if the function is not already present, // and returns the function the node represents. This also returns a boolean, // which is true if the function was added and false otherwise.
[ "findOrAdd", "takes", "a", "node", "representing", "a", "function", "adds", "the", "function", "represented", "by", "the", "node", "to", "the", "map", "if", "the", "function", "is", "not", "already", "present", "and", "returns", "the", "function", "the", "node", "represents", ".", "This", "also", "returns", "a", "boolean", "which", "is", "true", "if", "the", "function", "was", "added", "and", "false", "otherwise", "." ]
8358a9778bd1e48718ffcb96eb11ee061385bf62
https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/internal/report/report.go#L347-L363
train
google/pprof
internal/report/report.go
PrintAssembly
func PrintAssembly(w io.Writer, rpt *Report, obj plugin.ObjTool, maxFuncs int) error { o := rpt.options prof := rpt.prof g := rpt.newGraph(nil) // If the regexp source can be parsed as an address, also match // functions that land on that address. var address *uint64 if hex, err := strconv.ParseUint(o.Symbol.String(), 0, 64); err == nil { address = &hex } fmt.Fprintln(w, "Total:", rpt.formatValue(rpt.total)) symbols := symbolsFromBinaries(prof, g, o.Symbol, address, obj) symNodes := nodesPerSymbol(g.Nodes, symbols) // Sort for printing. var syms []*objSymbol for s := range symNodes { syms = append(syms, s) } byName := func(a, b *objSymbol) bool { if na, nb := a.sym.Name[0], b.sym.Name[0]; na != nb { return na < nb } return a.sym.Start < b.sym.Start } if maxFuncs < 0 { sort.Sort(orderSyms{syms, byName}) } else { byFlatSum := func(a, b *objSymbol) bool { suma, _ := symNodes[a].Sum() sumb, _ := symNodes[b].Sum() if suma != sumb { return suma > sumb } return byName(a, b) } sort.Sort(orderSyms{syms, byFlatSum}) if len(syms) > maxFuncs { syms = syms[:maxFuncs] } } // Correlate the symbols from the binary with the profile samples. for _, s := range syms { sns := symNodes[s] // Gather samples for this symbol. flatSum, cumSum := sns.Sum() // Get the function assembly. insts, err := obj.Disasm(s.sym.File, s.sym.Start, s.sym.End) if err != nil { return err } ns := annotateAssembly(insts, sns, s.base) fmt.Fprintf(w, "ROUTINE ======================== %s\n", s.sym.Name[0]) for _, name := range s.sym.Name[1:] { fmt.Fprintf(w, " AKA ======================== %s\n", name) } fmt.Fprintf(w, "%10s %10s (flat, cum) %s of Total\n", rpt.formatValue(flatSum), rpt.formatValue(cumSum), measurement.Percentage(cumSum, rpt.total)) function, file, line := "", "", 0 for _, n := range ns { locStr := "" // Skip loc information if it hasn't changed from previous instruction. if n.function != function || n.file != file || n.line != line { function, file, line = n.function, n.file, n.line if n.function != "" { locStr = n.function + " " } if n.file != "" { locStr += n.file if n.line != 0 { locStr += fmt.Sprintf(":%d", n.line) } } } switch { case locStr == "": // No location info, just print the instruction. fmt.Fprintf(w, "%10s %10s %10x: %s\n", valueOrDot(n.flatValue(), rpt), valueOrDot(n.cumValue(), rpt), n.address, n.instruction, ) case len(n.instruction) < 40: // Short instruction, print loc on the same line. fmt.Fprintf(w, "%10s %10s %10x: %-40s;%s\n", valueOrDot(n.flatValue(), rpt), valueOrDot(n.cumValue(), rpt), n.address, n.instruction, locStr, ) default: // Long instruction, print loc on a separate line. fmt.Fprintf(w, "%74s;%s\n", "", locStr) fmt.Fprintf(w, "%10s %10s %10x: %s\n", valueOrDot(n.flatValue(), rpt), valueOrDot(n.cumValue(), rpt), n.address, n.instruction, ) } } } return nil }
go
func PrintAssembly(w io.Writer, rpt *Report, obj plugin.ObjTool, maxFuncs int) error { o := rpt.options prof := rpt.prof g := rpt.newGraph(nil) // If the regexp source can be parsed as an address, also match // functions that land on that address. var address *uint64 if hex, err := strconv.ParseUint(o.Symbol.String(), 0, 64); err == nil { address = &hex } fmt.Fprintln(w, "Total:", rpt.formatValue(rpt.total)) symbols := symbolsFromBinaries(prof, g, o.Symbol, address, obj) symNodes := nodesPerSymbol(g.Nodes, symbols) // Sort for printing. var syms []*objSymbol for s := range symNodes { syms = append(syms, s) } byName := func(a, b *objSymbol) bool { if na, nb := a.sym.Name[0], b.sym.Name[0]; na != nb { return na < nb } return a.sym.Start < b.sym.Start } if maxFuncs < 0 { sort.Sort(orderSyms{syms, byName}) } else { byFlatSum := func(a, b *objSymbol) bool { suma, _ := symNodes[a].Sum() sumb, _ := symNodes[b].Sum() if suma != sumb { return suma > sumb } return byName(a, b) } sort.Sort(orderSyms{syms, byFlatSum}) if len(syms) > maxFuncs { syms = syms[:maxFuncs] } } // Correlate the symbols from the binary with the profile samples. for _, s := range syms { sns := symNodes[s] // Gather samples for this symbol. flatSum, cumSum := sns.Sum() // Get the function assembly. insts, err := obj.Disasm(s.sym.File, s.sym.Start, s.sym.End) if err != nil { return err } ns := annotateAssembly(insts, sns, s.base) fmt.Fprintf(w, "ROUTINE ======================== %s\n", s.sym.Name[0]) for _, name := range s.sym.Name[1:] { fmt.Fprintf(w, " AKA ======================== %s\n", name) } fmt.Fprintf(w, "%10s %10s (flat, cum) %s of Total\n", rpt.formatValue(flatSum), rpt.formatValue(cumSum), measurement.Percentage(cumSum, rpt.total)) function, file, line := "", "", 0 for _, n := range ns { locStr := "" // Skip loc information if it hasn't changed from previous instruction. if n.function != function || n.file != file || n.line != line { function, file, line = n.function, n.file, n.line if n.function != "" { locStr = n.function + " " } if n.file != "" { locStr += n.file if n.line != 0 { locStr += fmt.Sprintf(":%d", n.line) } } } switch { case locStr == "": // No location info, just print the instruction. fmt.Fprintf(w, "%10s %10s %10x: %s\n", valueOrDot(n.flatValue(), rpt), valueOrDot(n.cumValue(), rpt), n.address, n.instruction, ) case len(n.instruction) < 40: // Short instruction, print loc on the same line. fmt.Fprintf(w, "%10s %10s %10x: %-40s;%s\n", valueOrDot(n.flatValue(), rpt), valueOrDot(n.cumValue(), rpt), n.address, n.instruction, locStr, ) default: // Long instruction, print loc on a separate line. fmt.Fprintf(w, "%74s;%s\n", "", locStr) fmt.Fprintf(w, "%10s %10s %10x: %s\n", valueOrDot(n.flatValue(), rpt), valueOrDot(n.cumValue(), rpt), n.address, n.instruction, ) } } } return nil }
[ "func", "PrintAssembly", "(", "w", "io", ".", "Writer", ",", "rpt", "*", "Report", ",", "obj", "plugin", ".", "ObjTool", ",", "maxFuncs", "int", ")", "error", "{", "o", ":=", "rpt", ".", "options", "\n", "prof", ":=", "rpt", ".", "prof", "\n\n", "g", ":=", "rpt", ".", "newGraph", "(", "nil", ")", "\n\n", "// If the regexp source can be parsed as an address, also match", "// functions that land on that address.", "var", "address", "*", "uint64", "\n", "if", "hex", ",", "err", ":=", "strconv", ".", "ParseUint", "(", "o", ".", "Symbol", ".", "String", "(", ")", ",", "0", ",", "64", ")", ";", "err", "==", "nil", "{", "address", "=", "&", "hex", "\n", "}", "\n\n", "fmt", ".", "Fprintln", "(", "w", ",", "\"", "\"", ",", "rpt", ".", "formatValue", "(", "rpt", ".", "total", ")", ")", "\n", "symbols", ":=", "symbolsFromBinaries", "(", "prof", ",", "g", ",", "o", ".", "Symbol", ",", "address", ",", "obj", ")", "\n", "symNodes", ":=", "nodesPerSymbol", "(", "g", ".", "Nodes", ",", "symbols", ")", "\n\n", "// Sort for printing.", "var", "syms", "[", "]", "*", "objSymbol", "\n", "for", "s", ":=", "range", "symNodes", "{", "syms", "=", "append", "(", "syms", ",", "s", ")", "\n", "}", "\n", "byName", ":=", "func", "(", "a", ",", "b", "*", "objSymbol", ")", "bool", "{", "if", "na", ",", "nb", ":=", "a", ".", "sym", ".", "Name", "[", "0", "]", ",", "b", ".", "sym", ".", "Name", "[", "0", "]", ";", "na", "!=", "nb", "{", "return", "na", "<", "nb", "\n", "}", "\n", "return", "a", ".", "sym", ".", "Start", "<", "b", ".", "sym", ".", "Start", "\n", "}", "\n", "if", "maxFuncs", "<", "0", "{", "sort", ".", "Sort", "(", "orderSyms", "{", "syms", ",", "byName", "}", ")", "\n", "}", "else", "{", "byFlatSum", ":=", "func", "(", "a", ",", "b", "*", "objSymbol", ")", "bool", "{", "suma", ",", "_", ":=", "symNodes", "[", "a", "]", ".", "Sum", "(", ")", "\n", "sumb", ",", "_", ":=", "symNodes", "[", "b", "]", ".", "Sum", "(", ")", "\n", "if", "suma", "!=", "sumb", "{", "return", "suma", ">", "sumb", "\n", "}", "\n", "return", "byName", "(", "a", ",", "b", ")", "\n", "}", "\n", "sort", ".", "Sort", "(", "orderSyms", "{", "syms", ",", "byFlatSum", "}", ")", "\n", "if", "len", "(", "syms", ")", ">", "maxFuncs", "{", "syms", "=", "syms", "[", ":", "maxFuncs", "]", "\n", "}", "\n", "}", "\n\n", "// Correlate the symbols from the binary with the profile samples.", "for", "_", ",", "s", ":=", "range", "syms", "{", "sns", ":=", "symNodes", "[", "s", "]", "\n\n", "// Gather samples for this symbol.", "flatSum", ",", "cumSum", ":=", "sns", ".", "Sum", "(", ")", "\n\n", "// Get the function assembly.", "insts", ",", "err", ":=", "obj", ".", "Disasm", "(", "s", ".", "sym", ".", "File", ",", "s", ".", "sym", ".", "Start", ",", "s", ".", "sym", ".", "End", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "ns", ":=", "annotateAssembly", "(", "insts", ",", "sns", ",", "s", ".", "base", ")", "\n\n", "fmt", ".", "Fprintf", "(", "w", ",", "\"", "\\n", "\"", ",", "s", ".", "sym", ".", "Name", "[", "0", "]", ")", "\n", "for", "_", ",", "name", ":=", "range", "s", ".", "sym", ".", "Name", "[", "1", ":", "]", "{", "fmt", ".", "Fprintf", "(", "w", ",", "\"", "\\n", "\"", ",", "name", ")", "\n", "}", "\n", "fmt", ".", "Fprintf", "(", "w", ",", "\"", "\\n", "\"", ",", "rpt", ".", "formatValue", "(", "flatSum", ")", ",", "rpt", ".", "formatValue", "(", "cumSum", ")", ",", "measurement", ".", "Percentage", "(", "cumSum", ",", "rpt", ".", "total", ")", ")", "\n\n", "function", ",", "file", ",", "line", ":=", "\"", "\"", ",", "\"", "\"", ",", "0", "\n", "for", "_", ",", "n", ":=", "range", "ns", "{", "locStr", ":=", "\"", "\"", "\n", "// Skip loc information if it hasn't changed from previous instruction.", "if", "n", ".", "function", "!=", "function", "||", "n", ".", "file", "!=", "file", "||", "n", ".", "line", "!=", "line", "{", "function", ",", "file", ",", "line", "=", "n", ".", "function", ",", "n", ".", "file", ",", "n", ".", "line", "\n", "if", "n", ".", "function", "!=", "\"", "\"", "{", "locStr", "=", "n", ".", "function", "+", "\"", "\"", "\n", "}", "\n", "if", "n", ".", "file", "!=", "\"", "\"", "{", "locStr", "+=", "n", ".", "file", "\n", "if", "n", ".", "line", "!=", "0", "{", "locStr", "+=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "n", ".", "line", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "switch", "{", "case", "locStr", "==", "\"", "\"", ":", "// No location info, just print the instruction.", "fmt", ".", "Fprintf", "(", "w", ",", "\"", "\\n", "\"", ",", "valueOrDot", "(", "n", ".", "flatValue", "(", ")", ",", "rpt", ")", ",", "valueOrDot", "(", "n", ".", "cumValue", "(", ")", ",", "rpt", ")", ",", "n", ".", "address", ",", "n", ".", "instruction", ",", ")", "\n", "case", "len", "(", "n", ".", "instruction", ")", "<", "40", ":", "// Short instruction, print loc on the same line.", "fmt", ".", "Fprintf", "(", "w", ",", "\"", "\\n", "\"", ",", "valueOrDot", "(", "n", ".", "flatValue", "(", ")", ",", "rpt", ")", ",", "valueOrDot", "(", "n", ".", "cumValue", "(", ")", ",", "rpt", ")", ",", "n", ".", "address", ",", "n", ".", "instruction", ",", "locStr", ",", ")", "\n", "default", ":", "// Long instruction, print loc on a separate line.", "fmt", ".", "Fprintf", "(", "w", ",", "\"", "\\n", "\"", ",", "\"", "\"", ",", "locStr", ")", "\n", "fmt", ".", "Fprintf", "(", "w", ",", "\"", "\\n", "\"", ",", "valueOrDot", "(", "n", ".", "flatValue", "(", ")", ",", "rpt", ")", ",", "valueOrDot", "(", "n", ".", "cumValue", "(", ")", ",", "rpt", ")", ",", "n", ".", "address", ",", "n", ".", "instruction", ",", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// PrintAssembly prints annotated disassembly of rpt to w.
[ "PrintAssembly", "prints", "annotated", "disassembly", "of", "rpt", "to", "w", "." ]
8358a9778bd1e48718ffcb96eb11ee061385bf62
https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/internal/report/report.go#L371-L483
train
google/pprof
internal/report/report.go
valueOrDot
func valueOrDot(value int64, rpt *Report) string { if value == 0 { return "." } return rpt.formatValue(value) }
go
func valueOrDot(value int64, rpt *Report) string { if value == 0 { return "." } return rpt.formatValue(value) }
[ "func", "valueOrDot", "(", "value", "int64", ",", "rpt", "*", "Report", ")", "string", "{", "if", "value", "==", "0", "{", "return", "\"", "\"", "\n", "}", "\n", "return", "rpt", ".", "formatValue", "(", "value", ")", "\n", "}" ]
// valueOrDot formats a value according to a report, intercepting zero // values.
[ "valueOrDot", "formats", "a", "value", "according", "to", "a", "report", "intercepting", "zero", "values", "." ]
8358a9778bd1e48718ffcb96eb11ee061385bf62
https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/internal/report/report.go#L653-L658
train
google/pprof
internal/report/report.go
printComments
func printComments(w io.Writer, rpt *Report) error { p := rpt.prof for _, c := range p.Comments { fmt.Fprintln(w, c) } return nil }
go
func printComments(w io.Writer, rpt *Report) error { p := rpt.prof for _, c := range p.Comments { fmt.Fprintln(w, c) } return nil }
[ "func", "printComments", "(", "w", "io", ".", "Writer", ",", "rpt", "*", "Report", ")", "error", "{", "p", ":=", "rpt", ".", "prof", "\n\n", "for", "_", ",", "c", ":=", "range", "p", ".", "Comments", "{", "fmt", ".", "Fprintln", "(", "w", ",", "c", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// printComments prints all freeform comments in the profile.
[ "printComments", "prints", "all", "freeform", "comments", "in", "the", "profile", "." ]
8358a9778bd1e48718ffcb96eb11ee061385bf62
https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/internal/report/report.go#L727-L734
train
google/pprof
internal/report/report.go
TextItems
func TextItems(rpt *Report) ([]TextItem, []string) { g, origCount, droppedNodes, _ := rpt.newTrimmedGraph() rpt.selectOutputUnit(g) labels := reportLabels(rpt, g, origCount, droppedNodes, 0, false) var items []TextItem var flatSum int64 for _, n := range g.Nodes { name, flat, cum := n.Info.PrintableName(), n.FlatValue(), n.CumValue() var inline, noinline bool for _, e := range n.In { if e.Inline { inline = true } else { noinline = true } } var inl string if inline { if noinline { inl = "(partial-inline)" } else { inl = "(inline)" } } flatSum += flat items = append(items, TextItem{ Name: name, InlineLabel: inl, Flat: flat, Cum: cum, FlatFormat: rpt.formatValue(flat), CumFormat: rpt.formatValue(cum), }) } return items, labels }
go
func TextItems(rpt *Report) ([]TextItem, []string) { g, origCount, droppedNodes, _ := rpt.newTrimmedGraph() rpt.selectOutputUnit(g) labels := reportLabels(rpt, g, origCount, droppedNodes, 0, false) var items []TextItem var flatSum int64 for _, n := range g.Nodes { name, flat, cum := n.Info.PrintableName(), n.FlatValue(), n.CumValue() var inline, noinline bool for _, e := range n.In { if e.Inline { inline = true } else { noinline = true } } var inl string if inline { if noinline { inl = "(partial-inline)" } else { inl = "(inline)" } } flatSum += flat items = append(items, TextItem{ Name: name, InlineLabel: inl, Flat: flat, Cum: cum, FlatFormat: rpt.formatValue(flat), CumFormat: rpt.formatValue(cum), }) } return items, labels }
[ "func", "TextItems", "(", "rpt", "*", "Report", ")", "(", "[", "]", "TextItem", ",", "[", "]", "string", ")", "{", "g", ",", "origCount", ",", "droppedNodes", ",", "_", ":=", "rpt", ".", "newTrimmedGraph", "(", ")", "\n", "rpt", ".", "selectOutputUnit", "(", "g", ")", "\n", "labels", ":=", "reportLabels", "(", "rpt", ",", "g", ",", "origCount", ",", "droppedNodes", ",", "0", ",", "false", ")", "\n\n", "var", "items", "[", "]", "TextItem", "\n", "var", "flatSum", "int64", "\n", "for", "_", ",", "n", ":=", "range", "g", ".", "Nodes", "{", "name", ",", "flat", ",", "cum", ":=", "n", ".", "Info", ".", "PrintableName", "(", ")", ",", "n", ".", "FlatValue", "(", ")", ",", "n", ".", "CumValue", "(", ")", "\n\n", "var", "inline", ",", "noinline", "bool", "\n", "for", "_", ",", "e", ":=", "range", "n", ".", "In", "{", "if", "e", ".", "Inline", "{", "inline", "=", "true", "\n", "}", "else", "{", "noinline", "=", "true", "\n", "}", "\n", "}", "\n\n", "var", "inl", "string", "\n", "if", "inline", "{", "if", "noinline", "{", "inl", "=", "\"", "\"", "\n", "}", "else", "{", "inl", "=", "\"", "\"", "\n", "}", "\n", "}", "\n\n", "flatSum", "+=", "flat", "\n", "items", "=", "append", "(", "items", ",", "TextItem", "{", "Name", ":", "name", ",", "InlineLabel", ":", "inl", ",", "Flat", ":", "flat", ",", "Cum", ":", "cum", ",", "FlatFormat", ":", "rpt", ".", "formatValue", "(", "flat", ")", ",", "CumFormat", ":", "rpt", ".", "formatValue", "(", "cum", ")", ",", "}", ")", "\n", "}", "\n", "return", "items", ",", "labels", "\n", "}" ]
// TextItems returns a list of text items from the report and a list // of labels that describe the report.
[ "TextItems", "returns", "a", "list", "of", "text", "items", "from", "the", "report", "and", "a", "list", "of", "labels", "that", "describe", "the", "report", "." ]
8358a9778bd1e48718ffcb96eb11ee061385bf62
https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/internal/report/report.go#L746-L785
train
google/pprof
internal/report/report.go
printTraces
func printTraces(w io.Writer, rpt *Report) error { fmt.Fprintln(w, strings.Join(ProfileLabels(rpt), "\n")) prof := rpt.prof o := rpt.options const separator = "-----------+-------------------------------------------------------" _, locations := graph.CreateNodes(prof, &graph.Options{}) for _, sample := range prof.Sample { var stack graph.Nodes for _, loc := range sample.Location { id := loc.ID stack = append(stack, locations[id]...) } if len(stack) == 0 { continue } fmt.Fprintln(w, separator) // Print any text labels for the sample. var labels []string for s, vs := range sample.Label { labels = append(labels, fmt.Sprintf("%10s: %s\n", s, strings.Join(vs, " "))) } sort.Strings(labels) fmt.Fprint(w, strings.Join(labels, "")) // Print any numeric labels for the sample var numLabels []string for key, vals := range sample.NumLabel { unit := o.NumLabelUnits[key] numValues := make([]string, len(vals)) for i, vv := range vals { numValues[i] = measurement.Label(vv, unit) } numLabels = append(numLabels, fmt.Sprintf("%10s: %s\n", key, strings.Join(numValues, " "))) } sort.Strings(numLabels) fmt.Fprint(w, strings.Join(numLabels, "")) var d, v int64 v = o.SampleValue(sample.Value) if o.SampleMeanDivisor != nil { d = o.SampleMeanDivisor(sample.Value) } // Print call stack. if d != 0 { v = v / d } fmt.Fprintf(w, "%10s %s\n", rpt.formatValue(v), stack[0].Info.PrintableName()) for _, s := range stack[1:] { fmt.Fprintf(w, "%10s %s\n", "", s.Info.PrintableName()) } } fmt.Fprintln(w, separator) return nil }
go
func printTraces(w io.Writer, rpt *Report) error { fmt.Fprintln(w, strings.Join(ProfileLabels(rpt), "\n")) prof := rpt.prof o := rpt.options const separator = "-----------+-------------------------------------------------------" _, locations := graph.CreateNodes(prof, &graph.Options{}) for _, sample := range prof.Sample { var stack graph.Nodes for _, loc := range sample.Location { id := loc.ID stack = append(stack, locations[id]...) } if len(stack) == 0 { continue } fmt.Fprintln(w, separator) // Print any text labels for the sample. var labels []string for s, vs := range sample.Label { labels = append(labels, fmt.Sprintf("%10s: %s\n", s, strings.Join(vs, " "))) } sort.Strings(labels) fmt.Fprint(w, strings.Join(labels, "")) // Print any numeric labels for the sample var numLabels []string for key, vals := range sample.NumLabel { unit := o.NumLabelUnits[key] numValues := make([]string, len(vals)) for i, vv := range vals { numValues[i] = measurement.Label(vv, unit) } numLabels = append(numLabels, fmt.Sprintf("%10s: %s\n", key, strings.Join(numValues, " "))) } sort.Strings(numLabels) fmt.Fprint(w, strings.Join(numLabels, "")) var d, v int64 v = o.SampleValue(sample.Value) if o.SampleMeanDivisor != nil { d = o.SampleMeanDivisor(sample.Value) } // Print call stack. if d != 0 { v = v / d } fmt.Fprintf(w, "%10s %s\n", rpt.formatValue(v), stack[0].Info.PrintableName()) for _, s := range stack[1:] { fmt.Fprintf(w, "%10s %s\n", "", s.Info.PrintableName()) } } fmt.Fprintln(w, separator) return nil }
[ "func", "printTraces", "(", "w", "io", ".", "Writer", ",", "rpt", "*", "Report", ")", "error", "{", "fmt", ".", "Fprintln", "(", "w", ",", "strings", ".", "Join", "(", "ProfileLabels", "(", "rpt", ")", ",", "\"", "\\n", "\"", ")", ")", "\n\n", "prof", ":=", "rpt", ".", "prof", "\n", "o", ":=", "rpt", ".", "options", "\n\n", "const", "separator", "=", "\"", "\"", "\n\n", "_", ",", "locations", ":=", "graph", ".", "CreateNodes", "(", "prof", ",", "&", "graph", ".", "Options", "{", "}", ")", "\n", "for", "_", ",", "sample", ":=", "range", "prof", ".", "Sample", "{", "var", "stack", "graph", ".", "Nodes", "\n", "for", "_", ",", "loc", ":=", "range", "sample", ".", "Location", "{", "id", ":=", "loc", ".", "ID", "\n", "stack", "=", "append", "(", "stack", ",", "locations", "[", "id", "]", "...", ")", "\n", "}", "\n\n", "if", "len", "(", "stack", ")", "==", "0", "{", "continue", "\n", "}", "\n\n", "fmt", ".", "Fprintln", "(", "w", ",", "separator", ")", "\n", "// Print any text labels for the sample.", "var", "labels", "[", "]", "string", "\n", "for", "s", ",", "vs", ":=", "range", "sample", ".", "Label", "{", "labels", "=", "append", "(", "labels", ",", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "s", ",", "strings", ".", "Join", "(", "vs", ",", "\"", "\"", ")", ")", ")", "\n", "}", "\n", "sort", ".", "Strings", "(", "labels", ")", "\n", "fmt", ".", "Fprint", "(", "w", ",", "strings", ".", "Join", "(", "labels", ",", "\"", "\"", ")", ")", "\n\n", "// Print any numeric labels for the sample", "var", "numLabels", "[", "]", "string", "\n", "for", "key", ",", "vals", ":=", "range", "sample", ".", "NumLabel", "{", "unit", ":=", "o", ".", "NumLabelUnits", "[", "key", "]", "\n", "numValues", ":=", "make", "(", "[", "]", "string", ",", "len", "(", "vals", ")", ")", "\n", "for", "i", ",", "vv", ":=", "range", "vals", "{", "numValues", "[", "i", "]", "=", "measurement", ".", "Label", "(", "vv", ",", "unit", ")", "\n", "}", "\n", "numLabels", "=", "append", "(", "numLabels", ",", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "key", ",", "strings", ".", "Join", "(", "numValues", ",", "\"", "\"", ")", ")", ")", "\n", "}", "\n", "sort", ".", "Strings", "(", "numLabels", ")", "\n", "fmt", ".", "Fprint", "(", "w", ",", "strings", ".", "Join", "(", "numLabels", ",", "\"", "\"", ")", ")", "\n\n", "var", "d", ",", "v", "int64", "\n", "v", "=", "o", ".", "SampleValue", "(", "sample", ".", "Value", ")", "\n", "if", "o", ".", "SampleMeanDivisor", "!=", "nil", "{", "d", "=", "o", ".", "SampleMeanDivisor", "(", "sample", ".", "Value", ")", "\n", "}", "\n", "// Print call stack.", "if", "d", "!=", "0", "{", "v", "=", "v", "/", "d", "\n", "}", "\n", "fmt", ".", "Fprintf", "(", "w", ",", "\"", "\\n", "\"", ",", "rpt", ".", "formatValue", "(", "v", ")", ",", "stack", "[", "0", "]", ".", "Info", ".", "PrintableName", "(", ")", ")", "\n", "for", "_", ",", "s", ":=", "range", "stack", "[", "1", ":", "]", "{", "fmt", ".", "Fprintf", "(", "w", ",", "\"", "\\n", "\"", ",", "\"", "\"", ",", "s", ".", "Info", ".", "PrintableName", "(", ")", ")", "\n", "}", "\n", "}", "\n", "fmt", ".", "Fprintln", "(", "w", ",", "separator", ")", "\n", "return", "nil", "\n", "}" ]
// printTraces prints all traces from a profile.
[ "printTraces", "prints", "all", "traces", "from", "a", "profile", "." ]
8358a9778bd1e48718ffcb96eb11ee061385bf62
https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/internal/report/report.go#L810-L869
train
google/pprof
internal/report/report.go
GetDOT
func GetDOT(rpt *Report) (*graph.Graph, *graph.DotConfig) { g, origCount, droppedNodes, droppedEdges := rpt.newTrimmedGraph() rpt.selectOutputUnit(g) labels := reportLabels(rpt, g, origCount, droppedNodes, droppedEdges, true) c := &graph.DotConfig{ Title: rpt.options.Title, Labels: labels, FormatValue: rpt.formatValue, Total: rpt.total, } return g, c }
go
func GetDOT(rpt *Report) (*graph.Graph, *graph.DotConfig) { g, origCount, droppedNodes, droppedEdges := rpt.newTrimmedGraph() rpt.selectOutputUnit(g) labels := reportLabels(rpt, g, origCount, droppedNodes, droppedEdges, true) c := &graph.DotConfig{ Title: rpt.options.Title, Labels: labels, FormatValue: rpt.formatValue, Total: rpt.total, } return g, c }
[ "func", "GetDOT", "(", "rpt", "*", "Report", ")", "(", "*", "graph", ".", "Graph", ",", "*", "graph", ".", "DotConfig", ")", "{", "g", ",", "origCount", ",", "droppedNodes", ",", "droppedEdges", ":=", "rpt", ".", "newTrimmedGraph", "(", ")", "\n", "rpt", ".", "selectOutputUnit", "(", "g", ")", "\n", "labels", ":=", "reportLabels", "(", "rpt", ",", "g", ",", "origCount", ",", "droppedNodes", ",", "droppedEdges", ",", "true", ")", "\n\n", "c", ":=", "&", "graph", ".", "DotConfig", "{", "Title", ":", "rpt", ".", "options", ".", "Title", ",", "Labels", ":", "labels", ",", "FormatValue", ":", "rpt", ".", "formatValue", ",", "Total", ":", "rpt", ".", "total", ",", "}", "\n", "return", "g", ",", "c", "\n", "}" ]
// GetDOT returns a graph suitable for dot processing along with some // configuration information.
[ "GetDOT", "returns", "a", "graph", "suitable", "for", "dot", "processing", "along", "with", "some", "configuration", "information", "." ]
8358a9778bd1e48718ffcb96eb11ee061385bf62
https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/internal/report/report.go#L1074-L1086
train
google/pprof
internal/report/report.go
ProfileLabels
func ProfileLabels(rpt *Report) []string { label := []string{} prof := rpt.prof o := rpt.options if len(prof.Mapping) > 0 { if prof.Mapping[0].File != "" { label = append(label, "File: "+filepath.Base(prof.Mapping[0].File)) } if prof.Mapping[0].BuildID != "" { label = append(label, "Build ID: "+prof.Mapping[0].BuildID) } } // Only include comments that do not start with '#'. for _, c := range prof.Comments { if !strings.HasPrefix(c, "#") { label = append(label, c) } } if o.SampleType != "" { label = append(label, "Type: "+o.SampleType) } if prof.TimeNanos != 0 { const layout = "Jan 2, 2006 at 3:04pm (MST)" label = append(label, "Time: "+time.Unix(0, prof.TimeNanos).Format(layout)) } if prof.DurationNanos != 0 { duration := measurement.Label(prof.DurationNanos, "nanoseconds") totalNanos, totalUnit := measurement.Scale(rpt.total, o.SampleUnit, "nanoseconds") var ratio string if totalUnit == "ns" && totalNanos != 0 { ratio = "(" + measurement.Percentage(int64(totalNanos), prof.DurationNanos) + ")" } label = append(label, fmt.Sprintf("Duration: %s, Total samples = %s %s", duration, rpt.formatValue(rpt.total), ratio)) } return label }
go
func ProfileLabels(rpt *Report) []string { label := []string{} prof := rpt.prof o := rpt.options if len(prof.Mapping) > 0 { if prof.Mapping[0].File != "" { label = append(label, "File: "+filepath.Base(prof.Mapping[0].File)) } if prof.Mapping[0].BuildID != "" { label = append(label, "Build ID: "+prof.Mapping[0].BuildID) } } // Only include comments that do not start with '#'. for _, c := range prof.Comments { if !strings.HasPrefix(c, "#") { label = append(label, c) } } if o.SampleType != "" { label = append(label, "Type: "+o.SampleType) } if prof.TimeNanos != 0 { const layout = "Jan 2, 2006 at 3:04pm (MST)" label = append(label, "Time: "+time.Unix(0, prof.TimeNanos).Format(layout)) } if prof.DurationNanos != 0 { duration := measurement.Label(prof.DurationNanos, "nanoseconds") totalNanos, totalUnit := measurement.Scale(rpt.total, o.SampleUnit, "nanoseconds") var ratio string if totalUnit == "ns" && totalNanos != 0 { ratio = "(" + measurement.Percentage(int64(totalNanos), prof.DurationNanos) + ")" } label = append(label, fmt.Sprintf("Duration: %s, Total samples = %s %s", duration, rpt.formatValue(rpt.total), ratio)) } return label }
[ "func", "ProfileLabels", "(", "rpt", "*", "Report", ")", "[", "]", "string", "{", "label", ":=", "[", "]", "string", "{", "}", "\n", "prof", ":=", "rpt", ".", "prof", "\n", "o", ":=", "rpt", ".", "options", "\n", "if", "len", "(", "prof", ".", "Mapping", ")", ">", "0", "{", "if", "prof", ".", "Mapping", "[", "0", "]", ".", "File", "!=", "\"", "\"", "{", "label", "=", "append", "(", "label", ",", "\"", "\"", "+", "filepath", ".", "Base", "(", "prof", ".", "Mapping", "[", "0", "]", ".", "File", ")", ")", "\n", "}", "\n", "if", "prof", ".", "Mapping", "[", "0", "]", ".", "BuildID", "!=", "\"", "\"", "{", "label", "=", "append", "(", "label", ",", "\"", "\"", "+", "prof", ".", "Mapping", "[", "0", "]", ".", "BuildID", ")", "\n", "}", "\n", "}", "\n", "// Only include comments that do not start with '#'.", "for", "_", ",", "c", ":=", "range", "prof", ".", "Comments", "{", "if", "!", "strings", ".", "HasPrefix", "(", "c", ",", "\"", "\"", ")", "{", "label", "=", "append", "(", "label", ",", "c", ")", "\n", "}", "\n", "}", "\n", "if", "o", ".", "SampleType", "!=", "\"", "\"", "{", "label", "=", "append", "(", "label", ",", "\"", "\"", "+", "o", ".", "SampleType", ")", "\n", "}", "\n", "if", "prof", ".", "TimeNanos", "!=", "0", "{", "const", "layout", "=", "\"", "\"", "\n", "label", "=", "append", "(", "label", ",", "\"", "\"", "+", "time", ".", "Unix", "(", "0", ",", "prof", ".", "TimeNanos", ")", ".", "Format", "(", "layout", ")", ")", "\n", "}", "\n", "if", "prof", ".", "DurationNanos", "!=", "0", "{", "duration", ":=", "measurement", ".", "Label", "(", "prof", ".", "DurationNanos", ",", "\"", "\"", ")", "\n", "totalNanos", ",", "totalUnit", ":=", "measurement", ".", "Scale", "(", "rpt", ".", "total", ",", "o", ".", "SampleUnit", ",", "\"", "\"", ")", "\n", "var", "ratio", "string", "\n", "if", "totalUnit", "==", "\"", "\"", "&&", "totalNanos", "!=", "0", "{", "ratio", "=", "\"", "\"", "+", "measurement", ".", "Percentage", "(", "int64", "(", "totalNanos", ")", ",", "prof", ".", "DurationNanos", ")", "+", "\"", "\"", "\n", "}", "\n", "label", "=", "append", "(", "label", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "duration", ",", "rpt", ".", "formatValue", "(", "rpt", ".", "total", ")", ",", "ratio", ")", ")", "\n", "}", "\n", "return", "label", "\n", "}" ]
// ProfileLabels returns printable labels for a profile.
[ "ProfileLabels", "returns", "printable", "labels", "for", "a", "profile", "." ]
8358a9778bd1e48718ffcb96eb11ee061385bf62
https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/internal/report/report.go#L1096-L1131
train
google/pprof
internal/report/report.go
reportLabels
func reportLabels(rpt *Report, g *graph.Graph, origCount, droppedNodes, droppedEdges int, fullHeaders bool) []string { nodeFraction := rpt.options.NodeFraction edgeFraction := rpt.options.EdgeFraction nodeCount := len(g.Nodes) var label []string if len(rpt.options.ProfileLabels) > 0 { label = append(label, rpt.options.ProfileLabels...) } else if fullHeaders || !rpt.options.CompactLabels { label = ProfileLabels(rpt) } var flatSum int64 for _, n := range g.Nodes { flatSum = flatSum + n.FlatValue() } if len(rpt.options.ActiveFilters) > 0 { activeFilters := legendActiveFilters(rpt.options.ActiveFilters) label = append(label, activeFilters...) } label = append(label, fmt.Sprintf("Showing nodes accounting for %s, %s of %s total", rpt.formatValue(flatSum), strings.TrimSpace(measurement.Percentage(flatSum, rpt.total)), rpt.formatValue(rpt.total))) if rpt.total != 0 { if droppedNodes > 0 { label = append(label, genLabel(droppedNodes, "node", "cum", rpt.formatValue(abs64(int64(float64(rpt.total)*nodeFraction))))) } if droppedEdges > 0 { label = append(label, genLabel(droppedEdges, "edge", "freq", rpt.formatValue(abs64(int64(float64(rpt.total)*edgeFraction))))) } if nodeCount > 0 && nodeCount < origCount { label = append(label, fmt.Sprintf("Showing top %d nodes out of %d", nodeCount, origCount)) } } return label }
go
func reportLabels(rpt *Report, g *graph.Graph, origCount, droppedNodes, droppedEdges int, fullHeaders bool) []string { nodeFraction := rpt.options.NodeFraction edgeFraction := rpt.options.EdgeFraction nodeCount := len(g.Nodes) var label []string if len(rpt.options.ProfileLabels) > 0 { label = append(label, rpt.options.ProfileLabels...) } else if fullHeaders || !rpt.options.CompactLabels { label = ProfileLabels(rpt) } var flatSum int64 for _, n := range g.Nodes { flatSum = flatSum + n.FlatValue() } if len(rpt.options.ActiveFilters) > 0 { activeFilters := legendActiveFilters(rpt.options.ActiveFilters) label = append(label, activeFilters...) } label = append(label, fmt.Sprintf("Showing nodes accounting for %s, %s of %s total", rpt.formatValue(flatSum), strings.TrimSpace(measurement.Percentage(flatSum, rpt.total)), rpt.formatValue(rpt.total))) if rpt.total != 0 { if droppedNodes > 0 { label = append(label, genLabel(droppedNodes, "node", "cum", rpt.formatValue(abs64(int64(float64(rpt.total)*nodeFraction))))) } if droppedEdges > 0 { label = append(label, genLabel(droppedEdges, "edge", "freq", rpt.formatValue(abs64(int64(float64(rpt.total)*edgeFraction))))) } if nodeCount > 0 && nodeCount < origCount { label = append(label, fmt.Sprintf("Showing top %d nodes out of %d", nodeCount, origCount)) } } return label }
[ "func", "reportLabels", "(", "rpt", "*", "Report", ",", "g", "*", "graph", ".", "Graph", ",", "origCount", ",", "droppedNodes", ",", "droppedEdges", "int", ",", "fullHeaders", "bool", ")", "[", "]", "string", "{", "nodeFraction", ":=", "rpt", ".", "options", ".", "NodeFraction", "\n", "edgeFraction", ":=", "rpt", ".", "options", ".", "EdgeFraction", "\n", "nodeCount", ":=", "len", "(", "g", ".", "Nodes", ")", "\n\n", "var", "label", "[", "]", "string", "\n", "if", "len", "(", "rpt", ".", "options", ".", "ProfileLabels", ")", ">", "0", "{", "label", "=", "append", "(", "label", ",", "rpt", ".", "options", ".", "ProfileLabels", "...", ")", "\n", "}", "else", "if", "fullHeaders", "||", "!", "rpt", ".", "options", ".", "CompactLabels", "{", "label", "=", "ProfileLabels", "(", "rpt", ")", "\n", "}", "\n\n", "var", "flatSum", "int64", "\n", "for", "_", ",", "n", ":=", "range", "g", ".", "Nodes", "{", "flatSum", "=", "flatSum", "+", "n", ".", "FlatValue", "(", ")", "\n", "}", "\n\n", "if", "len", "(", "rpt", ".", "options", ".", "ActiveFilters", ")", ">", "0", "{", "activeFilters", ":=", "legendActiveFilters", "(", "rpt", ".", "options", ".", "ActiveFilters", ")", "\n", "label", "=", "append", "(", "label", ",", "activeFilters", "...", ")", "\n", "}", "\n\n", "label", "=", "append", "(", "label", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "rpt", ".", "formatValue", "(", "flatSum", ")", ",", "strings", ".", "TrimSpace", "(", "measurement", ".", "Percentage", "(", "flatSum", ",", "rpt", ".", "total", ")", ")", ",", "rpt", ".", "formatValue", "(", "rpt", ".", "total", ")", ")", ")", "\n\n", "if", "rpt", ".", "total", "!=", "0", "{", "if", "droppedNodes", ">", "0", "{", "label", "=", "append", "(", "label", ",", "genLabel", "(", "droppedNodes", ",", "\"", "\"", ",", "\"", "\"", ",", "rpt", ".", "formatValue", "(", "abs64", "(", "int64", "(", "float64", "(", "rpt", ".", "total", ")", "*", "nodeFraction", ")", ")", ")", ")", ")", "\n", "}", "\n", "if", "droppedEdges", ">", "0", "{", "label", "=", "append", "(", "label", ",", "genLabel", "(", "droppedEdges", ",", "\"", "\"", ",", "\"", "\"", ",", "rpt", ".", "formatValue", "(", "abs64", "(", "int64", "(", "float64", "(", "rpt", ".", "total", ")", "*", "edgeFraction", ")", ")", ")", ")", ")", "\n", "}", "\n", "if", "nodeCount", ">", "0", "&&", "nodeCount", "<", "origCount", "{", "label", "=", "append", "(", "label", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "nodeCount", ",", "origCount", ")", ")", "\n", "}", "\n", "}", "\n", "return", "label", "\n", "}" ]
// reportLabels returns printable labels for a report. Includes // profileLabels.
[ "reportLabels", "returns", "printable", "labels", "for", "a", "report", ".", "Includes", "profileLabels", "." ]
8358a9778bd1e48718ffcb96eb11ee061385bf62
https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/internal/report/report.go#L1135-L1174
train
google/pprof
internal/report/report.go
NewDefault
func NewDefault(prof *profile.Profile, options Options) *Report { index := len(prof.SampleType) - 1 o := &options if o.Title == "" && len(prof.Mapping) > 0 && prof.Mapping[0].File != "" { o.Title = filepath.Base(prof.Mapping[0].File) } o.SampleType = prof.SampleType[index].Type o.SampleUnit = strings.ToLower(prof.SampleType[index].Unit) o.SampleValue = func(v []int64) int64 { return v[index] } return New(prof, o) }
go
func NewDefault(prof *profile.Profile, options Options) *Report { index := len(prof.SampleType) - 1 o := &options if o.Title == "" && len(prof.Mapping) > 0 && prof.Mapping[0].File != "" { o.Title = filepath.Base(prof.Mapping[0].File) } o.SampleType = prof.SampleType[index].Type o.SampleUnit = strings.ToLower(prof.SampleType[index].Unit) o.SampleValue = func(v []int64) int64 { return v[index] } return New(prof, o) }
[ "func", "NewDefault", "(", "prof", "*", "profile", ".", "Profile", ",", "options", "Options", ")", "*", "Report", "{", "index", ":=", "len", "(", "prof", ".", "SampleType", ")", "-", "1", "\n", "o", ":=", "&", "options", "\n", "if", "o", ".", "Title", "==", "\"", "\"", "&&", "len", "(", "prof", ".", "Mapping", ")", ">", "0", "&&", "prof", ".", "Mapping", "[", "0", "]", ".", "File", "!=", "\"", "\"", "{", "o", ".", "Title", "=", "filepath", ".", "Base", "(", "prof", ".", "Mapping", "[", "0", "]", ".", "File", ")", "\n", "}", "\n", "o", ".", "SampleType", "=", "prof", ".", "SampleType", "[", "index", "]", ".", "Type", "\n", "o", ".", "SampleUnit", "=", "strings", ".", "ToLower", "(", "prof", ".", "SampleType", "[", "index", "]", ".", "Unit", ")", "\n", "o", ".", "SampleValue", "=", "func", "(", "v", "[", "]", "int64", ")", "int64", "{", "return", "v", "[", "index", "]", "\n", "}", "\n", "return", "New", "(", "prof", ",", "o", ")", "\n", "}" ]
// NewDefault builds a new report indexing the last sample value // available.
[ "NewDefault", "builds", "a", "new", "report", "indexing", "the", "last", "sample", "value", "available", "." ]
8358a9778bd1e48718ffcb96eb11ee061385bf62
https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/internal/report/report.go#L1211-L1223
train
google/pprof
internal/report/report.go
computeTotal
func computeTotal(prof *profile.Profile, value, meanDiv func(v []int64) int64) int64 { var div, total, diffDiv, diffTotal int64 for _, sample := range prof.Sample { var d, v int64 v = value(sample.Value) if meanDiv != nil { d = meanDiv(sample.Value) } if v < 0 { v = -v } total += v div += d if sample.DiffBaseSample() { diffTotal += v diffDiv += d } } if diffTotal > 0 { total = diffTotal div = diffDiv } if div != 0 { return total / div } return total }
go
func computeTotal(prof *profile.Profile, value, meanDiv func(v []int64) int64) int64 { var div, total, diffDiv, diffTotal int64 for _, sample := range prof.Sample { var d, v int64 v = value(sample.Value) if meanDiv != nil { d = meanDiv(sample.Value) } if v < 0 { v = -v } total += v div += d if sample.DiffBaseSample() { diffTotal += v diffDiv += d } } if diffTotal > 0 { total = diffTotal div = diffDiv } if div != 0 { return total / div } return total }
[ "func", "computeTotal", "(", "prof", "*", "profile", ".", "Profile", ",", "value", ",", "meanDiv", "func", "(", "v", "[", "]", "int64", ")", "int64", ")", "int64", "{", "var", "div", ",", "total", ",", "diffDiv", ",", "diffTotal", "int64", "\n", "for", "_", ",", "sample", ":=", "range", "prof", ".", "Sample", "{", "var", "d", ",", "v", "int64", "\n", "v", "=", "value", "(", "sample", ".", "Value", ")", "\n", "if", "meanDiv", "!=", "nil", "{", "d", "=", "meanDiv", "(", "sample", ".", "Value", ")", "\n", "}", "\n", "if", "v", "<", "0", "{", "v", "=", "-", "v", "\n", "}", "\n", "total", "+=", "v", "\n", "div", "+=", "d", "\n", "if", "sample", ".", "DiffBaseSample", "(", ")", "{", "diffTotal", "+=", "v", "\n", "diffDiv", "+=", "d", "\n", "}", "\n", "}", "\n", "if", "diffTotal", ">", "0", "{", "total", "=", "diffTotal", "\n", "div", "=", "diffDiv", "\n", "}", "\n", "if", "div", "!=", "0", "{", "return", "total", "/", "div", "\n", "}", "\n", "return", "total", "\n", "}" ]
// computeTotal computes the sum of the absolute value of all sample values. // If any samples have label indicating they belong to the diff base, then the // total will only include samples with that label.
[ "computeTotal", "computes", "the", "sum", "of", "the", "absolute", "value", "of", "all", "sample", "values", ".", "If", "any", "samples", "have", "label", "indicating", "they", "belong", "to", "the", "diff", "base", "then", "the", "total", "will", "only", "include", "samples", "with", "that", "label", "." ]
8358a9778bd1e48718ffcb96eb11ee061385bf62
https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/internal/report/report.go#L1228-L1254
train
google/pprof
profile/index.go
SampleIndexByName
func (p *Profile) SampleIndexByName(sampleIndex string) (int, error) { if sampleIndex == "" { if dst := p.DefaultSampleType; dst != "" { for i, t := range sampleTypes(p) { if t == dst { return i, nil } } } // By default select the last sample value return len(p.SampleType) - 1, nil } if i, err := strconv.Atoi(sampleIndex); err == nil { if i < 0 || i >= len(p.SampleType) { return 0, fmt.Errorf("sample_index %s is outside the range [0..%d]", sampleIndex, len(p.SampleType)-1) } return i, nil } // Remove the inuse_ prefix to support legacy pprof options // "inuse_space" and "inuse_objects" for profiles containing types // "space" and "objects". noInuse := strings.TrimPrefix(sampleIndex, "inuse_") for i, t := range p.SampleType { if t.Type == sampleIndex || t.Type == noInuse { return i, nil } } return 0, fmt.Errorf("sample_index %q must be one of: %v", sampleIndex, sampleTypes(p)) }
go
func (p *Profile) SampleIndexByName(sampleIndex string) (int, error) { if sampleIndex == "" { if dst := p.DefaultSampleType; dst != "" { for i, t := range sampleTypes(p) { if t == dst { return i, nil } } } // By default select the last sample value return len(p.SampleType) - 1, nil } if i, err := strconv.Atoi(sampleIndex); err == nil { if i < 0 || i >= len(p.SampleType) { return 0, fmt.Errorf("sample_index %s is outside the range [0..%d]", sampleIndex, len(p.SampleType)-1) } return i, nil } // Remove the inuse_ prefix to support legacy pprof options // "inuse_space" and "inuse_objects" for profiles containing types // "space" and "objects". noInuse := strings.TrimPrefix(sampleIndex, "inuse_") for i, t := range p.SampleType { if t.Type == sampleIndex || t.Type == noInuse { return i, nil } } return 0, fmt.Errorf("sample_index %q must be one of: %v", sampleIndex, sampleTypes(p)) }
[ "func", "(", "p", "*", "Profile", ")", "SampleIndexByName", "(", "sampleIndex", "string", ")", "(", "int", ",", "error", ")", "{", "if", "sampleIndex", "==", "\"", "\"", "{", "if", "dst", ":=", "p", ".", "DefaultSampleType", ";", "dst", "!=", "\"", "\"", "{", "for", "i", ",", "t", ":=", "range", "sampleTypes", "(", "p", ")", "{", "if", "t", "==", "dst", "{", "return", "i", ",", "nil", "\n", "}", "\n", "}", "\n", "}", "\n", "// By default select the last sample value", "return", "len", "(", "p", ".", "SampleType", ")", "-", "1", ",", "nil", "\n", "}", "\n", "if", "i", ",", "err", ":=", "strconv", ".", "Atoi", "(", "sampleIndex", ")", ";", "err", "==", "nil", "{", "if", "i", "<", "0", "||", "i", ">=", "len", "(", "p", ".", "SampleType", ")", "{", "return", "0", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "sampleIndex", ",", "len", "(", "p", ".", "SampleType", ")", "-", "1", ")", "\n", "}", "\n", "return", "i", ",", "nil", "\n", "}", "\n\n", "// Remove the inuse_ prefix to support legacy pprof options", "// \"inuse_space\" and \"inuse_objects\" for profiles containing types", "// \"space\" and \"objects\".", "noInuse", ":=", "strings", ".", "TrimPrefix", "(", "sampleIndex", ",", "\"", "\"", ")", "\n", "for", "i", ",", "t", ":=", "range", "p", ".", "SampleType", "{", "if", "t", ".", "Type", "==", "sampleIndex", "||", "t", ".", "Type", "==", "noInuse", "{", "return", "i", ",", "nil", "\n", "}", "\n", "}", "\n\n", "return", "0", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "sampleIndex", ",", "sampleTypes", "(", "p", ")", ")", "\n", "}" ]
// SampleIndexByName returns the appropriate index for a value of sample index. // If numeric, it returns the number, otherwise it looks up the text in the // profile sample types.
[ "SampleIndexByName", "returns", "the", "appropriate", "index", "for", "a", "value", "of", "sample", "index", ".", "If", "numeric", "it", "returns", "the", "number", "otherwise", "it", "looks", "up", "the", "text", "in", "the", "profile", "sample", "types", "." ]
8358a9778bd1e48718ffcb96eb11ee061385bf62
https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/profile/index.go#L26-L56
train
google/pprof
internal/driver/flamegraph.go
flamegraph
func (ui *webInterface) flamegraph(w http.ResponseWriter, req *http.Request) { // Force the call tree so that the graph is a tree. // Also do not trim the tree so that the flame graph contains all functions. rpt, errList := ui.makeReport(w, req, []string{"svg"}, "call_tree", "true", "trim", "false") if rpt == nil { return // error already reported } // Generate dot graph. g, config := report.GetDOT(rpt) var nodes []*treeNode nroots := 0 rootValue := int64(0) nodeArr := []string{} nodeMap := map[*graph.Node]*treeNode{} // Make all nodes and the map, collect the roots. for _, n := range g.Nodes { v := n.CumValue() fullName := n.Info.PrintableName() node := &treeNode{ Name: graph.ShortenFunctionName(fullName), FullName: fullName, Cum: v, CumFormat: config.FormatValue(v), Percent: strings.TrimSpace(measurement.Percentage(v, config.Total)), } nodes = append(nodes, node) if len(n.In) == 0 { nodes[nroots], nodes[len(nodes)-1] = nodes[len(nodes)-1], nodes[nroots] nroots++ rootValue += v } nodeMap[n] = node // Get all node names into an array. nodeArr = append(nodeArr, n.Info.Name) } // Populate the child links. for _, n := range g.Nodes { node := nodeMap[n] for child := range n.Out { node.Children = append(node.Children, nodeMap[child]) } } rootNode := &treeNode{ Name: "root", FullName: "root", Cum: rootValue, CumFormat: config.FormatValue(rootValue), Percent: strings.TrimSpace(measurement.Percentage(rootValue, config.Total)), Children: nodes[0:nroots], } // JSON marshalling flame graph b, err := json.Marshal(rootNode) if err != nil { http.Error(w, "error serializing flame graph", http.StatusInternalServerError) ui.options.UI.PrintErr(err) return } ui.render(w, "flamegraph", rpt, errList, config.Labels, webArgs{ FlameGraph: template.JS(b), Nodes: nodeArr, }) }
go
func (ui *webInterface) flamegraph(w http.ResponseWriter, req *http.Request) { // Force the call tree so that the graph is a tree. // Also do not trim the tree so that the flame graph contains all functions. rpt, errList := ui.makeReport(w, req, []string{"svg"}, "call_tree", "true", "trim", "false") if rpt == nil { return // error already reported } // Generate dot graph. g, config := report.GetDOT(rpt) var nodes []*treeNode nroots := 0 rootValue := int64(0) nodeArr := []string{} nodeMap := map[*graph.Node]*treeNode{} // Make all nodes and the map, collect the roots. for _, n := range g.Nodes { v := n.CumValue() fullName := n.Info.PrintableName() node := &treeNode{ Name: graph.ShortenFunctionName(fullName), FullName: fullName, Cum: v, CumFormat: config.FormatValue(v), Percent: strings.TrimSpace(measurement.Percentage(v, config.Total)), } nodes = append(nodes, node) if len(n.In) == 0 { nodes[nroots], nodes[len(nodes)-1] = nodes[len(nodes)-1], nodes[nroots] nroots++ rootValue += v } nodeMap[n] = node // Get all node names into an array. nodeArr = append(nodeArr, n.Info.Name) } // Populate the child links. for _, n := range g.Nodes { node := nodeMap[n] for child := range n.Out { node.Children = append(node.Children, nodeMap[child]) } } rootNode := &treeNode{ Name: "root", FullName: "root", Cum: rootValue, CumFormat: config.FormatValue(rootValue), Percent: strings.TrimSpace(measurement.Percentage(rootValue, config.Total)), Children: nodes[0:nroots], } // JSON marshalling flame graph b, err := json.Marshal(rootNode) if err != nil { http.Error(w, "error serializing flame graph", http.StatusInternalServerError) ui.options.UI.PrintErr(err) return } ui.render(w, "flamegraph", rpt, errList, config.Labels, webArgs{ FlameGraph: template.JS(b), Nodes: nodeArr, }) }
[ "func", "(", "ui", "*", "webInterface", ")", "flamegraph", "(", "w", "http", ".", "ResponseWriter", ",", "req", "*", "http", ".", "Request", ")", "{", "// Force the call tree so that the graph is a tree.", "// Also do not trim the tree so that the flame graph contains all functions.", "rpt", ",", "errList", ":=", "ui", ".", "makeReport", "(", "w", ",", "req", ",", "[", "]", "string", "{", "\"", "\"", "}", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "if", "rpt", "==", "nil", "{", "return", "// error already reported", "\n", "}", "\n\n", "// Generate dot graph.", "g", ",", "config", ":=", "report", ".", "GetDOT", "(", "rpt", ")", "\n", "var", "nodes", "[", "]", "*", "treeNode", "\n", "nroots", ":=", "0", "\n", "rootValue", ":=", "int64", "(", "0", ")", "\n", "nodeArr", ":=", "[", "]", "string", "{", "}", "\n", "nodeMap", ":=", "map", "[", "*", "graph", ".", "Node", "]", "*", "treeNode", "{", "}", "\n", "// Make all nodes and the map, collect the roots.", "for", "_", ",", "n", ":=", "range", "g", ".", "Nodes", "{", "v", ":=", "n", ".", "CumValue", "(", ")", "\n", "fullName", ":=", "n", ".", "Info", ".", "PrintableName", "(", ")", "\n", "node", ":=", "&", "treeNode", "{", "Name", ":", "graph", ".", "ShortenFunctionName", "(", "fullName", ")", ",", "FullName", ":", "fullName", ",", "Cum", ":", "v", ",", "CumFormat", ":", "config", ".", "FormatValue", "(", "v", ")", ",", "Percent", ":", "strings", ".", "TrimSpace", "(", "measurement", ".", "Percentage", "(", "v", ",", "config", ".", "Total", ")", ")", ",", "}", "\n", "nodes", "=", "append", "(", "nodes", ",", "node", ")", "\n", "if", "len", "(", "n", ".", "In", ")", "==", "0", "{", "nodes", "[", "nroots", "]", ",", "nodes", "[", "len", "(", "nodes", ")", "-", "1", "]", "=", "nodes", "[", "len", "(", "nodes", ")", "-", "1", "]", ",", "nodes", "[", "nroots", "]", "\n", "nroots", "++", "\n", "rootValue", "+=", "v", "\n", "}", "\n", "nodeMap", "[", "n", "]", "=", "node", "\n", "// Get all node names into an array.", "nodeArr", "=", "append", "(", "nodeArr", ",", "n", ".", "Info", ".", "Name", ")", "\n", "}", "\n", "// Populate the child links.", "for", "_", ",", "n", ":=", "range", "g", ".", "Nodes", "{", "node", ":=", "nodeMap", "[", "n", "]", "\n", "for", "child", ":=", "range", "n", ".", "Out", "{", "node", ".", "Children", "=", "append", "(", "node", ".", "Children", ",", "nodeMap", "[", "child", "]", ")", "\n", "}", "\n", "}", "\n\n", "rootNode", ":=", "&", "treeNode", "{", "Name", ":", "\"", "\"", ",", "FullName", ":", "\"", "\"", ",", "Cum", ":", "rootValue", ",", "CumFormat", ":", "config", ".", "FormatValue", "(", "rootValue", ")", ",", "Percent", ":", "strings", ".", "TrimSpace", "(", "measurement", ".", "Percentage", "(", "rootValue", ",", "config", ".", "Total", ")", ")", ",", "Children", ":", "nodes", "[", "0", ":", "nroots", "]", ",", "}", "\n\n", "// JSON marshalling flame graph", "b", ",", "err", ":=", "json", ".", "Marshal", "(", "rootNode", ")", "\n", "if", "err", "!=", "nil", "{", "http", ".", "Error", "(", "w", ",", "\"", "\"", ",", "http", ".", "StatusInternalServerError", ")", "\n", "ui", ".", "options", ".", "UI", ".", "PrintErr", "(", "err", ")", "\n", "return", "\n", "}", "\n\n", "ui", ".", "render", "(", "w", ",", "\"", "\"", ",", "rpt", ",", "errList", ",", "config", ".", "Labels", ",", "webArgs", "{", "FlameGraph", ":", "template", ".", "JS", "(", "b", ")", ",", "Nodes", ":", "nodeArr", ",", "}", ")", "\n", "}" ]
// flamegraph generates a web page containing a flamegraph.
[ "flamegraph", "generates", "a", "web", "page", "containing", "a", "flamegraph", "." ]
8358a9778bd1e48718ffcb96eb11ee061385bf62
https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/internal/driver/flamegraph.go#L38-L103
train
google/pprof
profile/merge.go
Compact
func (p *Profile) Compact() *Profile { p, _ = Merge([]*Profile{p}) return p }
go
func (p *Profile) Compact() *Profile { p, _ = Merge([]*Profile{p}) return p }
[ "func", "(", "p", "*", "Profile", ")", "Compact", "(", ")", "*", "Profile", "{", "p", ",", "_", "=", "Merge", "(", "[", "]", "*", "Profile", "{", "p", "}", ")", "\n", "return", "p", "\n", "}" ]
// Compact performs garbage collection on a profile to remove any // unreferenced fields. This is useful to reduce the size of a profile // after samples or locations have been removed.
[ "Compact", "performs", "garbage", "collection", "on", "a", "profile", "to", "remove", "any", "unreferenced", "fields", ".", "This", "is", "useful", "to", "reduce", "the", "size", "of", "a", "profile", "after", "samples", "or", "locations", "have", "been", "removed", "." ]
8358a9778bd1e48718ffcb96eb11ee061385bf62
https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/profile/merge.go#L27-L30
train
google/pprof
profile/merge.go
Merge
func Merge(srcs []*Profile) (*Profile, error) { if len(srcs) == 0 { return nil, fmt.Errorf("no profiles to merge") } p, err := combineHeaders(srcs) if err != nil { return nil, err } pm := &profileMerger{ p: p, samples: make(map[sampleKey]*Sample, len(srcs[0].Sample)), locations: make(map[locationKey]*Location, len(srcs[0].Location)), functions: make(map[functionKey]*Function, len(srcs[0].Function)), mappings: make(map[mappingKey]*Mapping, len(srcs[0].Mapping)), } for _, src := range srcs { // Clear the profile-specific hash tables pm.locationsByID = make(map[uint64]*Location, len(src.Location)) pm.functionsByID = make(map[uint64]*Function, len(src.Function)) pm.mappingsByID = make(map[uint64]mapInfo, len(src.Mapping)) if len(pm.mappings) == 0 && len(src.Mapping) > 0 { // The Mapping list has the property that the first mapping // represents the main binary. Take the first Mapping we see, // otherwise the operations below will add mappings in an // arbitrary order. pm.mapMapping(src.Mapping[0]) } for _, s := range src.Sample { if !isZeroSample(s) { pm.mapSample(s) } } } for _, s := range p.Sample { if isZeroSample(s) { // If there are any zero samples, re-merge the profile to GC // them. return Merge([]*Profile{p}) } } return p, nil }
go
func Merge(srcs []*Profile) (*Profile, error) { if len(srcs) == 0 { return nil, fmt.Errorf("no profiles to merge") } p, err := combineHeaders(srcs) if err != nil { return nil, err } pm := &profileMerger{ p: p, samples: make(map[sampleKey]*Sample, len(srcs[0].Sample)), locations: make(map[locationKey]*Location, len(srcs[0].Location)), functions: make(map[functionKey]*Function, len(srcs[0].Function)), mappings: make(map[mappingKey]*Mapping, len(srcs[0].Mapping)), } for _, src := range srcs { // Clear the profile-specific hash tables pm.locationsByID = make(map[uint64]*Location, len(src.Location)) pm.functionsByID = make(map[uint64]*Function, len(src.Function)) pm.mappingsByID = make(map[uint64]mapInfo, len(src.Mapping)) if len(pm.mappings) == 0 && len(src.Mapping) > 0 { // The Mapping list has the property that the first mapping // represents the main binary. Take the first Mapping we see, // otherwise the operations below will add mappings in an // arbitrary order. pm.mapMapping(src.Mapping[0]) } for _, s := range src.Sample { if !isZeroSample(s) { pm.mapSample(s) } } } for _, s := range p.Sample { if isZeroSample(s) { // If there are any zero samples, re-merge the profile to GC // them. return Merge([]*Profile{p}) } } return p, nil }
[ "func", "Merge", "(", "srcs", "[", "]", "*", "Profile", ")", "(", "*", "Profile", ",", "error", ")", "{", "if", "len", "(", "srcs", ")", "==", "0", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "p", ",", "err", ":=", "combineHeaders", "(", "srcs", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "pm", ":=", "&", "profileMerger", "{", "p", ":", "p", ",", "samples", ":", "make", "(", "map", "[", "sampleKey", "]", "*", "Sample", ",", "len", "(", "srcs", "[", "0", "]", ".", "Sample", ")", ")", ",", "locations", ":", "make", "(", "map", "[", "locationKey", "]", "*", "Location", ",", "len", "(", "srcs", "[", "0", "]", ".", "Location", ")", ")", ",", "functions", ":", "make", "(", "map", "[", "functionKey", "]", "*", "Function", ",", "len", "(", "srcs", "[", "0", "]", ".", "Function", ")", ")", ",", "mappings", ":", "make", "(", "map", "[", "mappingKey", "]", "*", "Mapping", ",", "len", "(", "srcs", "[", "0", "]", ".", "Mapping", ")", ")", ",", "}", "\n\n", "for", "_", ",", "src", ":=", "range", "srcs", "{", "// Clear the profile-specific hash tables", "pm", ".", "locationsByID", "=", "make", "(", "map", "[", "uint64", "]", "*", "Location", ",", "len", "(", "src", ".", "Location", ")", ")", "\n", "pm", ".", "functionsByID", "=", "make", "(", "map", "[", "uint64", "]", "*", "Function", ",", "len", "(", "src", ".", "Function", ")", ")", "\n", "pm", ".", "mappingsByID", "=", "make", "(", "map", "[", "uint64", "]", "mapInfo", ",", "len", "(", "src", ".", "Mapping", ")", ")", "\n\n", "if", "len", "(", "pm", ".", "mappings", ")", "==", "0", "&&", "len", "(", "src", ".", "Mapping", ")", ">", "0", "{", "// The Mapping list has the property that the first mapping", "// represents the main binary. Take the first Mapping we see,", "// otherwise the operations below will add mappings in an", "// arbitrary order.", "pm", ".", "mapMapping", "(", "src", ".", "Mapping", "[", "0", "]", ")", "\n", "}", "\n\n", "for", "_", ",", "s", ":=", "range", "src", ".", "Sample", "{", "if", "!", "isZeroSample", "(", "s", ")", "{", "pm", ".", "mapSample", "(", "s", ")", "\n", "}", "\n", "}", "\n", "}", "\n\n", "for", "_", ",", "s", ":=", "range", "p", ".", "Sample", "{", "if", "isZeroSample", "(", "s", ")", "{", "// If there are any zero samples, re-merge the profile to GC", "// them.", "return", "Merge", "(", "[", "]", "*", "Profile", "{", "p", "}", ")", "\n", "}", "\n", "}", "\n\n", "return", "p", ",", "nil", "\n", "}" ]
// Merge merges all the profiles in profs into a single Profile. // Returns a new profile independent of the input profiles. The merged // profile is compacted to eliminate unused samples, locations, // functions and mappings. Profiles must have identical profile sample // and period types or the merge will fail. profile.Period of the // resulting profile will be the maximum of all profiles, and // profile.TimeNanos will be the earliest nonzero one.
[ "Merge", "merges", "all", "the", "profiles", "in", "profs", "into", "a", "single", "Profile", ".", "Returns", "a", "new", "profile", "independent", "of", "the", "input", "profiles", ".", "The", "merged", "profile", "is", "compacted", "to", "eliminate", "unused", "samples", "locations", "functions", "and", "mappings", ".", "Profiles", "must", "have", "identical", "profile", "sample", "and", "period", "types", "or", "the", "merge", "will", "fail", ".", "profile", ".", "Period", "of", "the", "resulting", "profile", "will", "be", "the", "maximum", "of", "all", "profiles", "and", "profile", ".", "TimeNanos", "will", "be", "the", "earliest", "nonzero", "one", "." ]
8358a9778bd1e48718ffcb96eb11ee061385bf62
https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/profile/merge.go#L39-L86
train
google/pprof
profile/merge.go
Normalize
func (p *Profile) Normalize(pb *Profile) error { if err := p.compatible(pb); err != nil { return err } baseVals := make([]int64, len(p.SampleType)) for _, s := range pb.Sample { for i, v := range s.Value { baseVals[i] += v } } srcVals := make([]int64, len(p.SampleType)) for _, s := range p.Sample { for i, v := range s.Value { srcVals[i] += v } } normScale := make([]float64, len(baseVals)) for i := range baseVals { if srcVals[i] == 0 { normScale[i] = 0.0 } else { normScale[i] = float64(baseVals[i]) / float64(srcVals[i]) } } p.ScaleN(normScale) return nil }
go
func (p *Profile) Normalize(pb *Profile) error { if err := p.compatible(pb); err != nil { return err } baseVals := make([]int64, len(p.SampleType)) for _, s := range pb.Sample { for i, v := range s.Value { baseVals[i] += v } } srcVals := make([]int64, len(p.SampleType)) for _, s := range p.Sample { for i, v := range s.Value { srcVals[i] += v } } normScale := make([]float64, len(baseVals)) for i := range baseVals { if srcVals[i] == 0 { normScale[i] = 0.0 } else { normScale[i] = float64(baseVals[i]) / float64(srcVals[i]) } } p.ScaleN(normScale) return nil }
[ "func", "(", "p", "*", "Profile", ")", "Normalize", "(", "pb", "*", "Profile", ")", "error", "{", "if", "err", ":=", "p", ".", "compatible", "(", "pb", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "baseVals", ":=", "make", "(", "[", "]", "int64", ",", "len", "(", "p", ".", "SampleType", ")", ")", "\n", "for", "_", ",", "s", ":=", "range", "pb", ".", "Sample", "{", "for", "i", ",", "v", ":=", "range", "s", ".", "Value", "{", "baseVals", "[", "i", "]", "+=", "v", "\n", "}", "\n", "}", "\n\n", "srcVals", ":=", "make", "(", "[", "]", "int64", ",", "len", "(", "p", ".", "SampleType", ")", ")", "\n", "for", "_", ",", "s", ":=", "range", "p", ".", "Sample", "{", "for", "i", ",", "v", ":=", "range", "s", ".", "Value", "{", "srcVals", "[", "i", "]", "+=", "v", "\n", "}", "\n", "}", "\n\n", "normScale", ":=", "make", "(", "[", "]", "float64", ",", "len", "(", "baseVals", ")", ")", "\n", "for", "i", ":=", "range", "baseVals", "{", "if", "srcVals", "[", "i", "]", "==", "0", "{", "normScale", "[", "i", "]", "=", "0.0", "\n", "}", "else", "{", "normScale", "[", "i", "]", "=", "float64", "(", "baseVals", "[", "i", "]", ")", "/", "float64", "(", "srcVals", "[", "i", "]", ")", "\n", "}", "\n", "}", "\n", "p", ".", "ScaleN", "(", "normScale", ")", "\n", "return", "nil", "\n", "}" ]
// Normalize normalizes the source profile by multiplying each value in profile by the // ratio of the sum of the base profile's values of that sample type to the sum of the // source profile's value of that sample type.
[ "Normalize", "normalizes", "the", "source", "profile", "by", "multiplying", "each", "value", "in", "profile", "by", "the", "ratio", "of", "the", "sum", "of", "the", "base", "profile", "s", "values", "of", "that", "sample", "type", "to", "the", "sum", "of", "the", "source", "profile", "s", "value", "of", "that", "sample", "type", "." ]
8358a9778bd1e48718ffcb96eb11ee061385bf62
https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/profile/merge.go#L91-L121
train
google/pprof
profile/merge.go
key
func (sample *Sample) key() sampleKey { ids := make([]string, len(sample.Location)) for i, l := range sample.Location { ids[i] = strconv.FormatUint(l.ID, 16) } labels := make([]string, 0, len(sample.Label)) for k, v := range sample.Label { labels = append(labels, fmt.Sprintf("%q%q", k, v)) } sort.Strings(labels) numlabels := make([]string, 0, len(sample.NumLabel)) for k, v := range sample.NumLabel { numlabels = append(numlabels, fmt.Sprintf("%q%x%x", k, v, sample.NumUnit[k])) } sort.Strings(numlabels) return sampleKey{ strings.Join(ids, "|"), strings.Join(labels, ""), strings.Join(numlabels, ""), } }
go
func (sample *Sample) key() sampleKey { ids := make([]string, len(sample.Location)) for i, l := range sample.Location { ids[i] = strconv.FormatUint(l.ID, 16) } labels := make([]string, 0, len(sample.Label)) for k, v := range sample.Label { labels = append(labels, fmt.Sprintf("%q%q", k, v)) } sort.Strings(labels) numlabels := make([]string, 0, len(sample.NumLabel)) for k, v := range sample.NumLabel { numlabels = append(numlabels, fmt.Sprintf("%q%x%x", k, v, sample.NumUnit[k])) } sort.Strings(numlabels) return sampleKey{ strings.Join(ids, "|"), strings.Join(labels, ""), strings.Join(numlabels, ""), } }
[ "func", "(", "sample", "*", "Sample", ")", "key", "(", ")", "sampleKey", "{", "ids", ":=", "make", "(", "[", "]", "string", ",", "len", "(", "sample", ".", "Location", ")", ")", "\n", "for", "i", ",", "l", ":=", "range", "sample", ".", "Location", "{", "ids", "[", "i", "]", "=", "strconv", ".", "FormatUint", "(", "l", ".", "ID", ",", "16", ")", "\n", "}", "\n\n", "labels", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "sample", ".", "Label", ")", ")", "\n", "for", "k", ",", "v", ":=", "range", "sample", ".", "Label", "{", "labels", "=", "append", "(", "labels", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "k", ",", "v", ")", ")", "\n", "}", "\n", "sort", ".", "Strings", "(", "labels", ")", "\n\n", "numlabels", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "sample", ".", "NumLabel", ")", ")", "\n", "for", "k", ",", "v", ":=", "range", "sample", ".", "NumLabel", "{", "numlabels", "=", "append", "(", "numlabels", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "k", ",", "v", ",", "sample", ".", "NumUnit", "[", "k", "]", ")", ")", "\n", "}", "\n", "sort", ".", "Strings", "(", "numlabels", ")", "\n\n", "return", "sampleKey", "{", "strings", ".", "Join", "(", "ids", ",", "\"", "\"", ")", ",", "strings", ".", "Join", "(", "labels", ",", "\"", "\"", ")", ",", "strings", ".", "Join", "(", "numlabels", ",", "\"", "\"", ")", ",", "}", "\n", "}" ]
// key generates sampleKey to be used as a key for maps.
[ "key", "generates", "sampleKey", "to", "be", "used", "as", "a", "key", "for", "maps", "." ]
8358a9778bd1e48718ffcb96eb11ee061385bf62
https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/profile/merge.go#L194-L217
train
google/pprof
profile/merge.go
key
func (l *Location) key() locationKey { key := locationKey{ addr: l.Address, isFolded: l.IsFolded, } if l.Mapping != nil { // Normalizes address to handle address space randomization. key.addr -= l.Mapping.Start key.mappingID = l.Mapping.ID } lines := make([]string, len(l.Line)*2) for i, line := range l.Line { if line.Function != nil { lines[i*2] = strconv.FormatUint(line.Function.ID, 16) } lines[i*2+1] = strconv.FormatInt(line.Line, 16) } key.lines = strings.Join(lines, "|") return key }
go
func (l *Location) key() locationKey { key := locationKey{ addr: l.Address, isFolded: l.IsFolded, } if l.Mapping != nil { // Normalizes address to handle address space randomization. key.addr -= l.Mapping.Start key.mappingID = l.Mapping.ID } lines := make([]string, len(l.Line)*2) for i, line := range l.Line { if line.Function != nil { lines[i*2] = strconv.FormatUint(line.Function.ID, 16) } lines[i*2+1] = strconv.FormatInt(line.Line, 16) } key.lines = strings.Join(lines, "|") return key }
[ "func", "(", "l", "*", "Location", ")", "key", "(", ")", "locationKey", "{", "key", ":=", "locationKey", "{", "addr", ":", "l", ".", "Address", ",", "isFolded", ":", "l", ".", "IsFolded", ",", "}", "\n", "if", "l", ".", "Mapping", "!=", "nil", "{", "// Normalizes address to handle address space randomization.", "key", ".", "addr", "-=", "l", ".", "Mapping", ".", "Start", "\n", "key", ".", "mappingID", "=", "l", ".", "Mapping", ".", "ID", "\n", "}", "\n", "lines", ":=", "make", "(", "[", "]", "string", ",", "len", "(", "l", ".", "Line", ")", "*", "2", ")", "\n", "for", "i", ",", "line", ":=", "range", "l", ".", "Line", "{", "if", "line", ".", "Function", "!=", "nil", "{", "lines", "[", "i", "*", "2", "]", "=", "strconv", ".", "FormatUint", "(", "line", ".", "Function", ".", "ID", ",", "16", ")", "\n", "}", "\n", "lines", "[", "i", "*", "2", "+", "1", "]", "=", "strconv", ".", "FormatInt", "(", "line", ".", "Line", ",", "16", ")", "\n", "}", "\n", "key", ".", "lines", "=", "strings", ".", "Join", "(", "lines", ",", "\"", "\"", ")", "\n", "return", "key", "\n", "}" ]
// key generates locationKey to be used as a key for maps.
[ "key", "generates", "locationKey", "to", "be", "used", "as", "a", "key", "for", "maps", "." ]
8358a9778bd1e48718ffcb96eb11ee061385bf62
https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/profile/merge.go#L260-L279
train
google/pprof
profile/merge.go
key
func (m *Mapping) key() mappingKey { // Normalize addresses to handle address space randomization. // Round up to next 4K boundary to avoid minor discrepancies. const mapsizeRounding = 0x1000 size := m.Limit - m.Start size = size + mapsizeRounding - 1 size = size - (size % mapsizeRounding) key := mappingKey{ size: size, offset: m.Offset, } switch { case m.BuildID != "": key.buildIDOrFile = m.BuildID case m.File != "": key.buildIDOrFile = m.File default: // A mapping containing neither build ID nor file name is a fake mapping. A // key with empty buildIDOrFile is used for fake mappings so that they are // treated as the same mapping during merging. } return key }
go
func (m *Mapping) key() mappingKey { // Normalize addresses to handle address space randomization. // Round up to next 4K boundary to avoid minor discrepancies. const mapsizeRounding = 0x1000 size := m.Limit - m.Start size = size + mapsizeRounding - 1 size = size - (size % mapsizeRounding) key := mappingKey{ size: size, offset: m.Offset, } switch { case m.BuildID != "": key.buildIDOrFile = m.BuildID case m.File != "": key.buildIDOrFile = m.File default: // A mapping containing neither build ID nor file name is a fake mapping. A // key with empty buildIDOrFile is used for fake mappings so that they are // treated as the same mapping during merging. } return key }
[ "func", "(", "m", "*", "Mapping", ")", "key", "(", ")", "mappingKey", "{", "// Normalize addresses to handle address space randomization.", "// Round up to next 4K boundary to avoid minor discrepancies.", "const", "mapsizeRounding", "=", "0x1000", "\n\n", "size", ":=", "m", ".", "Limit", "-", "m", ".", "Start", "\n", "size", "=", "size", "+", "mapsizeRounding", "-", "1", "\n", "size", "=", "size", "-", "(", "size", "%", "mapsizeRounding", ")", "\n", "key", ":=", "mappingKey", "{", "size", ":", "size", ",", "offset", ":", "m", ".", "Offset", ",", "}", "\n\n", "switch", "{", "case", "m", ".", "BuildID", "!=", "\"", "\"", ":", "key", ".", "buildIDOrFile", "=", "m", ".", "BuildID", "\n", "case", "m", ".", "File", "!=", "\"", "\"", ":", "key", ".", "buildIDOrFile", "=", "m", ".", "File", "\n", "default", ":", "// A mapping containing neither build ID nor file name is a fake mapping. A", "// key with empty buildIDOrFile is used for fake mappings so that they are", "// treated as the same mapping during merging.", "}", "\n", "return", "key", "\n", "}" ]
// key generates encoded strings of Mapping to be used as a key for // maps.
[ "key", "generates", "encoded", "strings", "of", "Mapping", "to", "be", "used", "as", "a", "key", "for", "maps", "." ]
8358a9778bd1e48718ffcb96eb11ee061385bf62
https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/profile/merge.go#L326-L350
train
google/pprof
profile/merge.go
key
func (f *Function) key() functionKey { return functionKey{ f.StartLine, f.Name, f.SystemName, f.Filename, } }
go
func (f *Function) key() functionKey { return functionKey{ f.StartLine, f.Name, f.SystemName, f.Filename, } }
[ "func", "(", "f", "*", "Function", ")", "key", "(", ")", "functionKey", "{", "return", "functionKey", "{", "f", ".", "StartLine", ",", "f", ".", "Name", ",", "f", ".", "SystemName", ",", "f", ".", "Filename", ",", "}", "\n", "}" ]
// key generates a struct to be used as a key for maps.
[ "key", "generates", "a", "struct", "to", "be", "used", "as", "a", "key", "for", "maps", "." ]
8358a9778bd1e48718ffcb96eb11ee061385bf62
https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/profile/merge.go#L391-L398
train
google/pprof
profile/merge.go
combineHeaders
func combineHeaders(srcs []*Profile) (*Profile, error) { for _, s := range srcs[1:] { if err := srcs[0].compatible(s); err != nil { return nil, err } } var timeNanos, durationNanos, period int64 var comments []string seenComments := map[string]bool{} var defaultSampleType string for _, s := range srcs { if timeNanos == 0 || s.TimeNanos < timeNanos { timeNanos = s.TimeNanos } durationNanos += s.DurationNanos if period == 0 || period < s.Period { period = s.Period } for _, c := range s.Comments { if seen := seenComments[c]; !seen { comments = append(comments, c) seenComments[c] = true } } if defaultSampleType == "" { defaultSampleType = s.DefaultSampleType } } p := &Profile{ SampleType: make([]*ValueType, len(srcs[0].SampleType)), DropFrames: srcs[0].DropFrames, KeepFrames: srcs[0].KeepFrames, TimeNanos: timeNanos, DurationNanos: durationNanos, PeriodType: srcs[0].PeriodType, Period: period, Comments: comments, DefaultSampleType: defaultSampleType, } copy(p.SampleType, srcs[0].SampleType) return p, nil }
go
func combineHeaders(srcs []*Profile) (*Profile, error) { for _, s := range srcs[1:] { if err := srcs[0].compatible(s); err != nil { return nil, err } } var timeNanos, durationNanos, period int64 var comments []string seenComments := map[string]bool{} var defaultSampleType string for _, s := range srcs { if timeNanos == 0 || s.TimeNanos < timeNanos { timeNanos = s.TimeNanos } durationNanos += s.DurationNanos if period == 0 || period < s.Period { period = s.Period } for _, c := range s.Comments { if seen := seenComments[c]; !seen { comments = append(comments, c) seenComments[c] = true } } if defaultSampleType == "" { defaultSampleType = s.DefaultSampleType } } p := &Profile{ SampleType: make([]*ValueType, len(srcs[0].SampleType)), DropFrames: srcs[0].DropFrames, KeepFrames: srcs[0].KeepFrames, TimeNanos: timeNanos, DurationNanos: durationNanos, PeriodType: srcs[0].PeriodType, Period: period, Comments: comments, DefaultSampleType: defaultSampleType, } copy(p.SampleType, srcs[0].SampleType) return p, nil }
[ "func", "combineHeaders", "(", "srcs", "[", "]", "*", "Profile", ")", "(", "*", "Profile", ",", "error", ")", "{", "for", "_", ",", "s", ":=", "range", "srcs", "[", "1", ":", "]", "{", "if", "err", ":=", "srcs", "[", "0", "]", ".", "compatible", "(", "s", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n\n", "var", "timeNanos", ",", "durationNanos", ",", "period", "int64", "\n", "var", "comments", "[", "]", "string", "\n", "seenComments", ":=", "map", "[", "string", "]", "bool", "{", "}", "\n", "var", "defaultSampleType", "string", "\n", "for", "_", ",", "s", ":=", "range", "srcs", "{", "if", "timeNanos", "==", "0", "||", "s", ".", "TimeNanos", "<", "timeNanos", "{", "timeNanos", "=", "s", ".", "TimeNanos", "\n", "}", "\n", "durationNanos", "+=", "s", ".", "DurationNanos", "\n", "if", "period", "==", "0", "||", "period", "<", "s", ".", "Period", "{", "period", "=", "s", ".", "Period", "\n", "}", "\n", "for", "_", ",", "c", ":=", "range", "s", ".", "Comments", "{", "if", "seen", ":=", "seenComments", "[", "c", "]", ";", "!", "seen", "{", "comments", "=", "append", "(", "comments", ",", "c", ")", "\n", "seenComments", "[", "c", "]", "=", "true", "\n", "}", "\n", "}", "\n", "if", "defaultSampleType", "==", "\"", "\"", "{", "defaultSampleType", "=", "s", ".", "DefaultSampleType", "\n", "}", "\n", "}", "\n\n", "p", ":=", "&", "Profile", "{", "SampleType", ":", "make", "(", "[", "]", "*", "ValueType", ",", "len", "(", "srcs", "[", "0", "]", ".", "SampleType", ")", ")", ",", "DropFrames", ":", "srcs", "[", "0", "]", ".", "DropFrames", ",", "KeepFrames", ":", "srcs", "[", "0", "]", ".", "KeepFrames", ",", "TimeNanos", ":", "timeNanos", ",", "DurationNanos", ":", "durationNanos", ",", "PeriodType", ":", "srcs", "[", "0", "]", ".", "PeriodType", ",", "Period", ":", "period", ",", "Comments", ":", "comments", ",", "DefaultSampleType", ":", "defaultSampleType", ",", "}", "\n", "copy", "(", "p", ".", "SampleType", ",", "srcs", "[", "0", "]", ".", "SampleType", ")", "\n", "return", "p", ",", "nil", "\n", "}" ]
// combineHeaders checks that all profiles can be merged and returns // their combined profile.
[ "combineHeaders", "checks", "that", "all", "profiles", "can", "be", "merged", "and", "returns", "their", "combined", "profile", "." ]
8358a9778bd1e48718ffcb96eb11ee061385bf62
https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/profile/merge.go#L407-L453
train
google/pprof
internal/driver/flags.go
Bool
func (*GoFlags) Bool(o string, d bool, c string) *bool { return flag.Bool(o, d, c) }
go
func (*GoFlags) Bool(o string, d bool, c string) *bool { return flag.Bool(o, d, c) }
[ "func", "(", "*", "GoFlags", ")", "Bool", "(", "o", "string", ",", "d", "bool", ",", "c", "string", ")", "*", "bool", "{", "return", "flag", ".", "Bool", "(", "o", ",", "d", ",", "c", ")", "\n", "}" ]
// Bool implements the plugin.FlagSet interface.
[ "Bool", "implements", "the", "plugin", ".", "FlagSet", "interface", "." ]
8358a9778bd1e48718ffcb96eb11ee061385bf62
https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/internal/driver/flags.go#L28-L30
train
google/pprof
internal/driver/flags.go
Int
func (*GoFlags) Int(o string, d int, c string) *int { return flag.Int(o, d, c) }
go
func (*GoFlags) Int(o string, d int, c string) *int { return flag.Int(o, d, c) }
[ "func", "(", "*", "GoFlags", ")", "Int", "(", "o", "string", ",", "d", "int", ",", "c", "string", ")", "*", "int", "{", "return", "flag", ".", "Int", "(", "o", ",", "d", ",", "c", ")", "\n", "}" ]
// Int implements the plugin.FlagSet interface.
[ "Int", "implements", "the", "plugin", ".", "FlagSet", "interface", "." ]
8358a9778bd1e48718ffcb96eb11ee061385bf62
https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/internal/driver/flags.go#L33-L35
train
google/pprof
internal/driver/flags.go
Float64
func (*GoFlags) Float64(o string, d float64, c string) *float64 { return flag.Float64(o, d, c) }
go
func (*GoFlags) Float64(o string, d float64, c string) *float64 { return flag.Float64(o, d, c) }
[ "func", "(", "*", "GoFlags", ")", "Float64", "(", "o", "string", ",", "d", "float64", ",", "c", "string", ")", "*", "float64", "{", "return", "flag", ".", "Float64", "(", "o", ",", "d", ",", "c", ")", "\n", "}" ]
// Float64 implements the plugin.FlagSet interface.
[ "Float64", "implements", "the", "plugin", ".", "FlagSet", "interface", "." ]
8358a9778bd1e48718ffcb96eb11ee061385bf62
https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/internal/driver/flags.go#L38-L40
train
google/pprof
internal/driver/flags.go
BoolVar
func (*GoFlags) BoolVar(b *bool, o string, d bool, c string) { flag.BoolVar(b, o, d, c) }
go
func (*GoFlags) BoolVar(b *bool, o string, d bool, c string) { flag.BoolVar(b, o, d, c) }
[ "func", "(", "*", "GoFlags", ")", "BoolVar", "(", "b", "*", "bool", ",", "o", "string", ",", "d", "bool", ",", "c", "string", ")", "{", "flag", ".", "BoolVar", "(", "b", ",", "o", ",", "d", ",", "c", ")", "\n", "}" ]
// BoolVar implements the plugin.FlagSet interface.
[ "BoolVar", "implements", "the", "plugin", ".", "FlagSet", "interface", "." ]
8358a9778bd1e48718ffcb96eb11ee061385bf62
https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/internal/driver/flags.go#L48-L50
train
google/pprof
internal/driver/flags.go
IntVar
func (*GoFlags) IntVar(i *int, o string, d int, c string) { flag.IntVar(i, o, d, c) }
go
func (*GoFlags) IntVar(i *int, o string, d int, c string) { flag.IntVar(i, o, d, c) }
[ "func", "(", "*", "GoFlags", ")", "IntVar", "(", "i", "*", "int", ",", "o", "string", ",", "d", "int", ",", "c", "string", ")", "{", "flag", ".", "IntVar", "(", "i", ",", "o", ",", "d", ",", "c", ")", "\n", "}" ]
// IntVar implements the plugin.FlagSet interface.
[ "IntVar", "implements", "the", "plugin", ".", "FlagSet", "interface", "." ]
8358a9778bd1e48718ffcb96eb11ee061385bf62
https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/internal/driver/flags.go#L53-L55
train
google/pprof
internal/driver/flags.go
Float64Var
func (*GoFlags) Float64Var(f *float64, o string, d float64, c string) { flag.Float64Var(f, o, d, c) }
go
func (*GoFlags) Float64Var(f *float64, o string, d float64, c string) { flag.Float64Var(f, o, d, c) }
[ "func", "(", "*", "GoFlags", ")", "Float64Var", "(", "f", "*", "float64", ",", "o", "string", ",", "d", "float64", ",", "c", "string", ")", "{", "flag", ".", "Float64Var", "(", "f", ",", "o", ",", "d", ",", "c", ")", "\n", "}" ]
// Float64Var implements the plugin.FlagSet interface. // the value of the flag.
[ "Float64Var", "implements", "the", "plugin", ".", "FlagSet", "interface", ".", "the", "value", "of", "the", "flag", "." ]
8358a9778bd1e48718ffcb96eb11ee061385bf62
https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/internal/driver/flags.go#L59-L61
train
google/pprof
internal/driver/flags.go
StringVar
func (*GoFlags) StringVar(s *string, o, d, c string) { flag.StringVar(s, o, d, c) }
go
func (*GoFlags) StringVar(s *string, o, d, c string) { flag.StringVar(s, o, d, c) }
[ "func", "(", "*", "GoFlags", ")", "StringVar", "(", "s", "*", "string", ",", "o", ",", "d", ",", "c", "string", ")", "{", "flag", ".", "StringVar", "(", "s", ",", "o", ",", "d", ",", "c", ")", "\n", "}" ]
// StringVar implements the plugin.FlagSet interface.
[ "StringVar", "implements", "the", "plugin", ".", "FlagSet", "interface", "." ]
8358a9778bd1e48718ffcb96eb11ee061385bf62
https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/internal/driver/flags.go#L64-L66
train
google/pprof
internal/driver/flags.go
StringList
func (*GoFlags) StringList(o, d, c string) *[]*string { return &[]*string{flag.String(o, d, c)} }
go
func (*GoFlags) StringList(o, d, c string) *[]*string { return &[]*string{flag.String(o, d, c)} }
[ "func", "(", "*", "GoFlags", ")", "StringList", "(", "o", ",", "d", ",", "c", "string", ")", "*", "[", "]", "*", "string", "{", "return", "&", "[", "]", "*", "string", "{", "flag", ".", "String", "(", "o", ",", "d", ",", "c", ")", "}", "\n", "}" ]
// StringList implements the plugin.FlagSet interface.
[ "StringList", "implements", "the", "plugin", ".", "FlagSet", "interface", "." ]
8358a9778bd1e48718ffcb96eb11ee061385bf62
https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/internal/driver/flags.go#L69-L71
train
google/pprof
internal/driver/flags.go
AddExtraUsage
func (f *GoFlags) AddExtraUsage(eu string) { f.UsageMsgs = append(f.UsageMsgs, eu) }
go
func (f *GoFlags) AddExtraUsage(eu string) { f.UsageMsgs = append(f.UsageMsgs, eu) }
[ "func", "(", "f", "*", "GoFlags", ")", "AddExtraUsage", "(", "eu", "string", ")", "{", "f", ".", "UsageMsgs", "=", "append", "(", "f", ".", "UsageMsgs", ",", "eu", ")", "\n", "}" ]
// AddExtraUsage implements the plugin.FlagSet interface.
[ "AddExtraUsage", "implements", "the", "plugin", ".", "FlagSet", "interface", "." ]
8358a9778bd1e48718ffcb96eb11ee061385bf62
https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/internal/driver/flags.go#L79-L81
train
google/pprof
internal/driver/flags.go
Parse
func (*GoFlags) Parse(usage func()) []string { flag.Usage = usage flag.Parse() args := flag.Args() if len(args) == 0 { usage() } return args }
go
func (*GoFlags) Parse(usage func()) []string { flag.Usage = usage flag.Parse() args := flag.Args() if len(args) == 0 { usage() } return args }
[ "func", "(", "*", "GoFlags", ")", "Parse", "(", "usage", "func", "(", ")", ")", "[", "]", "string", "{", "flag", ".", "Usage", "=", "usage", "\n", "flag", ".", "Parse", "(", ")", "\n", "args", ":=", "flag", ".", "Args", "(", ")", "\n", "if", "len", "(", "args", ")", "==", "0", "{", "usage", "(", ")", "\n", "}", "\n", "return", "args", "\n", "}" ]
// Parse implements the plugin.FlagSet interface.
[ "Parse", "implements", "the", "plugin", ".", "FlagSet", "interface", "." ]
8358a9778bd1e48718ffcb96eb11ee061385bf62
https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/internal/driver/flags.go#L84-L92
train
google/pprof
internal/binutils/binutils.go
get
func (bu *Binutils) get() *binrep { bu.mu.Lock() r := bu.rep if r == nil { r = &binrep{} initTools(r, "") bu.rep = r } bu.mu.Unlock() return r }
go
func (bu *Binutils) get() *binrep { bu.mu.Lock() r := bu.rep if r == nil { r = &binrep{} initTools(r, "") bu.rep = r } bu.mu.Unlock() return r }
[ "func", "(", "bu", "*", "Binutils", ")", "get", "(", ")", "*", "binrep", "{", "bu", ".", "mu", ".", "Lock", "(", ")", "\n", "r", ":=", "bu", ".", "rep", "\n", "if", "r", "==", "nil", "{", "r", "=", "&", "binrep", "{", "}", "\n", "initTools", "(", "r", ",", "\"", "\"", ")", "\n", "bu", ".", "rep", "=", "r", "\n", "}", "\n", "bu", ".", "mu", ".", "Unlock", "(", ")", "\n", "return", "r", "\n", "}" ]
// get returns the current representation for bu, initializing it if necessary.
[ "get", "returns", "the", "current", "representation", "for", "bu", "initializing", "it", "if", "necessary", "." ]
8358a9778bd1e48718ffcb96eb11ee061385bf62
https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/internal/binutils/binutils.go#L61-L71
train
google/pprof
internal/binutils/binutils.go
update
func (bu *Binutils) update(fn func(r *binrep)) { r := &binrep{} bu.mu.Lock() defer bu.mu.Unlock() if bu.rep == nil { initTools(r, "") } else { *r = *bu.rep } fn(r) bu.rep = r }
go
func (bu *Binutils) update(fn func(r *binrep)) { r := &binrep{} bu.mu.Lock() defer bu.mu.Unlock() if bu.rep == nil { initTools(r, "") } else { *r = *bu.rep } fn(r) bu.rep = r }
[ "func", "(", "bu", "*", "Binutils", ")", "update", "(", "fn", "func", "(", "r", "*", "binrep", ")", ")", "{", "r", ":=", "&", "binrep", "{", "}", "\n", "bu", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "bu", ".", "mu", ".", "Unlock", "(", ")", "\n", "if", "bu", ".", "rep", "==", "nil", "{", "initTools", "(", "r", ",", "\"", "\"", ")", "\n", "}", "else", "{", "*", "r", "=", "*", "bu", ".", "rep", "\n", "}", "\n", "fn", "(", "r", ")", "\n", "bu", ".", "rep", "=", "r", "\n", "}" ]
// update modifies the rep for bu via the supplied function.
[ "update", "modifies", "the", "rep", "for", "bu", "via", "the", "supplied", "function", "." ]
8358a9778bd1e48718ffcb96eb11ee061385bf62
https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/internal/binutils/binutils.go#L74-L85
train
google/pprof
internal/binutils/binutils.go
String
func (bu *Binutils) String() string { r := bu.get() var llvmSymbolizer, addr2line, nm, objdump string if r.llvmSymbolizerFound { llvmSymbolizer = r.llvmSymbolizer } if r.addr2lineFound { addr2line = r.addr2line } if r.nmFound { nm = r.nm } if r.objdumpFound { objdump = r.objdump } return fmt.Sprintf("llvm-symbolizer=%q addr2line=%q nm=%q objdump=%q fast=%t", llvmSymbolizer, addr2line, nm, objdump, r.fast) }
go
func (bu *Binutils) String() string { r := bu.get() var llvmSymbolizer, addr2line, nm, objdump string if r.llvmSymbolizerFound { llvmSymbolizer = r.llvmSymbolizer } if r.addr2lineFound { addr2line = r.addr2line } if r.nmFound { nm = r.nm } if r.objdumpFound { objdump = r.objdump } return fmt.Sprintf("llvm-symbolizer=%q addr2line=%q nm=%q objdump=%q fast=%t", llvmSymbolizer, addr2line, nm, objdump, r.fast) }
[ "func", "(", "bu", "*", "Binutils", ")", "String", "(", ")", "string", "{", "r", ":=", "bu", ".", "get", "(", ")", "\n", "var", "llvmSymbolizer", ",", "addr2line", ",", "nm", ",", "objdump", "string", "\n", "if", "r", ".", "llvmSymbolizerFound", "{", "llvmSymbolizer", "=", "r", ".", "llvmSymbolizer", "\n", "}", "\n", "if", "r", ".", "addr2lineFound", "{", "addr2line", "=", "r", ".", "addr2line", "\n", "}", "\n", "if", "r", ".", "nmFound", "{", "nm", "=", "r", ".", "nm", "\n", "}", "\n", "if", "r", ".", "objdumpFound", "{", "objdump", "=", "r", ".", "objdump", "\n", "}", "\n", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "llvmSymbolizer", ",", "addr2line", ",", "nm", ",", "objdump", ",", "r", ".", "fast", ")", "\n", "}" ]
// String returns string representation of the binutils state for debug logging.
[ "String", "returns", "string", "representation", "of", "the", "binutils", "state", "for", "debug", "logging", "." ]
8358a9778bd1e48718ffcb96eb11ee061385bf62
https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/internal/binutils/binutils.go#L88-L105
train
google/pprof
internal/binutils/binutils.go
findExe
func findExe(cmd string, paths []string) (string, bool) { for _, p := range paths { cp := filepath.Join(p, cmd) if c, err := exec.LookPath(cp); err == nil { return c, true } } return cmd, false }
go
func findExe(cmd string, paths []string) (string, bool) { for _, p := range paths { cp := filepath.Join(p, cmd) if c, err := exec.LookPath(cp); err == nil { return c, true } } return cmd, false }
[ "func", "findExe", "(", "cmd", "string", ",", "paths", "[", "]", "string", ")", "(", "string", ",", "bool", ")", "{", "for", "_", ",", "p", ":=", "range", "paths", "{", "cp", ":=", "filepath", ".", "Join", "(", "p", ",", "cmd", ")", "\n", "if", "c", ",", "err", ":=", "exec", ".", "LookPath", "(", "cp", ")", ";", "err", "==", "nil", "{", "return", "c", ",", "true", "\n", "}", "\n", "}", "\n", "return", "cmd", ",", "false", "\n", "}" ]
// findExe looks for an executable command on a set of paths. // If it cannot find it, returns cmd.
[ "findExe", "looks", "for", "an", "executable", "command", "on", "a", "set", "of", "paths", ".", "If", "it", "cannot", "find", "it", "returns", "cmd", "." ]
8358a9778bd1e48718ffcb96eb11ee061385bf62
https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/internal/binutils/binutils.go#L148-L156
train
google/pprof
internal/binutils/binutils.go
Disasm
func (bu *Binutils) Disasm(file string, start, end uint64) ([]plugin.Inst, error) { b := bu.get() cmd := exec.Command(b.objdump, "-d", "-C", "--no-show-raw-insn", "-l", fmt.Sprintf("--start-address=%#x", start), fmt.Sprintf("--stop-address=%#x", end), file) out, err := cmd.Output() if err != nil { return nil, fmt.Errorf("%v: %v", cmd.Args, err) } return disassemble(out) }
go
func (bu *Binutils) Disasm(file string, start, end uint64) ([]plugin.Inst, error) { b := bu.get() cmd := exec.Command(b.objdump, "-d", "-C", "--no-show-raw-insn", "-l", fmt.Sprintf("--start-address=%#x", start), fmt.Sprintf("--stop-address=%#x", end), file) out, err := cmd.Output() if err != nil { return nil, fmt.Errorf("%v: %v", cmd.Args, err) } return disassemble(out) }
[ "func", "(", "bu", "*", "Binutils", ")", "Disasm", "(", "file", "string", ",", "start", ",", "end", "uint64", ")", "(", "[", "]", "plugin", ".", "Inst", ",", "error", ")", "{", "b", ":=", "bu", ".", "get", "(", ")", "\n", "cmd", ":=", "exec", ".", "Command", "(", "b", ".", "objdump", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "start", ")", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "end", ")", ",", "file", ")", "\n", "out", ",", "err", ":=", "cmd", ".", "Output", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "cmd", ".", "Args", ",", "err", ")", "\n", "}", "\n\n", "return", "disassemble", "(", "out", ")", "\n", "}" ]
// Disasm returns the assembly instructions for the specified address range // of a binary.
[ "Disasm", "returns", "the", "assembly", "instructions", "for", "the", "specified", "address", "range", "of", "a", "binary", "." ]
8358a9778bd1e48718ffcb96eb11ee061385bf62
https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/internal/binutils/binutils.go#L160-L172
train
google/pprof
internal/binutils/binutils.go
Open
func (bu *Binutils) Open(name string, start, limit, offset uint64) (plugin.ObjFile, error) { b := bu.get() // Make sure file is a supported executable. // This uses magic numbers, mainly to provide better error messages but // it should also help speed. if _, err := os.Stat(name); err != nil { // For testing, do not require file name to exist. if strings.Contains(b.addr2line, "testdata/") { return &fileAddr2Line{file: file{b: b, name: name}}, nil } return nil, err } // Read the first 4 bytes of the file. f, err := os.Open(name) if err != nil { return nil, fmt.Errorf("error opening %s: %v", name, err) } defer f.Close() var header [4]byte if _, err = io.ReadFull(f, header[:]); err != nil { return nil, fmt.Errorf("error reading magic number from %s: %v", name, err) } elfMagic := string(header[:]) // Match against supported file types. if elfMagic == elf.ELFMAG { f, err := b.openELF(name, start, limit, offset) if err != nil { return nil, fmt.Errorf("error reading ELF file %s: %v", name, err) } return f, nil } // Mach-O magic numbers can be big or little endian. machoMagicLittle := binary.LittleEndian.Uint32(header[:]) machoMagicBig := binary.BigEndian.Uint32(header[:]) if machoMagicLittle == macho.Magic32 || machoMagicLittle == macho.Magic64 || machoMagicBig == macho.Magic32 || machoMagicBig == macho.Magic64 { f, err := b.openMachO(name, start, limit, offset) if err != nil { return nil, fmt.Errorf("error reading Mach-O file %s: %v", name, err) } return f, nil } if machoMagicLittle == macho.MagicFat || machoMagicBig == macho.MagicFat { f, err := b.openFatMachO(name, start, limit, offset) if err != nil { return nil, fmt.Errorf("error reading fat Mach-O file %s: %v", name, err) } return f, nil } return nil, fmt.Errorf("unrecognized binary format: %s", name) }
go
func (bu *Binutils) Open(name string, start, limit, offset uint64) (plugin.ObjFile, error) { b := bu.get() // Make sure file is a supported executable. // This uses magic numbers, mainly to provide better error messages but // it should also help speed. if _, err := os.Stat(name); err != nil { // For testing, do not require file name to exist. if strings.Contains(b.addr2line, "testdata/") { return &fileAddr2Line{file: file{b: b, name: name}}, nil } return nil, err } // Read the first 4 bytes of the file. f, err := os.Open(name) if err != nil { return nil, fmt.Errorf("error opening %s: %v", name, err) } defer f.Close() var header [4]byte if _, err = io.ReadFull(f, header[:]); err != nil { return nil, fmt.Errorf("error reading magic number from %s: %v", name, err) } elfMagic := string(header[:]) // Match against supported file types. if elfMagic == elf.ELFMAG { f, err := b.openELF(name, start, limit, offset) if err != nil { return nil, fmt.Errorf("error reading ELF file %s: %v", name, err) } return f, nil } // Mach-O magic numbers can be big or little endian. machoMagicLittle := binary.LittleEndian.Uint32(header[:]) machoMagicBig := binary.BigEndian.Uint32(header[:]) if machoMagicLittle == macho.Magic32 || machoMagicLittle == macho.Magic64 || machoMagicBig == macho.Magic32 || machoMagicBig == macho.Magic64 { f, err := b.openMachO(name, start, limit, offset) if err != nil { return nil, fmt.Errorf("error reading Mach-O file %s: %v", name, err) } return f, nil } if machoMagicLittle == macho.MagicFat || machoMagicBig == macho.MagicFat { f, err := b.openFatMachO(name, start, limit, offset) if err != nil { return nil, fmt.Errorf("error reading fat Mach-O file %s: %v", name, err) } return f, nil } return nil, fmt.Errorf("unrecognized binary format: %s", name) }
[ "func", "(", "bu", "*", "Binutils", ")", "Open", "(", "name", "string", ",", "start", ",", "limit", ",", "offset", "uint64", ")", "(", "plugin", ".", "ObjFile", ",", "error", ")", "{", "b", ":=", "bu", ".", "get", "(", ")", "\n\n", "// Make sure file is a supported executable.", "// This uses magic numbers, mainly to provide better error messages but", "// it should also help speed.", "if", "_", ",", "err", ":=", "os", ".", "Stat", "(", "name", ")", ";", "err", "!=", "nil", "{", "// For testing, do not require file name to exist.", "if", "strings", ".", "Contains", "(", "b", ".", "addr2line", ",", "\"", "\"", ")", "{", "return", "&", "fileAddr2Line", "{", "file", ":", "file", "{", "b", ":", "b", ",", "name", ":", "name", "}", "}", ",", "nil", "\n", "}", "\n", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Read the first 4 bytes of the file.", "f", ",", "err", ":=", "os", ".", "Open", "(", "name", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "name", ",", "err", ")", "\n", "}", "\n", "defer", "f", ".", "Close", "(", ")", "\n\n", "var", "header", "[", "4", "]", "byte", "\n", "if", "_", ",", "err", "=", "io", ".", "ReadFull", "(", "f", ",", "header", "[", ":", "]", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "name", ",", "err", ")", "\n", "}", "\n\n", "elfMagic", ":=", "string", "(", "header", "[", ":", "]", ")", "\n\n", "// Match against supported file types.", "if", "elfMagic", "==", "elf", ".", "ELFMAG", "{", "f", ",", "err", ":=", "b", ".", "openELF", "(", "name", ",", "start", ",", "limit", ",", "offset", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "name", ",", "err", ")", "\n", "}", "\n", "return", "f", ",", "nil", "\n", "}", "\n\n", "// Mach-O magic numbers can be big or little endian.", "machoMagicLittle", ":=", "binary", ".", "LittleEndian", ".", "Uint32", "(", "header", "[", ":", "]", ")", "\n", "machoMagicBig", ":=", "binary", ".", "BigEndian", ".", "Uint32", "(", "header", "[", ":", "]", ")", "\n\n", "if", "machoMagicLittle", "==", "macho", ".", "Magic32", "||", "machoMagicLittle", "==", "macho", ".", "Magic64", "||", "machoMagicBig", "==", "macho", ".", "Magic32", "||", "machoMagicBig", "==", "macho", ".", "Magic64", "{", "f", ",", "err", ":=", "b", ".", "openMachO", "(", "name", ",", "start", ",", "limit", ",", "offset", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "name", ",", "err", ")", "\n", "}", "\n", "return", "f", ",", "nil", "\n", "}", "\n", "if", "machoMagicLittle", "==", "macho", ".", "MagicFat", "||", "machoMagicBig", "==", "macho", ".", "MagicFat", "{", "f", ",", "err", ":=", "b", ".", "openFatMachO", "(", "name", ",", "start", ",", "limit", ",", "offset", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "name", ",", "err", ")", "\n", "}", "\n", "return", "f", ",", "nil", "\n", "}", "\n\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "name", ")", "\n", "}" ]
// Open satisfies the plugin.ObjTool interface.
[ "Open", "satisfies", "the", "plugin", ".", "ObjTool", "interface", "." ]
8358a9778bd1e48718ffcb96eb11ee061385bf62
https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/internal/binutils/binutils.go#L175-L235
train
google/pprof
internal/binutils/addr2liner_llvm.go
newLLVMSymbolizer
func newLLVMSymbolizer(cmd, file string, base uint64) (*llvmSymbolizer, error) { if cmd == "" { cmd = defaultLLVMSymbolizer } j := &llvmSymbolizerJob{ cmd: exec.Command(cmd, "-inlining", "-demangle=false"), } var err error if j.in, err = j.cmd.StdinPipe(); err != nil { return nil, err } outPipe, err := j.cmd.StdoutPipe() if err != nil { return nil, err } j.out = bufio.NewReader(outPipe) if err := j.cmd.Start(); err != nil { return nil, err } a := &llvmSymbolizer{ filename: file, rw: j, base: base, } return a, nil }
go
func newLLVMSymbolizer(cmd, file string, base uint64) (*llvmSymbolizer, error) { if cmd == "" { cmd = defaultLLVMSymbolizer } j := &llvmSymbolizerJob{ cmd: exec.Command(cmd, "-inlining", "-demangle=false"), } var err error if j.in, err = j.cmd.StdinPipe(); err != nil { return nil, err } outPipe, err := j.cmd.StdoutPipe() if err != nil { return nil, err } j.out = bufio.NewReader(outPipe) if err := j.cmd.Start(); err != nil { return nil, err } a := &llvmSymbolizer{ filename: file, rw: j, base: base, } return a, nil }
[ "func", "newLLVMSymbolizer", "(", "cmd", ",", "file", "string", ",", "base", "uint64", ")", "(", "*", "llvmSymbolizer", ",", "error", ")", "{", "if", "cmd", "==", "\"", "\"", "{", "cmd", "=", "defaultLLVMSymbolizer", "\n", "}", "\n\n", "j", ":=", "&", "llvmSymbolizerJob", "{", "cmd", ":", "exec", ".", "Command", "(", "cmd", ",", "\"", "\"", ",", "\"", "\"", ")", ",", "}", "\n\n", "var", "err", "error", "\n", "if", "j", ".", "in", ",", "err", "=", "j", ".", "cmd", ".", "StdinPipe", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "outPipe", ",", "err", ":=", "j", ".", "cmd", ".", "StdoutPipe", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "j", ".", "out", "=", "bufio", ".", "NewReader", "(", "outPipe", ")", "\n", "if", "err", ":=", "j", ".", "cmd", ".", "Start", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "a", ":=", "&", "llvmSymbolizer", "{", "filename", ":", "file", ",", "rw", ":", "j", ",", "base", ":", "base", ",", "}", "\n\n", "return", "a", ",", "nil", "\n", "}" ]
// newLlvmSymbolizer starts the given llvmSymbolizer command reporting // information about the given executable file. If file is a shared // library, base should be the address at which it was mapped in the // program under consideration.
[ "newLlvmSymbolizer", "starts", "the", "given", "llvmSymbolizer", "command", "reporting", "information", "about", "the", "given", "executable", "file", ".", "If", "file", "is", "a", "shared", "library", "base", "should", "be", "the", "address", "at", "which", "it", "was", "mapped", "in", "the", "program", "under", "consideration", "." ]
8358a9778bd1e48718ffcb96eb11ee061385bf62
https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/internal/binutils/addr2liner_llvm.go#L67-L98
train
google/pprof
internal/binutils/addr2liner_llvm.go
readFrame
func (d *llvmSymbolizer) readFrame() (plugin.Frame, bool) { funcname, err := d.readString() if err != nil { return plugin.Frame{}, true } switch funcname { case "": return plugin.Frame{}, true case "??": funcname = "" } fileline, err := d.readString() if err != nil { return plugin.Frame{Func: funcname}, true } linenumber := 0 if fileline == "??:0" { fileline = "" } else { switch split := strings.Split(fileline, ":"); len(split) { case 1: // filename fileline = split[0] case 2, 3: // filename:line , or // filename:line:disc , or fileline = split[0] if line, err := strconv.Atoi(split[1]); err == nil { linenumber = line } default: // Unrecognized, ignore } } return plugin.Frame{Func: funcname, File: fileline, Line: linenumber}, false }
go
func (d *llvmSymbolizer) readFrame() (plugin.Frame, bool) { funcname, err := d.readString() if err != nil { return plugin.Frame{}, true } switch funcname { case "": return plugin.Frame{}, true case "??": funcname = "" } fileline, err := d.readString() if err != nil { return plugin.Frame{Func: funcname}, true } linenumber := 0 if fileline == "??:0" { fileline = "" } else { switch split := strings.Split(fileline, ":"); len(split) { case 1: // filename fileline = split[0] case 2, 3: // filename:line , or // filename:line:disc , or fileline = split[0] if line, err := strconv.Atoi(split[1]); err == nil { linenumber = line } default: // Unrecognized, ignore } } return plugin.Frame{Func: funcname, File: fileline, Line: linenumber}, false }
[ "func", "(", "d", "*", "llvmSymbolizer", ")", "readFrame", "(", ")", "(", "plugin", ".", "Frame", ",", "bool", ")", "{", "funcname", ",", "err", ":=", "d", ".", "readString", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "plugin", ".", "Frame", "{", "}", ",", "true", "\n", "}", "\n\n", "switch", "funcname", "{", "case", "\"", "\"", ":", "return", "plugin", ".", "Frame", "{", "}", ",", "true", "\n", "case", "\"", "\"", ":", "funcname", "=", "\"", "\"", "\n", "}", "\n\n", "fileline", ",", "err", ":=", "d", ".", "readString", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "plugin", ".", "Frame", "{", "Func", ":", "funcname", "}", ",", "true", "\n", "}", "\n\n", "linenumber", ":=", "0", "\n", "if", "fileline", "==", "\"", "\"", "{", "fileline", "=", "\"", "\"", "\n", "}", "else", "{", "switch", "split", ":=", "strings", ".", "Split", "(", "fileline", ",", "\"", "\"", ")", ";", "len", "(", "split", ")", "{", "case", "1", ":", "// filename", "fileline", "=", "split", "[", "0", "]", "\n", "case", "2", ",", "3", ":", "// filename:line , or", "// filename:line:disc , or", "fileline", "=", "split", "[", "0", "]", "\n", "if", "line", ",", "err", ":=", "strconv", ".", "Atoi", "(", "split", "[", "1", "]", ")", ";", "err", "==", "nil", "{", "linenumber", "=", "line", "\n", "}", "\n", "default", ":", "// Unrecognized, ignore", "}", "\n", "}", "\n\n", "return", "plugin", ".", "Frame", "{", "Func", ":", "funcname", ",", "File", ":", "fileline", ",", "Line", ":", "linenumber", "}", ",", "false", "\n", "}" ]
// readFrame parses the llvm-symbolizer output for a single address. It // returns a populated plugin.Frame and whether it has reached the end of the // data.
[ "readFrame", "parses", "the", "llvm", "-", "symbolizer", "output", "for", "a", "single", "address", ".", "It", "returns", "a", "populated", "plugin", ".", "Frame", "and", "whether", "it", "has", "reached", "the", "end", "of", "the", "data", "." ]
8358a9778bd1e48718ffcb96eb11ee061385bf62
https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/internal/binutils/addr2liner_llvm.go#L111-L150
train
google/pprof
internal/driver/cli.go
addBaseProfiles
func (source *source) addBaseProfiles(flagBase, flagDiffBase []*string) error { base, diffBase := dropEmpty(flagBase), dropEmpty(flagDiffBase) if len(base) > 0 && len(diffBase) > 0 { return errors.New("-base and -diff_base flags cannot both be specified") } source.Base = base if len(diffBase) > 0 { source.Base, source.DiffBase = diffBase, true } return nil }
go
func (source *source) addBaseProfiles(flagBase, flagDiffBase []*string) error { base, diffBase := dropEmpty(flagBase), dropEmpty(flagDiffBase) if len(base) > 0 && len(diffBase) > 0 { return errors.New("-base and -diff_base flags cannot both be specified") } source.Base = base if len(diffBase) > 0 { source.Base, source.DiffBase = diffBase, true } return nil }
[ "func", "(", "source", "*", "source", ")", "addBaseProfiles", "(", "flagBase", ",", "flagDiffBase", "[", "]", "*", "string", ")", "error", "{", "base", ",", "diffBase", ":=", "dropEmpty", "(", "flagBase", ")", ",", "dropEmpty", "(", "flagDiffBase", ")", "\n", "if", "len", "(", "base", ")", ">", "0", "&&", "len", "(", "diffBase", ")", ">", "0", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "source", ".", "Base", "=", "base", "\n", "if", "len", "(", "diffBase", ")", ">", "0", "{", "source", ".", "Base", ",", "source", ".", "DiffBase", "=", "diffBase", ",", "true", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// addBaseProfiles adds the list of base profiles or diff base profiles to // the source. This function will return an error if both base and diff base // profiles are specified.
[ "addBaseProfiles", "adds", "the", "list", "of", "base", "profiles", "or", "diff", "base", "profiles", "to", "the", "source", ".", "This", "function", "will", "return", "an", "error", "if", "both", "base", "and", "diff", "base", "profiles", "are", "specified", "." ]
8358a9778bd1e48718ffcb96eb11ee061385bf62
https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/internal/driver/cli.go#L172-L183
train
google/pprof
internal/driver/cli.go
dropEmpty
func dropEmpty(list []*string) []string { var l []string for _, s := range list { if *s != "" { l = append(l, *s) } } return l }
go
func dropEmpty(list []*string) []string { var l []string for _, s := range list { if *s != "" { l = append(l, *s) } } return l }
[ "func", "dropEmpty", "(", "list", "[", "]", "*", "string", ")", "[", "]", "string", "{", "var", "l", "[", "]", "string", "\n", "for", "_", ",", "s", ":=", "range", "list", "{", "if", "*", "s", "!=", "\"", "\"", "{", "l", "=", "append", "(", "l", ",", "*", "s", ")", "\n", "}", "\n", "}", "\n", "return", "l", "\n", "}" ]
// dropEmpty list takes a slice of string pointers, and outputs a slice of // non-empty strings associated with the flag.
[ "dropEmpty", "list", "takes", "a", "slice", "of", "string", "pointers", "and", "outputs", "a", "slice", "of", "non", "-", "empty", "strings", "associated", "with", "the", "flag", "." ]
8358a9778bd1e48718ffcb96eb11ee061385bf62
https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/internal/driver/cli.go#L187-L195
train
google/pprof
internal/driver/cli.go
installFlags
func installFlags(flag plugin.FlagSet) flagsInstalled { f := flagsInstalled{ ints: make(map[string]*int), bools: make(map[string]*bool), floats: make(map[string]*float64), strings: make(map[string]*string), } for n, v := range pprofVariables { switch v.kind { case boolKind: if v.group != "" { // Set all radio variables to false to identify conflicts. f.bools[n] = flag.Bool(n, false, v.help) } else { f.bools[n] = flag.Bool(n, v.boolValue(), v.help) } case intKind: f.ints[n] = flag.Int(n, v.intValue(), v.help) case floatKind: f.floats[n] = flag.Float64(n, v.floatValue(), v.help) case stringKind: f.strings[n] = flag.String(n, v.value, v.help) } } return f }
go
func installFlags(flag plugin.FlagSet) flagsInstalled { f := flagsInstalled{ ints: make(map[string]*int), bools: make(map[string]*bool), floats: make(map[string]*float64), strings: make(map[string]*string), } for n, v := range pprofVariables { switch v.kind { case boolKind: if v.group != "" { // Set all radio variables to false to identify conflicts. f.bools[n] = flag.Bool(n, false, v.help) } else { f.bools[n] = flag.Bool(n, v.boolValue(), v.help) } case intKind: f.ints[n] = flag.Int(n, v.intValue(), v.help) case floatKind: f.floats[n] = flag.Float64(n, v.floatValue(), v.help) case stringKind: f.strings[n] = flag.String(n, v.value, v.help) } } return f }
[ "func", "installFlags", "(", "flag", "plugin", ".", "FlagSet", ")", "flagsInstalled", "{", "f", ":=", "flagsInstalled", "{", "ints", ":", "make", "(", "map", "[", "string", "]", "*", "int", ")", ",", "bools", ":", "make", "(", "map", "[", "string", "]", "*", "bool", ")", ",", "floats", ":", "make", "(", "map", "[", "string", "]", "*", "float64", ")", ",", "strings", ":", "make", "(", "map", "[", "string", "]", "*", "string", ")", ",", "}", "\n", "for", "n", ",", "v", ":=", "range", "pprofVariables", "{", "switch", "v", ".", "kind", "{", "case", "boolKind", ":", "if", "v", ".", "group", "!=", "\"", "\"", "{", "// Set all radio variables to false to identify conflicts.", "f", ".", "bools", "[", "n", "]", "=", "flag", ".", "Bool", "(", "n", ",", "false", ",", "v", ".", "help", ")", "\n", "}", "else", "{", "f", ".", "bools", "[", "n", "]", "=", "flag", ".", "Bool", "(", "n", ",", "v", ".", "boolValue", "(", ")", ",", "v", ".", "help", ")", "\n", "}", "\n", "case", "intKind", ":", "f", ".", "ints", "[", "n", "]", "=", "flag", ".", "Int", "(", "n", ",", "v", ".", "intValue", "(", ")", ",", "v", ".", "help", ")", "\n", "case", "floatKind", ":", "f", ".", "floats", "[", "n", "]", "=", "flag", ".", "Float64", "(", "n", ",", "v", ".", "floatValue", "(", ")", ",", "v", ".", "help", ")", "\n", "case", "stringKind", ":", "f", ".", "strings", "[", "n", "]", "=", "flag", ".", "String", "(", "n", ",", "v", ".", "value", ",", "v", ".", "help", ")", "\n", "}", "\n", "}", "\n", "return", "f", "\n", "}" ]
// installFlags creates command line flags for pprof variables.
[ "installFlags", "creates", "command", "line", "flags", "for", "pprof", "variables", "." ]
8358a9778bd1e48718ffcb96eb11ee061385bf62
https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/internal/driver/cli.go#L198-L223
train
google/pprof
internal/driver/cli.go
updateFlags
func updateFlags(f flagsInstalled) error { vars := pprofVariables groups := map[string]string{} for n, v := range f.bools { vars.set(n, fmt.Sprint(*v)) if *v { g := vars[n].group if g != "" && groups[g] != "" { return fmt.Errorf("conflicting options %q and %q set", n, groups[g]) } groups[g] = n } } for n, v := range f.ints { vars.set(n, fmt.Sprint(*v)) } for n, v := range f.floats { vars.set(n, fmt.Sprint(*v)) } for n, v := range f.strings { vars.set(n, *v) } return nil }
go
func updateFlags(f flagsInstalled) error { vars := pprofVariables groups := map[string]string{} for n, v := range f.bools { vars.set(n, fmt.Sprint(*v)) if *v { g := vars[n].group if g != "" && groups[g] != "" { return fmt.Errorf("conflicting options %q and %q set", n, groups[g]) } groups[g] = n } } for n, v := range f.ints { vars.set(n, fmt.Sprint(*v)) } for n, v := range f.floats { vars.set(n, fmt.Sprint(*v)) } for n, v := range f.strings { vars.set(n, *v) } return nil }
[ "func", "updateFlags", "(", "f", "flagsInstalled", ")", "error", "{", "vars", ":=", "pprofVariables", "\n", "groups", ":=", "map", "[", "string", "]", "string", "{", "}", "\n", "for", "n", ",", "v", ":=", "range", "f", ".", "bools", "{", "vars", ".", "set", "(", "n", ",", "fmt", ".", "Sprint", "(", "*", "v", ")", ")", "\n", "if", "*", "v", "{", "g", ":=", "vars", "[", "n", "]", ".", "group", "\n", "if", "g", "!=", "\"", "\"", "&&", "groups", "[", "g", "]", "!=", "\"", "\"", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "n", ",", "groups", "[", "g", "]", ")", "\n", "}", "\n", "groups", "[", "g", "]", "=", "n", "\n", "}", "\n", "}", "\n", "for", "n", ",", "v", ":=", "range", "f", ".", "ints", "{", "vars", ".", "set", "(", "n", ",", "fmt", ".", "Sprint", "(", "*", "v", ")", ")", "\n", "}", "\n", "for", "n", ",", "v", ":=", "range", "f", ".", "floats", "{", "vars", ".", "set", "(", "n", ",", "fmt", ".", "Sprint", "(", "*", "v", ")", ")", "\n", "}", "\n", "for", "n", ",", "v", ":=", "range", "f", ".", "strings", "{", "vars", ".", "set", "(", "n", ",", "*", "v", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// updateFlags updates the pprof variables according to the flags // parsed in the command line.
[ "updateFlags", "updates", "the", "pprof", "variables", "according", "to", "the", "flags", "parsed", "in", "the", "command", "line", "." ]
8358a9778bd1e48718ffcb96eb11ee061385bf62
https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/internal/driver/cli.go#L227-L250
train
google/pprof
internal/graph/graph.go
FlatValue
func (n *Node) FlatValue() int64 { if n.FlatDiv == 0 { return n.Flat } return n.Flat / n.FlatDiv }
go
func (n *Node) FlatValue() int64 { if n.FlatDiv == 0 { return n.Flat } return n.Flat / n.FlatDiv }
[ "func", "(", "n", "*", "Node", ")", "FlatValue", "(", ")", "int64", "{", "if", "n", ".", "FlatDiv", "==", "0", "{", "return", "n", ".", "Flat", "\n", "}", "\n", "return", "n", ".", "Flat", "/", "n", ".", "FlatDiv", "\n", "}" ]
// FlatValue returns the exclusive value for this node, computing the // mean if a divisor is available.
[ "FlatValue", "returns", "the", "exclusive", "value", "for", "this", "node", "computing", "the", "mean", "if", "a", "divisor", "is", "available", "." ]
8358a9778bd1e48718ffcb96eb11ee061385bf62
https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/internal/graph/graph.go#L92-L97
train
google/pprof
internal/graph/graph.go
CumValue
func (n *Node) CumValue() int64 { if n.CumDiv == 0 { return n.Cum } return n.Cum / n.CumDiv }
go
func (n *Node) CumValue() int64 { if n.CumDiv == 0 { return n.Cum } return n.Cum / n.CumDiv }
[ "func", "(", "n", "*", "Node", ")", "CumValue", "(", ")", "int64", "{", "if", "n", ".", "CumDiv", "==", "0", "{", "return", "n", ".", "Cum", "\n", "}", "\n", "return", "n", ".", "Cum", "/", "n", ".", "CumDiv", "\n", "}" ]
// CumValue returns the inclusive value for this node, computing the // mean if a divisor is available.
[ "CumValue", "returns", "the", "inclusive", "value", "for", "this", "node", "computing", "the", "mean", "if", "a", "divisor", "is", "available", "." ]
8358a9778bd1e48718ffcb96eb11ee061385bf62
https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/internal/graph/graph.go#L101-L106
train
google/pprof
internal/graph/graph.go
AddToEdge
func (n *Node) AddToEdge(to *Node, v int64, residual, inline bool) { n.AddToEdgeDiv(to, 0, v, residual, inline) }
go
func (n *Node) AddToEdge(to *Node, v int64, residual, inline bool) { n.AddToEdgeDiv(to, 0, v, residual, inline) }
[ "func", "(", "n", "*", "Node", ")", "AddToEdge", "(", "to", "*", "Node", ",", "v", "int64", ",", "residual", ",", "inline", "bool", ")", "{", "n", ".", "AddToEdgeDiv", "(", "to", ",", "0", ",", "v", ",", "residual", ",", "inline", ")", "\n", "}" ]
// AddToEdge increases the weight of an edge between two nodes. If // there isn't such an edge one is created.
[ "AddToEdge", "increases", "the", "weight", "of", "an", "edge", "between", "two", "nodes", ".", "If", "there", "isn", "t", "such", "an", "edge", "one", "is", "created", "." ]
8358a9778bd1e48718ffcb96eb11ee061385bf62
https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/internal/graph/graph.go#L110-L112
train
google/pprof
internal/graph/graph.go
AddToEdgeDiv
func (n *Node) AddToEdgeDiv(to *Node, dv, v int64, residual, inline bool) { if n.Out[to] != to.In[n] { panic(fmt.Errorf("asymmetric edges %v %v", *n, *to)) } if e := n.Out[to]; e != nil { e.WeightDiv += dv e.Weight += v if residual { e.Residual = true } if !inline { e.Inline = false } return } info := &Edge{Src: n, Dest: to, WeightDiv: dv, Weight: v, Residual: residual, Inline: inline} n.Out[to] = info to.In[n] = info }
go
func (n *Node) AddToEdgeDiv(to *Node, dv, v int64, residual, inline bool) { if n.Out[to] != to.In[n] { panic(fmt.Errorf("asymmetric edges %v %v", *n, *to)) } if e := n.Out[to]; e != nil { e.WeightDiv += dv e.Weight += v if residual { e.Residual = true } if !inline { e.Inline = false } return } info := &Edge{Src: n, Dest: to, WeightDiv: dv, Weight: v, Residual: residual, Inline: inline} n.Out[to] = info to.In[n] = info }
[ "func", "(", "n", "*", "Node", ")", "AddToEdgeDiv", "(", "to", "*", "Node", ",", "dv", ",", "v", "int64", ",", "residual", ",", "inline", "bool", ")", "{", "if", "n", ".", "Out", "[", "to", "]", "!=", "to", ".", "In", "[", "n", "]", "{", "panic", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "*", "n", ",", "*", "to", ")", ")", "\n", "}", "\n\n", "if", "e", ":=", "n", ".", "Out", "[", "to", "]", ";", "e", "!=", "nil", "{", "e", ".", "WeightDiv", "+=", "dv", "\n", "e", ".", "Weight", "+=", "v", "\n", "if", "residual", "{", "e", ".", "Residual", "=", "true", "\n", "}", "\n", "if", "!", "inline", "{", "e", ".", "Inline", "=", "false", "\n", "}", "\n", "return", "\n", "}", "\n\n", "info", ":=", "&", "Edge", "{", "Src", ":", "n", ",", "Dest", ":", "to", ",", "WeightDiv", ":", "dv", ",", "Weight", ":", "v", ",", "Residual", ":", "residual", ",", "Inline", ":", "inline", "}", "\n", "n", ".", "Out", "[", "to", "]", "=", "info", "\n", "to", ".", "In", "[", "n", "]", "=", "info", "\n", "}" ]
// AddToEdgeDiv increases the weight of an edge between two nodes. If // there isn't such an edge one is created.
[ "AddToEdgeDiv", "increases", "the", "weight", "of", "an", "edge", "between", "two", "nodes", ".", "If", "there", "isn", "t", "such", "an", "edge", "one", "is", "created", "." ]
8358a9778bd1e48718ffcb96eb11ee061385bf62
https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/internal/graph/graph.go#L116-L136
train
google/pprof
internal/graph/graph.go
NameComponents
func (i *NodeInfo) NameComponents() []string { var name []string if i.Address != 0 { name = append(name, fmt.Sprintf("%016x", i.Address)) } if fun := i.Name; fun != "" { name = append(name, fun) } switch { case i.Lineno != 0: // User requested line numbers, provide what we have. name = append(name, fmt.Sprintf("%s:%d", i.File, i.Lineno)) case i.File != "": // User requested file name, provide it. name = append(name, i.File) case i.Name != "": // User requested function name. It was already included. case i.Objfile != "": // Only binary name is available name = append(name, "["+filepath.Base(i.Objfile)+"]") default: // Do not leave it empty if there is no information at all. name = append(name, "<unknown>") } return name }
go
func (i *NodeInfo) NameComponents() []string { var name []string if i.Address != 0 { name = append(name, fmt.Sprintf("%016x", i.Address)) } if fun := i.Name; fun != "" { name = append(name, fun) } switch { case i.Lineno != 0: // User requested line numbers, provide what we have. name = append(name, fmt.Sprintf("%s:%d", i.File, i.Lineno)) case i.File != "": // User requested file name, provide it. name = append(name, i.File) case i.Name != "": // User requested function name. It was already included. case i.Objfile != "": // Only binary name is available name = append(name, "["+filepath.Base(i.Objfile)+"]") default: // Do not leave it empty if there is no information at all. name = append(name, "<unknown>") } return name }
[ "func", "(", "i", "*", "NodeInfo", ")", "NameComponents", "(", ")", "[", "]", "string", "{", "var", "name", "[", "]", "string", "\n", "if", "i", ".", "Address", "!=", "0", "{", "name", "=", "append", "(", "name", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "i", ".", "Address", ")", ")", "\n", "}", "\n", "if", "fun", ":=", "i", ".", "Name", ";", "fun", "!=", "\"", "\"", "{", "name", "=", "append", "(", "name", ",", "fun", ")", "\n", "}", "\n\n", "switch", "{", "case", "i", ".", "Lineno", "!=", "0", ":", "// User requested line numbers, provide what we have.", "name", "=", "append", "(", "name", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "i", ".", "File", ",", "i", ".", "Lineno", ")", ")", "\n", "case", "i", ".", "File", "!=", "\"", "\"", ":", "// User requested file name, provide it.", "name", "=", "append", "(", "name", ",", "i", ".", "File", ")", "\n", "case", "i", ".", "Name", "!=", "\"", "\"", ":", "// User requested function name. It was already included.", "case", "i", ".", "Objfile", "!=", "\"", "\"", ":", "// Only binary name is available", "name", "=", "append", "(", "name", ",", "\"", "\"", "+", "filepath", ".", "Base", "(", "i", ".", "Objfile", ")", "+", "\"", "\"", ")", "\n", "default", ":", "// Do not leave it empty if there is no information at all.", "name", "=", "append", "(", "name", ",", "\"", "\"", ")", "\n", "}", "\n", "return", "name", "\n", "}" ]
// NameComponents returns the components of the printable name to be used for a node.
[ "NameComponents", "returns", "the", "components", "of", "the", "printable", "name", "to", "be", "used", "for", "a", "node", "." ]
8358a9778bd1e48718ffcb96eb11ee061385bf62
https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/internal/graph/graph.go#L154-L180
train
google/pprof
internal/graph/graph.go
FindOrInsertNode
func (nm NodeMap) FindOrInsertNode(info NodeInfo, kept NodeSet) *Node { if kept != nil { if _, ok := kept[info]; !ok { return nil } } if n, ok := nm[info]; ok { return n } n := &Node{ Info: info, In: make(EdgeMap), Out: make(EdgeMap), LabelTags: make(TagMap), NumericTags: make(map[string]TagMap), } nm[info] = n if info.Address == 0 && info.Lineno == 0 { // This node represents the whole function, so point Function // back to itself. n.Function = n return n } // Find a node that represents the whole function. info.Address = 0 info.Lineno = 0 n.Function = nm.FindOrInsertNode(info, nil) return n }
go
func (nm NodeMap) FindOrInsertNode(info NodeInfo, kept NodeSet) *Node { if kept != nil { if _, ok := kept[info]; !ok { return nil } } if n, ok := nm[info]; ok { return n } n := &Node{ Info: info, In: make(EdgeMap), Out: make(EdgeMap), LabelTags: make(TagMap), NumericTags: make(map[string]TagMap), } nm[info] = n if info.Address == 0 && info.Lineno == 0 { // This node represents the whole function, so point Function // back to itself. n.Function = n return n } // Find a node that represents the whole function. info.Address = 0 info.Lineno = 0 n.Function = nm.FindOrInsertNode(info, nil) return n }
[ "func", "(", "nm", "NodeMap", ")", "FindOrInsertNode", "(", "info", "NodeInfo", ",", "kept", "NodeSet", ")", "*", "Node", "{", "if", "kept", "!=", "nil", "{", "if", "_", ",", "ok", ":=", "kept", "[", "info", "]", ";", "!", "ok", "{", "return", "nil", "\n", "}", "\n", "}", "\n\n", "if", "n", ",", "ok", ":=", "nm", "[", "info", "]", ";", "ok", "{", "return", "n", "\n", "}", "\n\n", "n", ":=", "&", "Node", "{", "Info", ":", "info", ",", "In", ":", "make", "(", "EdgeMap", ")", ",", "Out", ":", "make", "(", "EdgeMap", ")", ",", "LabelTags", ":", "make", "(", "TagMap", ")", ",", "NumericTags", ":", "make", "(", "map", "[", "string", "]", "TagMap", ")", ",", "}", "\n", "nm", "[", "info", "]", "=", "n", "\n", "if", "info", ".", "Address", "==", "0", "&&", "info", ".", "Lineno", "==", "0", "{", "// This node represents the whole function, so point Function", "// back to itself.", "n", ".", "Function", "=", "n", "\n", "return", "n", "\n", "}", "\n", "// Find a node that represents the whole function.", "info", ".", "Address", "=", "0", "\n", "info", ".", "Lineno", "=", "0", "\n", "n", ".", "Function", "=", "nm", ".", "FindOrInsertNode", "(", "info", ",", "nil", ")", "\n", "return", "n", "\n", "}" ]
// FindOrInsertNode takes the info for a node and either returns a matching node // from the node map if one exists, or adds one to the map if one does not. // If kept is non-nil, nodes are only added if they can be located on it.
[ "FindOrInsertNode", "takes", "the", "info", "for", "a", "node", "and", "either", "returns", "a", "matching", "node", "from", "the", "node", "map", "if", "one", "exists", "or", "adds", "one", "to", "the", "map", "if", "one", "does", "not", ".", "If", "kept", "is", "non", "-", "nil", "nodes", "are", "only", "added", "if", "they", "can", "be", "located", "on", "it", "." ]
8358a9778bd1e48718ffcb96eb11ee061385bf62
https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/internal/graph/graph.go#L202-L232
train
google/pprof
internal/graph/graph.go
WeightValue
func (e *Edge) WeightValue() int64 { if e.WeightDiv == 0 { return e.Weight } return e.Weight / e.WeightDiv }
go
func (e *Edge) WeightValue() int64 { if e.WeightDiv == 0 { return e.Weight } return e.Weight / e.WeightDiv }
[ "func", "(", "e", "*", "Edge", ")", "WeightValue", "(", ")", "int64", "{", "if", "e", ".", "WeightDiv", "==", "0", "{", "return", "e", ".", "Weight", "\n", "}", "\n", "return", "e", ".", "Weight", "/", "e", ".", "WeightDiv", "\n", "}" ]
// WeightValue returns the weight value for this edge, normalizing if a // divisor is available.
[ "WeightValue", "returns", "the", "weight", "value", "for", "this", "edge", "normalizing", "if", "a", "divisor", "is", "available", "." ]
8358a9778bd1e48718ffcb96eb11ee061385bf62
https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/internal/graph/graph.go#L252-L257
train
google/pprof
internal/graph/graph.go
FlatValue
func (t *Tag) FlatValue() int64 { if t.FlatDiv == 0 { return t.Flat } return t.Flat / t.FlatDiv }
go
func (t *Tag) FlatValue() int64 { if t.FlatDiv == 0 { return t.Flat } return t.Flat / t.FlatDiv }
[ "func", "(", "t", "*", "Tag", ")", "FlatValue", "(", ")", "int64", "{", "if", "t", ".", "FlatDiv", "==", "0", "{", "return", "t", ".", "Flat", "\n", "}", "\n", "return", "t", ".", "Flat", "/", "t", ".", "FlatDiv", "\n", "}" ]
// FlatValue returns the exclusive value for this tag, computing the // mean if a divisor is available.
[ "FlatValue", "returns", "the", "exclusive", "value", "for", "this", "tag", "computing", "the", "mean", "if", "a", "divisor", "is", "available", "." ]
8358a9778bd1e48718ffcb96eb11ee061385bf62
https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/internal/graph/graph.go#L270-L275
train
google/pprof
internal/graph/graph.go
CumValue
func (t *Tag) CumValue() int64 { if t.CumDiv == 0 { return t.Cum } return t.Cum / t.CumDiv }
go
func (t *Tag) CumValue() int64 { if t.CumDiv == 0 { return t.Cum } return t.Cum / t.CumDiv }
[ "func", "(", "t", "*", "Tag", ")", "CumValue", "(", ")", "int64", "{", "if", "t", ".", "CumDiv", "==", "0", "{", "return", "t", ".", "Cum", "\n", "}", "\n", "return", "t", ".", "Cum", "/", "t", ".", "CumDiv", "\n", "}" ]
// CumValue returns the inclusive value for this tag, computing the // mean if a divisor is available.
[ "CumValue", "returns", "the", "inclusive", "value", "for", "this", "tag", "computing", "the", "mean", "if", "a", "divisor", "is", "available", "." ]
8358a9778bd1e48718ffcb96eb11ee061385bf62
https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/internal/graph/graph.go#L279-L284
train
google/pprof
internal/graph/graph.go
SortTags
func SortTags(t []*Tag, flat bool) []*Tag { ts := tags{t, flat} sort.Sort(ts) return ts.t }
go
func SortTags(t []*Tag, flat bool) []*Tag { ts := tags{t, flat} sort.Sort(ts) return ts.t }
[ "func", "SortTags", "(", "t", "[", "]", "*", "Tag", ",", "flat", "bool", ")", "[", "]", "*", "Tag", "{", "ts", ":=", "tags", "{", "t", ",", "flat", "}", "\n", "sort", ".", "Sort", "(", "ts", ")", "\n", "return", "ts", ".", "t", "\n", "}" ]
// SortTags sorts a slice of tags based on their weight.
[ "SortTags", "sorts", "a", "slice", "of", "tags", "based", "on", "their", "weight", "." ]
8358a9778bd1e48718ffcb96eb11ee061385bf62
https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/internal/graph/graph.go#L290-L294
train
google/pprof
internal/graph/graph.go
New
func New(prof *profile.Profile, o *Options) *Graph { if o.CallTree { return newTree(prof, o) } g, _ := newGraph(prof, o) return g }
go
func New(prof *profile.Profile, o *Options) *Graph { if o.CallTree { return newTree(prof, o) } g, _ := newGraph(prof, o) return g }
[ "func", "New", "(", "prof", "*", "profile", ".", "Profile", ",", "o", "*", "Options", ")", "*", "Graph", "{", "if", "o", ".", "CallTree", "{", "return", "newTree", "(", "prof", ",", "o", ")", "\n", "}", "\n", "g", ",", "_", ":=", "newGraph", "(", "prof", ",", "o", ")", "\n", "return", "g", "\n", "}" ]
// New summarizes performance data from a profile into a graph.
[ "New", "summarizes", "performance", "data", "from", "a", "profile", "into", "a", "graph", "." ]
8358a9778bd1e48718ffcb96eb11ee061385bf62
https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/internal/graph/graph.go#L297-L303
train
google/pprof
internal/graph/graph.go
newGraph
func newGraph(prof *profile.Profile, o *Options) (*Graph, map[uint64]Nodes) { nodes, locationMap := CreateNodes(prof, o) for _, sample := range prof.Sample { var w, dw int64 w = o.SampleValue(sample.Value) if o.SampleMeanDivisor != nil { dw = o.SampleMeanDivisor(sample.Value) } if dw == 0 && w == 0 { continue } seenNode := make(map[*Node]bool, len(sample.Location)) seenEdge := make(map[nodePair]bool, len(sample.Location)) var parent *Node // A residual edge goes over one or more nodes that were not kept. residual := false labels := joinLabels(sample) // Group the sample frames, based on a global map. for i := len(sample.Location) - 1; i >= 0; i-- { l := sample.Location[i] locNodes := locationMap[l.ID] for ni := len(locNodes) - 1; ni >= 0; ni-- { n := locNodes[ni] if n == nil { residual = true continue } // Add cum weight to all nodes in stack, avoiding double counting. if _, ok := seenNode[n]; !ok { seenNode[n] = true n.addSample(dw, w, labels, sample.NumLabel, sample.NumUnit, o.FormatTag, false) } // Update edge weights for all edges in stack, avoiding double counting. if _, ok := seenEdge[nodePair{n, parent}]; !ok && parent != nil && n != parent { seenEdge[nodePair{n, parent}] = true parent.AddToEdgeDiv(n, dw, w, residual, ni != len(locNodes)-1) } parent = n residual = false } } if parent != nil && !residual { // Add flat weight to leaf node. parent.addSample(dw, w, labels, sample.NumLabel, sample.NumUnit, o.FormatTag, true) } } return selectNodesForGraph(nodes, o.DropNegative), locationMap }
go
func newGraph(prof *profile.Profile, o *Options) (*Graph, map[uint64]Nodes) { nodes, locationMap := CreateNodes(prof, o) for _, sample := range prof.Sample { var w, dw int64 w = o.SampleValue(sample.Value) if o.SampleMeanDivisor != nil { dw = o.SampleMeanDivisor(sample.Value) } if dw == 0 && w == 0 { continue } seenNode := make(map[*Node]bool, len(sample.Location)) seenEdge := make(map[nodePair]bool, len(sample.Location)) var parent *Node // A residual edge goes over one or more nodes that were not kept. residual := false labels := joinLabels(sample) // Group the sample frames, based on a global map. for i := len(sample.Location) - 1; i >= 0; i-- { l := sample.Location[i] locNodes := locationMap[l.ID] for ni := len(locNodes) - 1; ni >= 0; ni-- { n := locNodes[ni] if n == nil { residual = true continue } // Add cum weight to all nodes in stack, avoiding double counting. if _, ok := seenNode[n]; !ok { seenNode[n] = true n.addSample(dw, w, labels, sample.NumLabel, sample.NumUnit, o.FormatTag, false) } // Update edge weights for all edges in stack, avoiding double counting. if _, ok := seenEdge[nodePair{n, parent}]; !ok && parent != nil && n != parent { seenEdge[nodePair{n, parent}] = true parent.AddToEdgeDiv(n, dw, w, residual, ni != len(locNodes)-1) } parent = n residual = false } } if parent != nil && !residual { // Add flat weight to leaf node. parent.addSample(dw, w, labels, sample.NumLabel, sample.NumUnit, o.FormatTag, true) } } return selectNodesForGraph(nodes, o.DropNegative), locationMap }
[ "func", "newGraph", "(", "prof", "*", "profile", ".", "Profile", ",", "o", "*", "Options", ")", "(", "*", "Graph", ",", "map", "[", "uint64", "]", "Nodes", ")", "{", "nodes", ",", "locationMap", ":=", "CreateNodes", "(", "prof", ",", "o", ")", "\n", "for", "_", ",", "sample", ":=", "range", "prof", ".", "Sample", "{", "var", "w", ",", "dw", "int64", "\n", "w", "=", "o", ".", "SampleValue", "(", "sample", ".", "Value", ")", "\n", "if", "o", ".", "SampleMeanDivisor", "!=", "nil", "{", "dw", "=", "o", ".", "SampleMeanDivisor", "(", "sample", ".", "Value", ")", "\n", "}", "\n", "if", "dw", "==", "0", "&&", "w", "==", "0", "{", "continue", "\n", "}", "\n", "seenNode", ":=", "make", "(", "map", "[", "*", "Node", "]", "bool", ",", "len", "(", "sample", ".", "Location", ")", ")", "\n", "seenEdge", ":=", "make", "(", "map", "[", "nodePair", "]", "bool", ",", "len", "(", "sample", ".", "Location", ")", ")", "\n", "var", "parent", "*", "Node", "\n", "// A residual edge goes over one or more nodes that were not kept.", "residual", ":=", "false", "\n\n", "labels", ":=", "joinLabels", "(", "sample", ")", "\n", "// Group the sample frames, based on a global map.", "for", "i", ":=", "len", "(", "sample", ".", "Location", ")", "-", "1", ";", "i", ">=", "0", ";", "i", "--", "{", "l", ":=", "sample", ".", "Location", "[", "i", "]", "\n", "locNodes", ":=", "locationMap", "[", "l", ".", "ID", "]", "\n", "for", "ni", ":=", "len", "(", "locNodes", ")", "-", "1", ";", "ni", ">=", "0", ";", "ni", "--", "{", "n", ":=", "locNodes", "[", "ni", "]", "\n", "if", "n", "==", "nil", "{", "residual", "=", "true", "\n", "continue", "\n", "}", "\n", "// Add cum weight to all nodes in stack, avoiding double counting.", "if", "_", ",", "ok", ":=", "seenNode", "[", "n", "]", ";", "!", "ok", "{", "seenNode", "[", "n", "]", "=", "true", "\n", "n", ".", "addSample", "(", "dw", ",", "w", ",", "labels", ",", "sample", ".", "NumLabel", ",", "sample", ".", "NumUnit", ",", "o", ".", "FormatTag", ",", "false", ")", "\n", "}", "\n", "// Update edge weights for all edges in stack, avoiding double counting.", "if", "_", ",", "ok", ":=", "seenEdge", "[", "nodePair", "{", "n", ",", "parent", "}", "]", ";", "!", "ok", "&&", "parent", "!=", "nil", "&&", "n", "!=", "parent", "{", "seenEdge", "[", "nodePair", "{", "n", ",", "parent", "}", "]", "=", "true", "\n", "parent", ".", "AddToEdgeDiv", "(", "n", ",", "dw", ",", "w", ",", "residual", ",", "ni", "!=", "len", "(", "locNodes", ")", "-", "1", ")", "\n", "}", "\n", "parent", "=", "n", "\n", "residual", "=", "false", "\n", "}", "\n", "}", "\n", "if", "parent", "!=", "nil", "&&", "!", "residual", "{", "// Add flat weight to leaf node.", "parent", ".", "addSample", "(", "dw", ",", "w", ",", "labels", ",", "sample", ".", "NumLabel", ",", "sample", ".", "NumUnit", ",", "o", ".", "FormatTag", ",", "true", ")", "\n", "}", "\n", "}", "\n\n", "return", "selectNodesForGraph", "(", "nodes", ",", "o", ".", "DropNegative", ")", ",", "locationMap", "\n", "}" ]
// newGraph computes a graph from a profile. It returns the graph, and // a map from the profile location indices to the corresponding graph // nodes.
[ "newGraph", "computes", "a", "graph", "from", "a", "profile", ".", "It", "returns", "the", "graph", "and", "a", "map", "from", "the", "profile", "location", "indices", "to", "the", "corresponding", "graph", "nodes", "." ]
8358a9778bd1e48718ffcb96eb11ee061385bf62
https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/internal/graph/graph.go#L308-L357
train
google/pprof
internal/graph/graph.go
ShortenFunctionName
func ShortenFunctionName(f string) string { for _, re := range []*regexp.Regexp{goRegExp, javaRegExp, cppRegExp} { if matches := re.FindStringSubmatch(f); len(matches) >= 2 { return strings.Join(matches[1:], "") } } return f }
go
func ShortenFunctionName(f string) string { for _, re := range []*regexp.Regexp{goRegExp, javaRegExp, cppRegExp} { if matches := re.FindStringSubmatch(f); len(matches) >= 2 { return strings.Join(matches[1:], "") } } return f }
[ "func", "ShortenFunctionName", "(", "f", "string", ")", "string", "{", "for", "_", ",", "re", ":=", "range", "[", "]", "*", "regexp", ".", "Regexp", "{", "goRegExp", ",", "javaRegExp", ",", "cppRegExp", "}", "{", "if", "matches", ":=", "re", ".", "FindStringSubmatch", "(", "f", ")", ";", "len", "(", "matches", ")", ">=", "2", "{", "return", "strings", ".", "Join", "(", "matches", "[", "1", ":", "]", ",", "\"", "\"", ")", "\n", "}", "\n", "}", "\n", "return", "f", "\n", "}" ]
// ShortenFunctionName returns a shortened version of a function's name.
[ "ShortenFunctionName", "returns", "a", "shortened", "version", "of", "a", "function", "s", "name", "." ]
8358a9778bd1e48718ffcb96eb11ee061385bf62
https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/internal/graph/graph.go#L431-L438
train
google/pprof
internal/graph/graph.go
TrimTree
func (g *Graph) TrimTree(kept NodePtrSet) { // Creates a new list of nodes oldNodes := g.Nodes g.Nodes = make(Nodes, 0, len(kept)) for _, cur := range oldNodes { // A node may not have multiple parents if len(cur.In) > 1 { panic("TrimTree only works on trees") } // If a node should be kept, add it to the new list of nodes if _, ok := kept[cur]; ok { g.Nodes = append(g.Nodes, cur) continue } // If a node has no parents, then delete all of the in edges of its // children to make them each roots of their own trees. if len(cur.In) == 0 { for _, outEdge := range cur.Out { delete(outEdge.Dest.In, cur) } continue } // Get the parent. This works since at this point cur.In must contain only // one element. if len(cur.In) != 1 { panic("Get parent assertion failed. cur.In expected to be of length 1.") } var parent *Node for _, edge := range cur.In { parent = edge.Src } parentEdgeInline := parent.Out[cur].Inline // Remove the edge from the parent to this node delete(parent.Out, cur) // Reconfigure every edge from the current node to now begin at the parent. for _, outEdge := range cur.Out { child := outEdge.Dest delete(child.In, cur) child.In[parent] = outEdge parent.Out[child] = outEdge outEdge.Src = parent outEdge.Residual = true // If the edge from the parent to the current node and the edge from the // current node to the child are both inline, then this resulting residual // edge should also be inline outEdge.Inline = parentEdgeInline && outEdge.Inline } } g.RemoveRedundantEdges() }
go
func (g *Graph) TrimTree(kept NodePtrSet) { // Creates a new list of nodes oldNodes := g.Nodes g.Nodes = make(Nodes, 0, len(kept)) for _, cur := range oldNodes { // A node may not have multiple parents if len(cur.In) > 1 { panic("TrimTree only works on trees") } // If a node should be kept, add it to the new list of nodes if _, ok := kept[cur]; ok { g.Nodes = append(g.Nodes, cur) continue } // If a node has no parents, then delete all of the in edges of its // children to make them each roots of their own trees. if len(cur.In) == 0 { for _, outEdge := range cur.Out { delete(outEdge.Dest.In, cur) } continue } // Get the parent. This works since at this point cur.In must contain only // one element. if len(cur.In) != 1 { panic("Get parent assertion failed. cur.In expected to be of length 1.") } var parent *Node for _, edge := range cur.In { parent = edge.Src } parentEdgeInline := parent.Out[cur].Inline // Remove the edge from the parent to this node delete(parent.Out, cur) // Reconfigure every edge from the current node to now begin at the parent. for _, outEdge := range cur.Out { child := outEdge.Dest delete(child.In, cur) child.In[parent] = outEdge parent.Out[child] = outEdge outEdge.Src = parent outEdge.Residual = true // If the edge from the parent to the current node and the edge from the // current node to the child are both inline, then this resulting residual // edge should also be inline outEdge.Inline = parentEdgeInline && outEdge.Inline } } g.RemoveRedundantEdges() }
[ "func", "(", "g", "*", "Graph", ")", "TrimTree", "(", "kept", "NodePtrSet", ")", "{", "// Creates a new list of nodes", "oldNodes", ":=", "g", ".", "Nodes", "\n", "g", ".", "Nodes", "=", "make", "(", "Nodes", ",", "0", ",", "len", "(", "kept", ")", ")", "\n\n", "for", "_", ",", "cur", ":=", "range", "oldNodes", "{", "// A node may not have multiple parents", "if", "len", "(", "cur", ".", "In", ")", ">", "1", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// If a node should be kept, add it to the new list of nodes", "if", "_", ",", "ok", ":=", "kept", "[", "cur", "]", ";", "ok", "{", "g", ".", "Nodes", "=", "append", "(", "g", ".", "Nodes", ",", "cur", ")", "\n", "continue", "\n", "}", "\n\n", "// If a node has no parents, then delete all of the in edges of its", "// children to make them each roots of their own trees.", "if", "len", "(", "cur", ".", "In", ")", "==", "0", "{", "for", "_", ",", "outEdge", ":=", "range", "cur", ".", "Out", "{", "delete", "(", "outEdge", ".", "Dest", ".", "In", ",", "cur", ")", "\n", "}", "\n", "continue", "\n", "}", "\n\n", "// Get the parent. This works since at this point cur.In must contain only", "// one element.", "if", "len", "(", "cur", ".", "In", ")", "!=", "1", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "var", "parent", "*", "Node", "\n", "for", "_", ",", "edge", ":=", "range", "cur", ".", "In", "{", "parent", "=", "edge", ".", "Src", "\n", "}", "\n\n", "parentEdgeInline", ":=", "parent", ".", "Out", "[", "cur", "]", ".", "Inline", "\n\n", "// Remove the edge from the parent to this node", "delete", "(", "parent", ".", "Out", ",", "cur", ")", "\n\n", "// Reconfigure every edge from the current node to now begin at the parent.", "for", "_", ",", "outEdge", ":=", "range", "cur", ".", "Out", "{", "child", ":=", "outEdge", ".", "Dest", "\n\n", "delete", "(", "child", ".", "In", ",", "cur", ")", "\n", "child", ".", "In", "[", "parent", "]", "=", "outEdge", "\n", "parent", ".", "Out", "[", "child", "]", "=", "outEdge", "\n\n", "outEdge", ".", "Src", "=", "parent", "\n", "outEdge", ".", "Residual", "=", "true", "\n", "// If the edge from the parent to the current node and the edge from the", "// current node to the child are both inline, then this resulting residual", "// edge should also be inline", "outEdge", ".", "Inline", "=", "parentEdgeInline", "&&", "outEdge", ".", "Inline", "\n", "}", "\n", "}", "\n", "g", ".", "RemoveRedundantEdges", "(", ")", "\n", "}" ]
// TrimTree trims a Graph in forest form, keeping only the nodes in kept. This // will not work correctly if even a single node has multiple parents.
[ "TrimTree", "trims", "a", "Graph", "in", "forest", "form", "keeping", "only", "the", "nodes", "in", "kept", ".", "This", "will", "not", "work", "correctly", "if", "even", "a", "single", "node", "has", "multiple", "parents", "." ]
8358a9778bd1e48718ffcb96eb11ee061385bf62
https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/internal/graph/graph.go#L442-L500
train
google/pprof
internal/graph/graph.go
isNegative
func isNegative(n *Node) bool { switch { case n.Flat < 0: return true case n.Flat == 0 && n.Cum < 0: return true default: return false } }
go
func isNegative(n *Node) bool { switch { case n.Flat < 0: return true case n.Flat == 0 && n.Cum < 0: return true default: return false } }
[ "func", "isNegative", "(", "n", "*", "Node", ")", "bool", "{", "switch", "{", "case", "n", ".", "Flat", "<", "0", ":", "return", "true", "\n", "case", "n", ".", "Flat", "==", "0", "&&", "n", ".", "Cum", "<", "0", ":", "return", "true", "\n", "default", ":", "return", "false", "\n", "}", "\n", "}" ]
// isNegative returns true if the node is considered as "negative" for the // purposes of drop_negative.
[ "isNegative", "returns", "true", "if", "the", "node", "is", "considered", "as", "negative", "for", "the", "purposes", "of", "drop_negative", "." ]
8358a9778bd1e48718ffcb96eb11ee061385bf62
https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/internal/graph/graph.go#L519-L528
train
google/pprof
internal/graph/graph.go
Sum
func (ns Nodes) Sum() (flat int64, cum int64) { for _, n := range ns { flat += n.Flat cum += n.Cum } return }
go
func (ns Nodes) Sum() (flat int64, cum int64) { for _, n := range ns { flat += n.Flat cum += n.Cum } return }
[ "func", "(", "ns", "Nodes", ")", "Sum", "(", ")", "(", "flat", "int64", ",", "cum", "int64", ")", "{", "for", "_", ",", "n", ":=", "range", "ns", "{", "flat", "+=", "n", ".", "Flat", "\n", "cum", "+=", "n", ".", "Cum", "\n", "}", "\n", "return", "\n", "}" ]
// Sum adds the flat and cum values of a set of nodes.
[ "Sum", "adds", "the", "flat", "and", "cum", "values", "of", "a", "set", "of", "nodes", "." ]
8358a9778bd1e48718ffcb96eb11ee061385bf62
https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/internal/graph/graph.go#L612-L618
train
google/pprof
internal/graph/graph.go
String
func (g *Graph) String() string { var s []string nodeIndex := make(map[*Node]int, len(g.Nodes)) for i, n := range g.Nodes { nodeIndex[n] = i + 1 } for i, n := range g.Nodes { name := n.Info.PrintableName() var in, out []int for _, from := range n.In { in = append(in, nodeIndex[from.Src]) } for _, to := range n.Out { out = append(out, nodeIndex[to.Dest]) } s = append(s, fmt.Sprintf("%d: %s[flat=%d cum=%d] %x -> %v ", i+1, name, n.Flat, n.Cum, in, out)) } return strings.Join(s, "\n") }
go
func (g *Graph) String() string { var s []string nodeIndex := make(map[*Node]int, len(g.Nodes)) for i, n := range g.Nodes { nodeIndex[n] = i + 1 } for i, n := range g.Nodes { name := n.Info.PrintableName() var in, out []int for _, from := range n.In { in = append(in, nodeIndex[from.Src]) } for _, to := range n.Out { out = append(out, nodeIndex[to.Dest]) } s = append(s, fmt.Sprintf("%d: %s[flat=%d cum=%d] %x -> %v ", i+1, name, n.Flat, n.Cum, in, out)) } return strings.Join(s, "\n") }
[ "func", "(", "g", "*", "Graph", ")", "String", "(", ")", "string", "{", "var", "s", "[", "]", "string", "\n\n", "nodeIndex", ":=", "make", "(", "map", "[", "*", "Node", "]", "int", ",", "len", "(", "g", ".", "Nodes", ")", ")", "\n\n", "for", "i", ",", "n", ":=", "range", "g", ".", "Nodes", "{", "nodeIndex", "[", "n", "]", "=", "i", "+", "1", "\n", "}", "\n\n", "for", "i", ",", "n", ":=", "range", "g", ".", "Nodes", "{", "name", ":=", "n", ".", "Info", ".", "PrintableName", "(", ")", "\n", "var", "in", ",", "out", "[", "]", "int", "\n\n", "for", "_", ",", "from", ":=", "range", "n", ".", "In", "{", "in", "=", "append", "(", "in", ",", "nodeIndex", "[", "from", ".", "Src", "]", ")", "\n", "}", "\n", "for", "_", ",", "to", ":=", "range", "n", ".", "Out", "{", "out", "=", "append", "(", "out", ",", "nodeIndex", "[", "to", ".", "Dest", "]", ")", "\n", "}", "\n", "s", "=", "append", "(", "s", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "i", "+", "1", ",", "name", ",", "n", ".", "Flat", ",", "n", ".", "Cum", ",", "in", ",", "out", ")", ")", "\n", "}", "\n", "return", "strings", ".", "Join", "(", "s", ",", "\"", "\\n", "\"", ")", "\n", "}" ]
// String returns a text representation of a graph, for debugging purposes.
[ "String", "returns", "a", "text", "representation", "of", "a", "graph", "for", "debugging", "purposes", "." ]
8358a9778bd1e48718ffcb96eb11ee061385bf62
https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/internal/graph/graph.go#L689-L711
train
google/pprof
internal/graph/graph.go
DiscardLowFrequencyNodes
func (g *Graph) DiscardLowFrequencyNodes(nodeCutoff int64) NodeSet { return makeNodeSet(g.Nodes, nodeCutoff) }
go
func (g *Graph) DiscardLowFrequencyNodes(nodeCutoff int64) NodeSet { return makeNodeSet(g.Nodes, nodeCutoff) }
[ "func", "(", "g", "*", "Graph", ")", "DiscardLowFrequencyNodes", "(", "nodeCutoff", "int64", ")", "NodeSet", "{", "return", "makeNodeSet", "(", "g", ".", "Nodes", ",", "nodeCutoff", ")", "\n", "}" ]
// DiscardLowFrequencyNodes returns a set of the nodes at or over a // specific cum value cutoff.
[ "DiscardLowFrequencyNodes", "returns", "a", "set", "of", "the", "nodes", "at", "or", "over", "a", "specific", "cum", "value", "cutoff", "." ]
8358a9778bd1e48718ffcb96eb11ee061385bf62
https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/internal/graph/graph.go#L715-L717
train
google/pprof
internal/graph/graph.go
DiscardLowFrequencyNodePtrs
func (g *Graph) DiscardLowFrequencyNodePtrs(nodeCutoff int64) NodePtrSet { cutNodes := getNodesAboveCumCutoff(g.Nodes, nodeCutoff) kept := make(NodePtrSet, len(cutNodes)) for _, n := range cutNodes { kept[n] = true } return kept }
go
func (g *Graph) DiscardLowFrequencyNodePtrs(nodeCutoff int64) NodePtrSet { cutNodes := getNodesAboveCumCutoff(g.Nodes, nodeCutoff) kept := make(NodePtrSet, len(cutNodes)) for _, n := range cutNodes { kept[n] = true } return kept }
[ "func", "(", "g", "*", "Graph", ")", "DiscardLowFrequencyNodePtrs", "(", "nodeCutoff", "int64", ")", "NodePtrSet", "{", "cutNodes", ":=", "getNodesAboveCumCutoff", "(", "g", ".", "Nodes", ",", "nodeCutoff", ")", "\n", "kept", ":=", "make", "(", "NodePtrSet", ",", "len", "(", "cutNodes", ")", ")", "\n", "for", "_", ",", "n", ":=", "range", "cutNodes", "{", "kept", "[", "n", "]", "=", "true", "\n", "}", "\n", "return", "kept", "\n", "}" ]
// DiscardLowFrequencyNodePtrs returns a NodePtrSet of nodes at or over a // specific cum value cutoff.
[ "DiscardLowFrequencyNodePtrs", "returns", "a", "NodePtrSet", "of", "nodes", "at", "or", "over", "a", "specific", "cum", "value", "cutoff", "." ]
8358a9778bd1e48718ffcb96eb11ee061385bf62
https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/internal/graph/graph.go#L721-L728
train
google/pprof
internal/graph/graph.go
getNodesAboveCumCutoff
func getNodesAboveCumCutoff(nodes Nodes, nodeCutoff int64) Nodes { cutoffNodes := make(Nodes, 0, len(nodes)) for _, n := range nodes { if abs64(n.Cum) < nodeCutoff { continue } cutoffNodes = append(cutoffNodes, n) } return cutoffNodes }
go
func getNodesAboveCumCutoff(nodes Nodes, nodeCutoff int64) Nodes { cutoffNodes := make(Nodes, 0, len(nodes)) for _, n := range nodes { if abs64(n.Cum) < nodeCutoff { continue } cutoffNodes = append(cutoffNodes, n) } return cutoffNodes }
[ "func", "getNodesAboveCumCutoff", "(", "nodes", "Nodes", ",", "nodeCutoff", "int64", ")", "Nodes", "{", "cutoffNodes", ":=", "make", "(", "Nodes", ",", "0", ",", "len", "(", "nodes", ")", ")", "\n", "for", "_", ",", "n", ":=", "range", "nodes", "{", "if", "abs64", "(", "n", ".", "Cum", ")", "<", "nodeCutoff", "{", "continue", "\n", "}", "\n", "cutoffNodes", "=", "append", "(", "cutoffNodes", ",", "n", ")", "\n", "}", "\n", "return", "cutoffNodes", "\n", "}" ]
// getNodesAboveCumCutoff returns all the nodes which have a Cum value greater // than or equal to cutoff.
[ "getNodesAboveCumCutoff", "returns", "all", "the", "nodes", "which", "have", "a", "Cum", "value", "greater", "than", "or", "equal", "to", "cutoff", "." ]
8358a9778bd1e48718ffcb96eb11ee061385bf62
https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/internal/graph/graph.go#L741-L750
train
google/pprof
internal/graph/graph.go
TrimLowFrequencyTags
func (g *Graph) TrimLowFrequencyTags(tagCutoff int64) { // Remove nodes with value <= total*nodeFraction for _, n := range g.Nodes { n.LabelTags = trimLowFreqTags(n.LabelTags, tagCutoff) for s, nt := range n.NumericTags { n.NumericTags[s] = trimLowFreqTags(nt, tagCutoff) } } }
go
func (g *Graph) TrimLowFrequencyTags(tagCutoff int64) { // Remove nodes with value <= total*nodeFraction for _, n := range g.Nodes { n.LabelTags = trimLowFreqTags(n.LabelTags, tagCutoff) for s, nt := range n.NumericTags { n.NumericTags[s] = trimLowFreqTags(nt, tagCutoff) } } }
[ "func", "(", "g", "*", "Graph", ")", "TrimLowFrequencyTags", "(", "tagCutoff", "int64", ")", "{", "// Remove nodes with value <= total*nodeFraction", "for", "_", ",", "n", ":=", "range", "g", ".", "Nodes", "{", "n", ".", "LabelTags", "=", "trimLowFreqTags", "(", "n", ".", "LabelTags", ",", "tagCutoff", ")", "\n", "for", "s", ",", "nt", ":=", "range", "n", ".", "NumericTags", "{", "n", ".", "NumericTags", "[", "s", "]", "=", "trimLowFreqTags", "(", "nt", ",", "tagCutoff", ")", "\n", "}", "\n", "}", "\n", "}" ]
// TrimLowFrequencyTags removes tags that have less than // the specified weight.
[ "TrimLowFrequencyTags", "removes", "tags", "that", "have", "less", "than", "the", "specified", "weight", "." ]
8358a9778bd1e48718ffcb96eb11ee061385bf62
https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/internal/graph/graph.go#L754-L762
train
google/pprof
internal/graph/graph.go
TrimLowFrequencyEdges
func (g *Graph) TrimLowFrequencyEdges(edgeCutoff int64) int { var droppedEdges int for _, n := range g.Nodes { for src, e := range n.In { if abs64(e.Weight) < edgeCutoff { delete(n.In, src) delete(src.Out, n) droppedEdges++ } } } return droppedEdges }
go
func (g *Graph) TrimLowFrequencyEdges(edgeCutoff int64) int { var droppedEdges int for _, n := range g.Nodes { for src, e := range n.In { if abs64(e.Weight) < edgeCutoff { delete(n.In, src) delete(src.Out, n) droppedEdges++ } } } return droppedEdges }
[ "func", "(", "g", "*", "Graph", ")", "TrimLowFrequencyEdges", "(", "edgeCutoff", "int64", ")", "int", "{", "var", "droppedEdges", "int", "\n", "for", "_", ",", "n", ":=", "range", "g", ".", "Nodes", "{", "for", "src", ",", "e", ":=", "range", "n", ".", "In", "{", "if", "abs64", "(", "e", ".", "Weight", ")", "<", "edgeCutoff", "{", "delete", "(", "n", ".", "In", ",", "src", ")", "\n", "delete", "(", "src", ".", "Out", ",", "n", ")", "\n", "droppedEdges", "++", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "droppedEdges", "\n", "}" ]
// TrimLowFrequencyEdges removes edges that have less than // the specified weight. Returns the number of edges removed
[ "TrimLowFrequencyEdges", "removes", "edges", "that", "have", "less", "than", "the", "specified", "weight", ".", "Returns", "the", "number", "of", "edges", "removed" ]
8358a9778bd1e48718ffcb96eb11ee061385bf62
https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/internal/graph/graph.go#L776-L788
train
google/pprof
internal/graph/graph.go
SortNodes
func (g *Graph) SortNodes(cum bool, visualMode bool) { // Sort nodes based on requested mode switch { case visualMode: // Specialized sort to produce a more visually-interesting graph g.Nodes.Sort(EntropyOrder) case cum: g.Nodes.Sort(CumNameOrder) default: g.Nodes.Sort(FlatNameOrder) } }
go
func (g *Graph) SortNodes(cum bool, visualMode bool) { // Sort nodes based on requested mode switch { case visualMode: // Specialized sort to produce a more visually-interesting graph g.Nodes.Sort(EntropyOrder) case cum: g.Nodes.Sort(CumNameOrder) default: g.Nodes.Sort(FlatNameOrder) } }
[ "func", "(", "g", "*", "Graph", ")", "SortNodes", "(", "cum", "bool", ",", "visualMode", "bool", ")", "{", "// Sort nodes based on requested mode", "switch", "{", "case", "visualMode", ":", "// Specialized sort to produce a more visually-interesting graph", "g", ".", "Nodes", ".", "Sort", "(", "EntropyOrder", ")", "\n", "case", "cum", ":", "g", ".", "Nodes", ".", "Sort", "(", "CumNameOrder", ")", "\n", "default", ":", "g", ".", "Nodes", ".", "Sort", "(", "FlatNameOrder", ")", "\n", "}", "\n", "}" ]
// SortNodes sorts the nodes in a graph based on a specific heuristic.
[ "SortNodes", "sorts", "the", "nodes", "in", "a", "graph", "based", "on", "a", "specific", "heuristic", "." ]
8358a9778bd1e48718ffcb96eb11ee061385bf62
https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/internal/graph/graph.go#L791-L802
train
google/pprof
internal/graph/graph.go
SelectTopNodes
func (g *Graph) SelectTopNodes(maxNodes int, visualMode bool) NodeSet { return makeNodeSet(g.selectTopNodes(maxNodes, visualMode), 0) }
go
func (g *Graph) SelectTopNodes(maxNodes int, visualMode bool) NodeSet { return makeNodeSet(g.selectTopNodes(maxNodes, visualMode), 0) }
[ "func", "(", "g", "*", "Graph", ")", "SelectTopNodes", "(", "maxNodes", "int", ",", "visualMode", "bool", ")", "NodeSet", "{", "return", "makeNodeSet", "(", "g", ".", "selectTopNodes", "(", "maxNodes", ",", "visualMode", ")", ",", "0", ")", "\n", "}" ]
// SelectTopNodes returns a set of the top maxNodes nodes in a graph.
[ "SelectTopNodes", "returns", "a", "set", "of", "the", "top", "maxNodes", "nodes", "in", "a", "graph", "." ]
8358a9778bd1e48718ffcb96eb11ee061385bf62
https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/internal/graph/graph.go#L814-L816
train
google/pprof
internal/graph/graph.go
selectTopNodes
func (g *Graph) selectTopNodes(maxNodes int, visualMode bool) Nodes { if maxNodes > 0 { if visualMode { var count int // If generating a visual graph, count tags as nodes. Update // maxNodes to account for them. for i, n := range g.Nodes { tags := countTags(n) if tags > maxNodelets { tags = maxNodelets } if count += tags + 1; count >= maxNodes { maxNodes = i + 1 break } } } } if maxNodes > len(g.Nodes) { maxNodes = len(g.Nodes) } return g.Nodes[:maxNodes] }
go
func (g *Graph) selectTopNodes(maxNodes int, visualMode bool) Nodes { if maxNodes > 0 { if visualMode { var count int // If generating a visual graph, count tags as nodes. Update // maxNodes to account for them. for i, n := range g.Nodes { tags := countTags(n) if tags > maxNodelets { tags = maxNodelets } if count += tags + 1; count >= maxNodes { maxNodes = i + 1 break } } } } if maxNodes > len(g.Nodes) { maxNodes = len(g.Nodes) } return g.Nodes[:maxNodes] }
[ "func", "(", "g", "*", "Graph", ")", "selectTopNodes", "(", "maxNodes", "int", ",", "visualMode", "bool", ")", "Nodes", "{", "if", "maxNodes", ">", "0", "{", "if", "visualMode", "{", "var", "count", "int", "\n", "// If generating a visual graph, count tags as nodes. Update", "// maxNodes to account for them.", "for", "i", ",", "n", ":=", "range", "g", ".", "Nodes", "{", "tags", ":=", "countTags", "(", "n", ")", "\n", "if", "tags", ">", "maxNodelets", "{", "tags", "=", "maxNodelets", "\n", "}", "\n", "if", "count", "+=", "tags", "+", "1", ";", "count", ">=", "maxNodes", "{", "maxNodes", "=", "i", "+", "1", "\n", "break", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "if", "maxNodes", ">", "len", "(", "g", ".", "Nodes", ")", "{", "maxNodes", "=", "len", "(", "g", ".", "Nodes", ")", "\n", "}", "\n", "return", "g", ".", "Nodes", "[", ":", "maxNodes", "]", "\n", "}" ]
// selectTopNodes returns a slice of the top maxNodes nodes in a graph.
[ "selectTopNodes", "returns", "a", "slice", "of", "the", "top", "maxNodes", "nodes", "in", "a", "graph", "." ]
8358a9778bd1e48718ffcb96eb11ee061385bf62
https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/internal/graph/graph.go#L819-L841
train
google/pprof
internal/graph/graph.go
countTags
func countTags(n *Node) int { count := 0 for _, e := range n.LabelTags { if e.Flat != 0 { count++ } } for _, t := range n.NumericTags { for _, e := range t { if e.Flat != 0 { count++ } } } return count }
go
func countTags(n *Node) int { count := 0 for _, e := range n.LabelTags { if e.Flat != 0 { count++ } } for _, t := range n.NumericTags { for _, e := range t { if e.Flat != 0 { count++ } } } return count }
[ "func", "countTags", "(", "n", "*", "Node", ")", "int", "{", "count", ":=", "0", "\n", "for", "_", ",", "e", ":=", "range", "n", ".", "LabelTags", "{", "if", "e", ".", "Flat", "!=", "0", "{", "count", "++", "\n", "}", "\n", "}", "\n", "for", "_", ",", "t", ":=", "range", "n", ".", "NumericTags", "{", "for", "_", ",", "e", ":=", "range", "t", "{", "if", "e", ".", "Flat", "!=", "0", "{", "count", "++", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "count", "\n", "}" ]
// countTags counts the tags with flat count. This underestimates the // number of tags being displayed, but in practice is close enough.
[ "countTags", "counts", "the", "tags", "with", "flat", "count", ".", "This", "underestimates", "the", "number", "of", "tags", "being", "displayed", "but", "in", "practice", "is", "close", "enough", "." ]
8358a9778bd1e48718ffcb96eb11ee061385bf62
https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/internal/graph/graph.go#L845-L860
train
google/pprof
internal/graph/graph.go
RemoveRedundantEdges
func (g *Graph) RemoveRedundantEdges() { // Walk the nodes and outgoing edges in reverse order to prefer // removing edges with the lowest weight. for i := len(g.Nodes); i > 0; i-- { n := g.Nodes[i-1] in := n.In.Sort() for j := len(in); j > 0; j-- { e := in[j-1] if !e.Residual { // Do not remove edges heavier than a non-residual edge, to // avoid potential confusion. break } if isRedundantEdge(e) { delete(e.Src.Out, e.Dest) delete(e.Dest.In, e.Src) } } } }
go
func (g *Graph) RemoveRedundantEdges() { // Walk the nodes and outgoing edges in reverse order to prefer // removing edges with the lowest weight. for i := len(g.Nodes); i > 0; i-- { n := g.Nodes[i-1] in := n.In.Sort() for j := len(in); j > 0; j-- { e := in[j-1] if !e.Residual { // Do not remove edges heavier than a non-residual edge, to // avoid potential confusion. break } if isRedundantEdge(e) { delete(e.Src.Out, e.Dest) delete(e.Dest.In, e.Src) } } } }
[ "func", "(", "g", "*", "Graph", ")", "RemoveRedundantEdges", "(", ")", "{", "// Walk the nodes and outgoing edges in reverse order to prefer", "// removing edges with the lowest weight.", "for", "i", ":=", "len", "(", "g", ".", "Nodes", ")", ";", "i", ">", "0", ";", "i", "--", "{", "n", ":=", "g", ".", "Nodes", "[", "i", "-", "1", "]", "\n", "in", ":=", "n", ".", "In", ".", "Sort", "(", ")", "\n", "for", "j", ":=", "len", "(", "in", ")", ";", "j", ">", "0", ";", "j", "--", "{", "e", ":=", "in", "[", "j", "-", "1", "]", "\n", "if", "!", "e", ".", "Residual", "{", "// Do not remove edges heavier than a non-residual edge, to", "// avoid potential confusion.", "break", "\n", "}", "\n", "if", "isRedundantEdge", "(", "e", ")", "{", "delete", "(", "e", ".", "Src", ".", "Out", ",", "e", ".", "Dest", ")", "\n", "delete", "(", "e", ".", "Dest", ".", "In", ",", "e", ".", "Src", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "}" ]
// RemoveRedundantEdges removes residual edges if the destination can // be reached through another path. This is done to simplify the graph // while preserving connectivity.
[ "RemoveRedundantEdges", "removes", "residual", "edges", "if", "the", "destination", "can", "be", "reached", "through", "another", "path", ".", "This", "is", "done", "to", "simplify", "the", "graph", "while", "preserving", "connectivity", "." ]
8358a9778bd1e48718ffcb96eb11ee061385bf62
https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/internal/graph/graph.go#L865-L884
train
google/pprof
internal/graph/graph.go
isRedundantEdge
func isRedundantEdge(e *Edge) bool { src, n := e.Src, e.Dest seen := map[*Node]bool{n: true} queue := Nodes{n} for len(queue) > 0 { n := queue[0] queue = queue[1:] for _, ie := range n.In { if e == ie || seen[ie.Src] { continue } if ie.Src == src { return true } seen[ie.Src] = true queue = append(queue, ie.Src) } } return false }
go
func isRedundantEdge(e *Edge) bool { src, n := e.Src, e.Dest seen := map[*Node]bool{n: true} queue := Nodes{n} for len(queue) > 0 { n := queue[0] queue = queue[1:] for _, ie := range n.In { if e == ie || seen[ie.Src] { continue } if ie.Src == src { return true } seen[ie.Src] = true queue = append(queue, ie.Src) } } return false }
[ "func", "isRedundantEdge", "(", "e", "*", "Edge", ")", "bool", "{", "src", ",", "n", ":=", "e", ".", "Src", ",", "e", ".", "Dest", "\n", "seen", ":=", "map", "[", "*", "Node", "]", "bool", "{", "n", ":", "true", "}", "\n", "queue", ":=", "Nodes", "{", "n", "}", "\n", "for", "len", "(", "queue", ")", ">", "0", "{", "n", ":=", "queue", "[", "0", "]", "\n", "queue", "=", "queue", "[", "1", ":", "]", "\n", "for", "_", ",", "ie", ":=", "range", "n", ".", "In", "{", "if", "e", "==", "ie", "||", "seen", "[", "ie", ".", "Src", "]", "{", "continue", "\n", "}", "\n", "if", "ie", ".", "Src", "==", "src", "{", "return", "true", "\n", "}", "\n", "seen", "[", "ie", ".", "Src", "]", "=", "true", "\n", "queue", "=", "append", "(", "queue", ",", "ie", ".", "Src", ")", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// isRedundantEdge determines if there is a path that allows e.Src // to reach e.Dest after removing e.
[ "isRedundantEdge", "determines", "if", "there", "is", "a", "path", "that", "allows", "e", ".", "Src", "to", "reach", "e", ".", "Dest", "after", "removing", "e", "." ]
8358a9778bd1e48718ffcb96eb11ee061385bf62
https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/internal/graph/graph.go#L888-L907
train
google/pprof
internal/graph/graph.go
compareNodes
func compareNodes(l, r *Node) bool { return fmt.Sprint(l.Info) < fmt.Sprint(r.Info) }
go
func compareNodes(l, r *Node) bool { return fmt.Sprint(l.Info) < fmt.Sprint(r.Info) }
[ "func", "compareNodes", "(", "l", ",", "r", "*", "Node", ")", "bool", "{", "return", "fmt", ".", "Sprint", "(", "l", ".", "Info", ")", "<", "fmt", ".", "Sprint", "(", "r", ".", "Info", ")", "\n", "}" ]
// compareNodes compares two nodes to provide a deterministic ordering // between them. Two nodes cannot have the same Node.Info value.
[ "compareNodes", "compares", "two", "nodes", "to", "provide", "a", "deterministic", "ordering", "between", "them", ".", "Two", "nodes", "cannot", "have", "the", "same", "Node", ".", "Info", "value", "." ]
8358a9778bd1e48718ffcb96eb11ee061385bf62
https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/internal/graph/graph.go#L1027-L1029
train
google/pprof
internal/graph/graph.go
Sum
func (e EdgeMap) Sum() int64 { var ret int64 for _, edge := range e { ret += edge.Weight } return ret }
go
func (e EdgeMap) Sum() int64 { var ret int64 for _, edge := range e { ret += edge.Weight } return ret }
[ "func", "(", "e", "EdgeMap", ")", "Sum", "(", ")", "int64", "{", "var", "ret", "int64", "\n", "for", "_", ",", "edge", ":=", "range", "e", "{", "ret", "+=", "edge", ".", "Weight", "\n", "}", "\n", "return", "ret", "\n", "}" ]
// Sum returns the total weight for a set of nodes.
[ "Sum", "returns", "the", "total", "weight", "for", "a", "set", "of", "nodes", "." ]
8358a9778bd1e48718ffcb96eb11ee061385bf62
https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/internal/graph/graph.go#L1110-L1116
train
google/pprof
internal/elfexec/elfexec.go
parseNotes
func parseNotes(reader io.Reader, alignment int, order binary.ByteOrder) ([]elfNote, error) { r := bufio.NewReader(reader) // padding returns the number of bytes required to pad the given size to an // alignment boundary. padding := func(size int) int { return ((size + (alignment - 1)) &^ (alignment - 1)) - size } var notes []elfNote for { noteHeader := make([]byte, 12) // 3 4-byte words if _, err := io.ReadFull(r, noteHeader); err == io.EOF { break } else if err != nil { return nil, err } namesz := order.Uint32(noteHeader[0:4]) descsz := order.Uint32(noteHeader[4:8]) typ := order.Uint32(noteHeader[8:12]) if uint64(namesz) > uint64(maxNoteSize) { return nil, fmt.Errorf("note name too long (%d bytes)", namesz) } var name string if namesz > 0 { // Documentation differs as to whether namesz is meant to include the // trailing zero, but everyone agrees that name is null-terminated. // So we'll just determine the actual length after the fact. var err error name, err = r.ReadString('\x00') if err == io.EOF { return nil, fmt.Errorf("missing note name (want %d bytes)", namesz) } else if err != nil { return nil, err } namesz = uint32(len(name)) name = name[:len(name)-1] } // Drop padding bytes until the desc field. for n := padding(len(noteHeader) + int(namesz)); n > 0; n-- { if _, err := r.ReadByte(); err == io.EOF { return nil, fmt.Errorf( "missing %d bytes of padding after note name", n) } else if err != nil { return nil, err } } if uint64(descsz) > uint64(maxNoteSize) { return nil, fmt.Errorf("note desc too long (%d bytes)", descsz) } desc := make([]byte, int(descsz)) if _, err := io.ReadFull(r, desc); err == io.EOF { return nil, fmt.Errorf("missing desc (want %d bytes)", len(desc)) } else if err != nil { return nil, err } notes = append(notes, elfNote{Name: name, Desc: desc, Type: typ}) // Drop padding bytes until the next note or the end of the section, // whichever comes first. for n := padding(len(desc)); n > 0; n-- { if _, err := r.ReadByte(); err == io.EOF { // We hit the end of the section before an alignment boundary. // This can happen if this section is at the end of the file or the next // section has a smaller alignment requirement. break } else if err != nil { return nil, err } } } return notes, nil }
go
func parseNotes(reader io.Reader, alignment int, order binary.ByteOrder) ([]elfNote, error) { r := bufio.NewReader(reader) // padding returns the number of bytes required to pad the given size to an // alignment boundary. padding := func(size int) int { return ((size + (alignment - 1)) &^ (alignment - 1)) - size } var notes []elfNote for { noteHeader := make([]byte, 12) // 3 4-byte words if _, err := io.ReadFull(r, noteHeader); err == io.EOF { break } else if err != nil { return nil, err } namesz := order.Uint32(noteHeader[0:4]) descsz := order.Uint32(noteHeader[4:8]) typ := order.Uint32(noteHeader[8:12]) if uint64(namesz) > uint64(maxNoteSize) { return nil, fmt.Errorf("note name too long (%d bytes)", namesz) } var name string if namesz > 0 { // Documentation differs as to whether namesz is meant to include the // trailing zero, but everyone agrees that name is null-terminated. // So we'll just determine the actual length after the fact. var err error name, err = r.ReadString('\x00') if err == io.EOF { return nil, fmt.Errorf("missing note name (want %d bytes)", namesz) } else if err != nil { return nil, err } namesz = uint32(len(name)) name = name[:len(name)-1] } // Drop padding bytes until the desc field. for n := padding(len(noteHeader) + int(namesz)); n > 0; n-- { if _, err := r.ReadByte(); err == io.EOF { return nil, fmt.Errorf( "missing %d bytes of padding after note name", n) } else if err != nil { return nil, err } } if uint64(descsz) > uint64(maxNoteSize) { return nil, fmt.Errorf("note desc too long (%d bytes)", descsz) } desc := make([]byte, int(descsz)) if _, err := io.ReadFull(r, desc); err == io.EOF { return nil, fmt.Errorf("missing desc (want %d bytes)", len(desc)) } else if err != nil { return nil, err } notes = append(notes, elfNote{Name: name, Desc: desc, Type: typ}) // Drop padding bytes until the next note or the end of the section, // whichever comes first. for n := padding(len(desc)); n > 0; n-- { if _, err := r.ReadByte(); err == io.EOF { // We hit the end of the section before an alignment boundary. // This can happen if this section is at the end of the file or the next // section has a smaller alignment requirement. break } else if err != nil { return nil, err } } } return notes, nil }
[ "func", "parseNotes", "(", "reader", "io", ".", "Reader", ",", "alignment", "int", ",", "order", "binary", ".", "ByteOrder", ")", "(", "[", "]", "elfNote", ",", "error", ")", "{", "r", ":=", "bufio", ".", "NewReader", "(", "reader", ")", "\n\n", "// padding returns the number of bytes required to pad the given size to an", "// alignment boundary.", "padding", ":=", "func", "(", "size", "int", ")", "int", "{", "return", "(", "(", "size", "+", "(", "alignment", "-", "1", ")", ")", "&^", "(", "alignment", "-", "1", ")", ")", "-", "size", "\n", "}", "\n\n", "var", "notes", "[", "]", "elfNote", "\n", "for", "{", "noteHeader", ":=", "make", "(", "[", "]", "byte", ",", "12", ")", "// 3 4-byte words", "\n", "if", "_", ",", "err", ":=", "io", ".", "ReadFull", "(", "r", ",", "noteHeader", ")", ";", "err", "==", "io", ".", "EOF", "{", "break", "\n", "}", "else", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "namesz", ":=", "order", ".", "Uint32", "(", "noteHeader", "[", "0", ":", "4", "]", ")", "\n", "descsz", ":=", "order", ".", "Uint32", "(", "noteHeader", "[", "4", ":", "8", "]", ")", "\n", "typ", ":=", "order", ".", "Uint32", "(", "noteHeader", "[", "8", ":", "12", "]", ")", "\n\n", "if", "uint64", "(", "namesz", ")", ">", "uint64", "(", "maxNoteSize", ")", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "namesz", ")", "\n", "}", "\n", "var", "name", "string", "\n", "if", "namesz", ">", "0", "{", "// Documentation differs as to whether namesz is meant to include the", "// trailing zero, but everyone agrees that name is null-terminated.", "// So we'll just determine the actual length after the fact.", "var", "err", "error", "\n", "name", ",", "err", "=", "r", ".", "ReadString", "(", "'\\x00'", ")", "\n", "if", "err", "==", "io", ".", "EOF", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "namesz", ")", "\n", "}", "else", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "namesz", "=", "uint32", "(", "len", "(", "name", ")", ")", "\n", "name", "=", "name", "[", ":", "len", "(", "name", ")", "-", "1", "]", "\n", "}", "\n\n", "// Drop padding bytes until the desc field.", "for", "n", ":=", "padding", "(", "len", "(", "noteHeader", ")", "+", "int", "(", "namesz", ")", ")", ";", "n", ">", "0", ";", "n", "--", "{", "if", "_", ",", "err", ":=", "r", ".", "ReadByte", "(", ")", ";", "err", "==", "io", ".", "EOF", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "n", ")", "\n", "}", "else", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n\n", "if", "uint64", "(", "descsz", ")", ">", "uint64", "(", "maxNoteSize", ")", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "descsz", ")", "\n", "}", "\n", "desc", ":=", "make", "(", "[", "]", "byte", ",", "int", "(", "descsz", ")", ")", "\n", "if", "_", ",", "err", ":=", "io", ".", "ReadFull", "(", "r", ",", "desc", ")", ";", "err", "==", "io", ".", "EOF", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "len", "(", "desc", ")", ")", "\n", "}", "else", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "notes", "=", "append", "(", "notes", ",", "elfNote", "{", "Name", ":", "name", ",", "Desc", ":", "desc", ",", "Type", ":", "typ", "}", ")", "\n\n", "// Drop padding bytes until the next note or the end of the section,", "// whichever comes first.", "for", "n", ":=", "padding", "(", "len", "(", "desc", ")", ")", ";", "n", ">", "0", ";", "n", "--", "{", "if", "_", ",", "err", ":=", "r", ".", "ReadByte", "(", ")", ";", "err", "==", "io", ".", "EOF", "{", "// We hit the end of the section before an alignment boundary.", "// This can happen if this section is at the end of the file or the next", "// section has a smaller alignment requirement.", "break", "\n", "}", "else", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "notes", ",", "nil", "\n", "}" ]
// parseNotes returns the notes from a SHT_NOTE section or PT_NOTE segment.
[ "parseNotes", "returns", "the", "notes", "from", "a", "SHT_NOTE", "section", "or", "PT_NOTE", "segment", "." ]
8358a9778bd1e48718ffcb96eb11ee061385bf62
https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/internal/elfexec/elfexec.go#L39-L115
train
google/pprof
internal/elfexec/elfexec.go
GetBase
func GetBase(fh *elf.FileHeader, loadSegment *elf.ProgHeader, stextOffset *uint64, start, limit, offset uint64) (uint64, error) { const ( pageSize = 4096 // PAGE_OFFSET for PowerPC64, see arch/powerpc/Kconfig in the kernel sources. pageOffsetPpc64 = 0xc000000000000000 ) if start == 0 && offset == 0 && (limit == ^uint64(0) || limit == 0) { // Some tools may introduce a fake mapping that spans the entire // address space. Assume that the address has already been // adjusted, so no additional base adjustment is necessary. return 0, nil } switch fh.Type { case elf.ET_EXEC: if loadSegment == nil { // Assume fixed-address executable and so no adjustment. return 0, nil } if stextOffset == nil && start > 0 && start < 0x8000000000000000 { // A regular user-mode executable. Compute the base offset using same // arithmetics as in ET_DYN case below, see the explanation there. // Ideally, the condition would just be "stextOffset == nil" as that // represents the address of _stext symbol in the vmlinux image. Alas, // the caller may skip reading it from the binary (it's expensive to scan // all the symbols) and so it may be nil even for the kernel executable. // So additionally check that the start is within the user-mode half of // the 64-bit address space. return start - offset + loadSegment.Off - loadSegment.Vaddr, nil } // Various kernel heuristics and cases follow. if loadSegment.Vaddr == start-offset { return offset, nil } if start == 0 && limit != 0 { // ChromeOS remaps its kernel to 0. Nothing else should come // down this path. Empirical values: // VADDR=0xffffffff80200000 // stextOffset=0xffffffff80200198 if stextOffset != nil { return -*stextOffset, nil } return -loadSegment.Vaddr, nil } if start >= loadSegment.Vaddr && limit > start && (offset == 0 || offset == pageOffsetPpc64 || offset == start) { // Some kernels look like: // VADDR=0xffffffff80200000 // stextOffset=0xffffffff80200198 // Start=0xffffffff83200000 // Limit=0xffffffff84200000 // Offset=0 (0xc000000000000000 for PowerPC64) (== Start for ASLR kernel) // So the base should be: if stextOffset != nil && (start%pageSize) == (*stextOffset%pageSize) { // perf uses the address of _stext as start. Some tools may // adjust for this before calling GetBase, in which case the page // alignment should be different from that of stextOffset. return start - *stextOffset, nil } return start - loadSegment.Vaddr, nil } else if start%pageSize != 0 && stextOffset != nil && *stextOffset%pageSize == start%pageSize { // ChromeOS remaps its kernel to 0 + start%pageSize. Nothing // else should come down this path. Empirical values: // start=0x198 limit=0x2f9fffff offset=0 // VADDR=0xffffffff81000000 // stextOffset=0xffffffff81000198 return start - *stextOffset, nil } return 0, fmt.Errorf("don't know how to handle EXEC segment: %v start=0x%x limit=0x%x offset=0x%x", *loadSegment, start, limit, offset) case elf.ET_REL: if offset != 0 { return 0, fmt.Errorf("don't know how to handle mapping.Offset") } return start, nil case elf.ET_DYN: // The process mapping information, start = start of virtual address range, // and offset = offset in the executable file of the start address, tells us // that a runtime virtual address x maps to a file offset // fx = x - start + offset. if loadSegment == nil { return start - offset, nil } // The program header, if not nil, indicates the offset in the file where // the executable segment is located (loadSegment.Off), and the base virtual // address where the first byte of the segment is loaded // (loadSegment.Vaddr). A file offset fx maps to a virtual (symbol) address // sx = fx - loadSegment.Off + loadSegment.Vaddr. // // Thus, a runtime virtual address x maps to a symbol address // sx = x - start + offset - loadSegment.Off + loadSegment.Vaddr. return start - offset + loadSegment.Off - loadSegment.Vaddr, nil } return 0, fmt.Errorf("don't know how to handle FileHeader.Type %v", fh.Type) }
go
func GetBase(fh *elf.FileHeader, loadSegment *elf.ProgHeader, stextOffset *uint64, start, limit, offset uint64) (uint64, error) { const ( pageSize = 4096 // PAGE_OFFSET for PowerPC64, see arch/powerpc/Kconfig in the kernel sources. pageOffsetPpc64 = 0xc000000000000000 ) if start == 0 && offset == 0 && (limit == ^uint64(0) || limit == 0) { // Some tools may introduce a fake mapping that spans the entire // address space. Assume that the address has already been // adjusted, so no additional base adjustment is necessary. return 0, nil } switch fh.Type { case elf.ET_EXEC: if loadSegment == nil { // Assume fixed-address executable and so no adjustment. return 0, nil } if stextOffset == nil && start > 0 && start < 0x8000000000000000 { // A regular user-mode executable. Compute the base offset using same // arithmetics as in ET_DYN case below, see the explanation there. // Ideally, the condition would just be "stextOffset == nil" as that // represents the address of _stext symbol in the vmlinux image. Alas, // the caller may skip reading it from the binary (it's expensive to scan // all the symbols) and so it may be nil even for the kernel executable. // So additionally check that the start is within the user-mode half of // the 64-bit address space. return start - offset + loadSegment.Off - loadSegment.Vaddr, nil } // Various kernel heuristics and cases follow. if loadSegment.Vaddr == start-offset { return offset, nil } if start == 0 && limit != 0 { // ChromeOS remaps its kernel to 0. Nothing else should come // down this path. Empirical values: // VADDR=0xffffffff80200000 // stextOffset=0xffffffff80200198 if stextOffset != nil { return -*stextOffset, nil } return -loadSegment.Vaddr, nil } if start >= loadSegment.Vaddr && limit > start && (offset == 0 || offset == pageOffsetPpc64 || offset == start) { // Some kernels look like: // VADDR=0xffffffff80200000 // stextOffset=0xffffffff80200198 // Start=0xffffffff83200000 // Limit=0xffffffff84200000 // Offset=0 (0xc000000000000000 for PowerPC64) (== Start for ASLR kernel) // So the base should be: if stextOffset != nil && (start%pageSize) == (*stextOffset%pageSize) { // perf uses the address of _stext as start. Some tools may // adjust for this before calling GetBase, in which case the page // alignment should be different from that of stextOffset. return start - *stextOffset, nil } return start - loadSegment.Vaddr, nil } else if start%pageSize != 0 && stextOffset != nil && *stextOffset%pageSize == start%pageSize { // ChromeOS remaps its kernel to 0 + start%pageSize. Nothing // else should come down this path. Empirical values: // start=0x198 limit=0x2f9fffff offset=0 // VADDR=0xffffffff81000000 // stextOffset=0xffffffff81000198 return start - *stextOffset, nil } return 0, fmt.Errorf("don't know how to handle EXEC segment: %v start=0x%x limit=0x%x offset=0x%x", *loadSegment, start, limit, offset) case elf.ET_REL: if offset != 0 { return 0, fmt.Errorf("don't know how to handle mapping.Offset") } return start, nil case elf.ET_DYN: // The process mapping information, start = start of virtual address range, // and offset = offset in the executable file of the start address, tells us // that a runtime virtual address x maps to a file offset // fx = x - start + offset. if loadSegment == nil { return start - offset, nil } // The program header, if not nil, indicates the offset in the file where // the executable segment is located (loadSegment.Off), and the base virtual // address where the first byte of the segment is loaded // (loadSegment.Vaddr). A file offset fx maps to a virtual (symbol) address // sx = fx - loadSegment.Off + loadSegment.Vaddr. // // Thus, a runtime virtual address x maps to a symbol address // sx = x - start + offset - loadSegment.Off + loadSegment.Vaddr. return start - offset + loadSegment.Off - loadSegment.Vaddr, nil } return 0, fmt.Errorf("don't know how to handle FileHeader.Type %v", fh.Type) }
[ "func", "GetBase", "(", "fh", "*", "elf", ".", "FileHeader", ",", "loadSegment", "*", "elf", ".", "ProgHeader", ",", "stextOffset", "*", "uint64", ",", "start", ",", "limit", ",", "offset", "uint64", ")", "(", "uint64", ",", "error", ")", "{", "const", "(", "pageSize", "=", "4096", "\n", "// PAGE_OFFSET for PowerPC64, see arch/powerpc/Kconfig in the kernel sources.", "pageOffsetPpc64", "=", "0xc000000000000000", "\n", ")", "\n\n", "if", "start", "==", "0", "&&", "offset", "==", "0", "&&", "(", "limit", "==", "^", "uint64", "(", "0", ")", "||", "limit", "==", "0", ")", "{", "// Some tools may introduce a fake mapping that spans the entire", "// address space. Assume that the address has already been", "// adjusted, so no additional base adjustment is necessary.", "return", "0", ",", "nil", "\n", "}", "\n\n", "switch", "fh", ".", "Type", "{", "case", "elf", ".", "ET_EXEC", ":", "if", "loadSegment", "==", "nil", "{", "// Assume fixed-address executable and so no adjustment.", "return", "0", ",", "nil", "\n", "}", "\n", "if", "stextOffset", "==", "nil", "&&", "start", ">", "0", "&&", "start", "<", "0x8000000000000000", "{", "// A regular user-mode executable. Compute the base offset using same", "// arithmetics as in ET_DYN case below, see the explanation there.", "// Ideally, the condition would just be \"stextOffset == nil\" as that", "// represents the address of _stext symbol in the vmlinux image. Alas,", "// the caller may skip reading it from the binary (it's expensive to scan", "// all the symbols) and so it may be nil even for the kernel executable.", "// So additionally check that the start is within the user-mode half of", "// the 64-bit address space.", "return", "start", "-", "offset", "+", "loadSegment", ".", "Off", "-", "loadSegment", ".", "Vaddr", ",", "nil", "\n", "}", "\n", "// Various kernel heuristics and cases follow.", "if", "loadSegment", ".", "Vaddr", "==", "start", "-", "offset", "{", "return", "offset", ",", "nil", "\n", "}", "\n", "if", "start", "==", "0", "&&", "limit", "!=", "0", "{", "// ChromeOS remaps its kernel to 0. Nothing else should come", "// down this path. Empirical values:", "// VADDR=0xffffffff80200000", "// stextOffset=0xffffffff80200198", "if", "stextOffset", "!=", "nil", "{", "return", "-", "*", "stextOffset", ",", "nil", "\n", "}", "\n", "return", "-", "loadSegment", ".", "Vaddr", ",", "nil", "\n", "}", "\n", "if", "start", ">=", "loadSegment", ".", "Vaddr", "&&", "limit", ">", "start", "&&", "(", "offset", "==", "0", "||", "offset", "==", "pageOffsetPpc64", "||", "offset", "==", "start", ")", "{", "// Some kernels look like:", "// VADDR=0xffffffff80200000", "// stextOffset=0xffffffff80200198", "// Start=0xffffffff83200000", "// Limit=0xffffffff84200000", "// Offset=0 (0xc000000000000000 for PowerPC64) (== Start for ASLR kernel)", "// So the base should be:", "if", "stextOffset", "!=", "nil", "&&", "(", "start", "%", "pageSize", ")", "==", "(", "*", "stextOffset", "%", "pageSize", ")", "{", "// perf uses the address of _stext as start. Some tools may", "// adjust for this before calling GetBase, in which case the page", "// alignment should be different from that of stextOffset.", "return", "start", "-", "*", "stextOffset", ",", "nil", "\n", "}", "\n\n", "return", "start", "-", "loadSegment", ".", "Vaddr", ",", "nil", "\n", "}", "else", "if", "start", "%", "pageSize", "!=", "0", "&&", "stextOffset", "!=", "nil", "&&", "*", "stextOffset", "%", "pageSize", "==", "start", "%", "pageSize", "{", "// ChromeOS remaps its kernel to 0 + start%pageSize. Nothing", "// else should come down this path. Empirical values:", "// start=0x198 limit=0x2f9fffff offset=0", "// VADDR=0xffffffff81000000", "// stextOffset=0xffffffff81000198", "return", "start", "-", "*", "stextOffset", ",", "nil", "\n", "}", "\n\n", "return", "0", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "*", "loadSegment", ",", "start", ",", "limit", ",", "offset", ")", "\n", "case", "elf", ".", "ET_REL", ":", "if", "offset", "!=", "0", "{", "return", "0", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "start", ",", "nil", "\n", "case", "elf", ".", "ET_DYN", ":", "// The process mapping information, start = start of virtual address range,", "// and offset = offset in the executable file of the start address, tells us", "// that a runtime virtual address x maps to a file offset", "// fx = x - start + offset.", "if", "loadSegment", "==", "nil", "{", "return", "start", "-", "offset", ",", "nil", "\n", "}", "\n", "// The program header, if not nil, indicates the offset in the file where", "// the executable segment is located (loadSegment.Off), and the base virtual", "// address where the first byte of the segment is loaded", "// (loadSegment.Vaddr). A file offset fx maps to a virtual (symbol) address", "// sx = fx - loadSegment.Off + loadSegment.Vaddr.", "//", "// Thus, a runtime virtual address x maps to a symbol address", "// sx = x - start + offset - loadSegment.Off + loadSegment.Vaddr.", "return", "start", "-", "offset", "+", "loadSegment", ".", "Off", "-", "loadSegment", ".", "Vaddr", ",", "nil", "\n", "}", "\n", "return", "0", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "fh", ".", "Type", ")", "\n", "}" ]
// GetBase determines the base address to subtract from virtual // address to get symbol table address. For an executable, the base // is 0. Otherwise, it's a shared library, and the base is the // address where the mapping starts. The kernel is special, and may // use the address of the _stext symbol as the mmap start. _stext // offset can be obtained with `nm vmlinux | grep _stext`
[ "GetBase", "determines", "the", "base", "address", "to", "subtract", "from", "virtual", "address", "to", "get", "symbol", "table", "address", ".", "For", "an", "executable", "the", "base", "is", "0", ".", "Otherwise", "it", "s", "a", "shared", "library", "and", "the", "base", "is", "the", "address", "where", "the", "mapping", "starts", ".", "The", "kernel", "is", "special", "and", "may", "use", "the", "address", "of", "the", "_stext", "symbol", "as", "the", "mmap", "start", ".", "_stext", "offset", "can", "be", "obtained", "with", "nm", "vmlinux", "|", "grep", "_stext" ]
8358a9778bd1e48718ffcb96eb11ee061385bf62
https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/internal/elfexec/elfexec.go#L174-L269
train
google/pprof
internal/elfexec/elfexec.go
FindTextProgHeader
func FindTextProgHeader(f *elf.File) *elf.ProgHeader { for _, s := range f.Sections { if s.Name == ".text" { // Find the LOAD segment containing the .text section. for _, p := range f.Progs { if p.Type == elf.PT_LOAD && p.Flags&elf.PF_X != 0 && s.Addr >= p.Vaddr && s.Addr < p.Vaddr+p.Memsz { return &p.ProgHeader } } } } return nil }
go
func FindTextProgHeader(f *elf.File) *elf.ProgHeader { for _, s := range f.Sections { if s.Name == ".text" { // Find the LOAD segment containing the .text section. for _, p := range f.Progs { if p.Type == elf.PT_LOAD && p.Flags&elf.PF_X != 0 && s.Addr >= p.Vaddr && s.Addr < p.Vaddr+p.Memsz { return &p.ProgHeader } } } } return nil }
[ "func", "FindTextProgHeader", "(", "f", "*", "elf", ".", "File", ")", "*", "elf", ".", "ProgHeader", "{", "for", "_", ",", "s", ":=", "range", "f", ".", "Sections", "{", "if", "s", ".", "Name", "==", "\"", "\"", "{", "// Find the LOAD segment containing the .text section.", "for", "_", ",", "p", ":=", "range", "f", ".", "Progs", "{", "if", "p", ".", "Type", "==", "elf", ".", "PT_LOAD", "&&", "p", ".", "Flags", "&", "elf", ".", "PF_X", "!=", "0", "&&", "s", ".", "Addr", ">=", "p", ".", "Vaddr", "&&", "s", ".", "Addr", "<", "p", ".", "Vaddr", "+", "p", ".", "Memsz", "{", "return", "&", "p", ".", "ProgHeader", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// FindTextProgHeader finds the program segment header containing the .text // section or nil if the segment cannot be found.
[ "FindTextProgHeader", "finds", "the", "program", "segment", "header", "containing", "the", ".", "text", "section", "or", "nil", "if", "the", "segment", "cannot", "be", "found", "." ]
8358a9778bd1e48718ffcb96eb11ee061385bf62
https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/internal/elfexec/elfexec.go#L273-L285
train