id int32 0 167k | 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 list | docstring stringlengths 6 2.61k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 85 252 |
|---|---|---|---|---|---|---|---|---|---|---|---|
164,900 | 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",
":=",
"&"... | // 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 |
164,901 | 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",
")... | // 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 |
164,902 | 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 |
164,903 | 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",
... | // 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 |
164,904 | 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",
"(... | // 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",
... | 7087cb70de9f7a8bc0a10c375cb0d2280a8edf9c | https://github.com/hashicorp/golang-lru/blob/7087cb70de9f7a8bc0a10c375cb0d2280a8edf9c/lru.go#L77-L86 |
164,905 | 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",
"(",
... | // 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 |
164,906 | 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",
",",
... | // 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 |
164,907 | 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",
")",
"{",
"fil... | // 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 |
164,908 | 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",
"... | // 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 |
164,909 | 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",
"(",
")",
... | // 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 |
164,910 | 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",
"(",
")",
... | // 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 |
164,911 | 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",
"... | // 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 |
164,912 | 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",
"\""... | // 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 |
164,913 | 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",
"... | // 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 |
164,914 | 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",... | // 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 |
164,915 | 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 ... | // 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 |
164,916 | 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",
".",
... | // 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 |
164,917 | 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"... | // 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 |
164,918 | 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",
"at... | // 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 |
164,919 | 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",
"[",
"]",
"*",
"Ta... | // 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 |
164,920 | 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",... | // 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 |
164,921 | 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",
"(... | // 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 |
164,922 | 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 i... | // 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 |
164,923 | 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",
... | // 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 |
164,924 | 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",
"... | // 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",
"no... | 8358a9778bd1e48718ffcb96eb11ee061385bf62 | https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/internal/report/report.go#L347-L363 |
164,925 | 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... | // 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 |
164,926 | 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 |
164,927 | 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",
",",
... | // 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 |
164,928 | 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",
".",
"selectOutputUni... | // 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 |
164,929 | 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",
"p... | // 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 |
164,930 | 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",
"r... | // 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 |
164,931 | 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",
".",
... | // 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 |
164,932 | 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",
".",
"optio... | // 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 |
164,933 | 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",
".",
"Titl... | // 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 |
164,934 | 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... | // 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",
... | 8358a9778bd1e48718ffcb96eb11ee061385bf62 | https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/internal/report/report.go#L1228-L1254 |
164,935 | 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",
"!=",
"\"",
"... | // 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 |
164,936 | 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 f... | // 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 |
164,937 | 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",
"r... | 8358a9778bd1e48718ffcb96eb11ee061385bf62 | https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/profile/merge.go#L27-L30 |
164,938 | 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",
... | // 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",
"unus... | 8358a9778bd1e48718ffcb96eb11ee061385bf62 | https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/profile/merge.go#L39-L86 |
164,939 | 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... | // 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",... | 8358a9778bd1e48718ffcb96eb11ee061385bf62 | https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/profile/merge.go#L91-L121 |
164,940 | 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"... | // 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 |
164,941 | 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",
"{... | // 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 |
164,942 | 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",
... | // 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 |
164,943 | 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 |
164,944 | 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"... | // 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 |
164,945 | 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 |
164,946 | 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 |
164,947 | 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 |
164,948 | 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 |
164,949 | 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 |
164,950 | 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 |
164,951 | 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 |
164,952 | 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 |
164,953 | 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 |
164,954 | 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",
... | // 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 |
164,955 | 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"... | // 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 |
164,956 | 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",
"... | // 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 |
164,957 | 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",
"{",... | // 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 |
164,958 | 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",... | // 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 |
164,959 | 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",
... | // 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 |
164,960 | 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 fi... | // 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 |
164,961 | 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",
":=",
"&",
... | // 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... | 8358a9778bd1e48718ffcb96eb11ee061385bf62 | https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/internal/binutils/addr2liner_llvm.go#L67-L98 |
164,962 | 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",
".",
... | // 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 |
164,963 | 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",
")",
... | // 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 |
164,964 | 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",
"(",
... | // 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 |
164,965 | 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",
"... | // 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 |
164,966 | 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",
".",... | // 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 |
164,967 | 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 |
164,968 | 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 |
164,969 | 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 |
164,970 | 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",
"]",
"{",
"p... | // 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 |
164,971 | 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",
"(",
... | // 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 |
164,972 | 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",
"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",
"k... | 8358a9778bd1e48718ffcb96eb11ee061385bf62 | https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/internal/graph/graph.go#L202-L232 |
164,973 | 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 |
164,974 | 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 |
164,975 | 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 |
164,976 | 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 |
164,977 | 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",
"(... | // 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 |
164,978 | 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"... | // 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 |
164,979 | 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",
".",
"Fi... | // 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 |
164,980 | 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",
")",
"... | // 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 |
164,981 | 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",
... | // 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 |
164,982 | 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",
"ret... | // 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 |
164,983 | 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",
... | // 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 |
164,984 | 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 |
164,985 | 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",
... | // 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 |
164,986 | 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",
"{",
... | // 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 |
164,987 | 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",
"(... | // 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 |
164,988 | 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",
... | // 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 |
164,989 | 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",
".",
... | // 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 |
164,990 | 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 |
164,991 | 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 ... | // 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 |
164,992 | 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",
... | // 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 |
164,993 | 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",
";",... | // 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 |
164,994 | 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",
":=",
"Nod... | // 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 |
164,995 | 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 |
164,996 | 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 |
164,997 | 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",
"// ... | // 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 |
164,998 | 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",... | // 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",
"... | 8358a9778bd1e48718ffcb96eb11ee061385bf62 | https://github.com/google/pprof/blob/8358a9778bd1e48718ffcb96eb11ee061385bf62/internal/elfexec/elfexec.go#L174-L269 |
164,999 | 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 containin... | // 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.