本文整理汇总了Golang中runtime.FuncForPC函数的典型用法代码示例。如果您正苦于以下问题:Golang FuncForPC函数的具体用法?Golang FuncForPC怎么用?Golang FuncForPC使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了FuncForPC函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: Break
// break
func Break(format bool, v ...interface{}) {
fmt.Println("Variables:")
Fdump(os.Stdout, format, v...)
var pc, file, line, ok = runtime.Caller(1)
if ok {
fmt.Printf("\n\n[Debug] %s() [%s:%d]\n[Stack]\n", runtime.FuncForPC(pc).Name(), file, line)
}
for i := 2; ; i++ {
pc, file, line, ok := runtime.Caller(i)
if !ok {
break
}
fn := runtime.FuncForPC(pc).Name()
if 0 != len(file) {
// /usr/local/go/src/pkg/runtime/proc.c:1223 (0x173d0)
fmt.Printf("%s(...)\n%s:%d (0x%x)\n", fn, file, line, pc)
} else {
// runtime.goexit(...)
// L1223: runtime.goexit(...) (0x173d0)
fmt.Printf("L%d: %s(...) (0x%x)\n", line, fn, pc)
}
}
fmt.Println("\nPress Enter to Continue")
fmt.Scanln()
fmt.Println("Break End...")
}
示例2: logCaller
func (c *C) logCaller(skip int) {
// This is a bit heavier than it ought to be.
skip += 1 // Our own frame.
pc, callerFile, callerLine, ok := runtime.Caller(skip)
if !ok {
return
}
var testFile string
var testLine int
testFunc := runtime.FuncForPC(c.method.PC())
if runtime.FuncForPC(pc) != testFunc {
for {
skip += 1
if pc, file, line, ok := runtime.Caller(skip); ok {
// Note that the test line may be different on
// distinct calls for the same test. Showing
// the "internal" line is helpful when debugging.
if runtime.FuncForPC(pc) == testFunc {
testFile, testLine = file, line
break
}
} else {
break
}
}
}
if testFile != "" && (testFile != callerFile || testLine != callerLine) {
c.logCode(testFile, testLine)
}
c.logCode(callerFile, callerLine)
}
示例3: findDepth
func (self *Tester) findDepth() int {
height := 1 // Skip us
for {
pc, _, _, ok := runtime.Caller(height)
function := runtime.FuncForPC(pc)
if !ok {
// Got too close to the sun
if false {
for ; height > 0; height-- {
pc, _, _, ok := runtime.Caller(height)
fmt.Printf("[%d %v %v]", height, pc, ok)
if ok {
function := runtime.FuncForPC(pc)
fmt.Printf(" => [%s]", function.Name())
}
fmt.Printf("\n")
}
}
return 1
}
functionEntry := function.Entry()
if functionEntry == self.focusEntry || functionEntry == self.testEntry {
return height - 1 // Not the surrounding test function, but within it
}
height += 1
}
return 1
}
示例4: getActualCaller
func getActualCaller() (file string, line int, ok bool) {
cpc, _, _, ok := runtime.Caller(2)
if !ok {
return
}
callerFunPtr := runtime.FuncForPC(cpc)
if callerFunPtr == nil {
ok = false
return
}
var pc uintptr
for callLevel := 3; callLevel < 5; callLevel++ {
pc, file, line, ok = runtime.Caller(callLevel)
if !ok {
return
}
funcPtr := runtime.FuncForPC(pc)
if funcPtr == nil {
ok = false
return
}
if getFuncNameWithoutPackage(funcPtr.Name()) !=
getFuncNameWithoutPackage(callerFunPtr.Name()) {
return
}
}
ok = false
return
}
示例5: test2
func test2() {
pc, file, line, ok := runtime.Caller(2)
log.Println(pc)
log.Println(file)
log.Println(line)
log.Println(ok)
f := runtime.FuncForPC(pc)
log.Println(f.Name())
pc, file, line, ok = runtime.Caller(0)
log.Println(pc)
log.Println(file)
log.Println(line)
log.Println(ok)
f = runtime.FuncForPC(pc)
log.Println(f.Name())
pc, file, line, ok = runtime.Caller(1)
log.Println(pc)
log.Println(file)
log.Println(line)
log.Println(ok)
f = runtime.FuncForPC(pc)
log.Println(f.Name())
}
示例6: getCallerInfo
func getCallerInfo() string {
pc := make([]uintptr, 10)
// Note: the default value 4 will ensure stat name exclude the path
// "/perfstat.UpdateTimeStat -> /perfstat.updateStat -> /perfstat.getCallerInfo"
// "/perfstat.UpdateDataStat -> /perfstat.updateStat -> /perfstat.getCallerInfo"
runtime.Callers(4, pc)
var path bytes.Buffer
j := 0
for i := range pc {
f := runtime.FuncForPC(pc[i])
funcName := f.Name()
if strings.HasPrefix(funcName, commonPrefix) {
j = i
} else {
break
}
}
for i := j; i >= 0; i-- {
f := runtime.FuncForPC(pc[i])
funcName := f.Name()
funcNameShort := funcName[commonPrefixLen:]
path.WriteString(funcNameShort)
if i > 0 {
path.WriteString(" -> ")
}
}
return path.String()
}
示例7: Format
// Format formats the frame according to the fmt.Formatter interface.
//
// %s source file
// %d source line
// %n function name
// %v equivalent to %s:%d
//
// Format accepts flags that alter the printing of some verbs, as follows:
//
// %+s path of source file relative to the compile time GOPATH
// %+v equivalent to %+s:%d
func (f Frame) Format(s fmt.State, verb rune) {
switch verb {
case 's':
switch {
case s.Flag('+'):
pc := f.pc()
fn := runtime.FuncForPC(pc)
if fn == nil {
io.WriteString(s, "unknown")
} else {
file, _ := fn.FileLine(pc)
fmt.Fprintf(s, "%s\n\t%s", fn.Name(), file)
}
default:
io.WriteString(s, path.Base(f.file()))
}
case 'd':
fmt.Fprintf(s, "%d", f.line())
case 'n':
name := runtime.FuncForPC(f.pc()).Name()
io.WriteString(s, funcname(name))
case 'v':
f.Format(s, 's')
io.WriteString(s, ":")
f.Format(s, 'd')
}
}
示例8: logCaller
func (c *C) logCaller(skip int, issue string) {
// This is a bit heavier than it ought to be.
skip += 1 // Our own frame.
if pc, callerFile, callerLine, ok := runtime.Caller(skip); ok {
var testFile string
var testLine int
testFunc := runtime.FuncForPC(c.method.Get())
if runtime.FuncForPC(pc) != testFunc {
for {
skip += 1
if pc, file, line, ok := runtime.Caller(skip); ok {
// Note that the test line may be different on
// distinct calls for the same test. Showing
// the "internal" line is helpful when debugging.
if runtime.FuncForPC(pc) == testFunc {
testFile, testLine = file, line
break
}
} else {
break
}
}
}
if testFile != "" && (testFile != callerFile ||
testLine != callerLine) {
c.logf("%s:%d > %s:%d:\n... %s", nicePath(testFile), testLine,
nicePath(callerFile), callerLine, issue)
} else {
c.logf("%s:%d:\n... %s", nicePath(callerFile), callerLine, issue)
}
}
}
示例9: TrackRaftProtos
// TrackRaftProtos instruments proto marshalling to track protos which are
// marshalled downstream of raft. It returns a function that removes the
// instrumentation and returns the list of downstream-of-raft protos.
func TrackRaftProtos() func() []reflect.Type {
// Grab the name of the function that roots all raft operations.
applyRaftFunc := runtime.FuncForPC(reflect.ValueOf((*Replica).executeBatch).Pointer()).Name()
// Some raft operations trigger gossip, but we don't care about proto
// serialization in gossip, so we're going to ignore it.
addInfoFunc := runtime.FuncForPC(reflect.ValueOf((*gossip.Gossip).AddInfoProto).Pointer()).Name()
belowRaftProtos := struct {
sync.Mutex
inner map[reflect.Type]struct{}
}{
inner: make(map[reflect.Type]struct{}),
}
protoutil.Interceptor = func(pb proto.Message) {
t := reflect.TypeOf(pb)
belowRaftProtos.Lock()
_, ok := belowRaftProtos.inner[t]
belowRaftProtos.Unlock()
if ok {
return
}
pcs := make([]uintptr, 100)
numCallers := runtime.Callers(0, pcs)
if numCallers == len(pcs) {
panic(fmt.Sprintf("number of callers %d might have exceeded slice size %d", numCallers, len(pcs)))
}
for _, pc := range pcs[:numCallers] {
funcName := runtime.FuncForPC(pc).Name()
if strings.Contains(funcName, addInfoFunc) {
break
}
if strings.Contains(funcName, applyRaftFunc) {
belowRaftProtos.Lock()
belowRaftProtos.inner[t] = struct{}{}
belowRaftProtos.Unlock()
break
}
}
}
return func() []reflect.Type {
protoutil.Interceptor = func(_ proto.Message) {}
belowRaftProtos.Lock()
types := make([]reflect.Type, 0, len(belowRaftProtos.inner))
for t := range belowRaftProtos.inner {
types = append(types, t)
}
belowRaftProtos.Unlock()
return types
}
}
示例10: getCallerName
// getCallerName returns the test name that called this function.
// It traverses the stack to find the function name directly after a testing.* call.
func getCallerName() string {
pc := make([]uintptr, 10)
n := runtime.Callers(2, pc)
for i := n; i > 0; i-- {
fname := runtime.FuncForPC(pc[i-1]).Name()
if strings.HasPrefix(fname, "testing.") {
return runtime.FuncForPC(pc[i-2]).Name()
}
}
return "unknown"
}
示例11: DefaultErrorHandler
func DefaultErrorHandler(err error, typeid, funcid int32, call int) {
pc1, _, _, ok1 := runtime.Caller(call)
fn1 := runtime.FuncForPC(pc1)
pc2, file, line, ok2 := runtime.Caller(call + 1)
fn2 := runtime.FuncForPC(pc2)
if ok1 && ok2 {
log.Printf("err:%s, type:%d, func:%d; %s, %s , %s, %d \n", err, typeid, funcid, fn1.Name(), fn2.Name(), file, line)
} else {
log.Printf("err:%s, type:%d, func:%d\n", err, typeid, funcid)
}
}
示例12: handlePrivmsg
func handlePrivmsg(conn *irc.Conn, line *irc.Line) {
nick := conn.GetNick(line.Nick)
if nick == nil {
return
}
nick.Host = line.Host
if ignores[conn.Network][nick.Host] {
return
}
defer func() {
if r := recover(); r != nil {
fmt.Println("Recovered from", r)
callers := make([]uintptr, 10)
runtime.Callers(4, callers)
cutoff := runtime.FuncForPC(reflect.ValueOf(handlePrivmsg).Pointer()).Entry()
for _, pc := range callers {
function := runtime.FuncForPC(pc - 1)
if function.Entry() == cutoff {
break
}
file, line := function.FileLine(pc - 1)
fmt.Printf("%s:%d\n\t%s\n", file, line, function.Name())
}
}
}()
target := line.Args[0]
if isChannel(target) {
// message to a channel
if !command(conn, nick, line.Args[1], target) {
var video string
if start := strings.Index(line.Args[1], "youtube.com/watch?"); start > -1 {
start = strings.Index(line.Args[1], "v=")
video = line.Args[1][start+2:]
}
if start := strings.Index(line.Args[1], "youtu.be/"); start > -1 {
video = line.Args[1][start+9:]
}
if video != "" {
if end := strings.IndexAny(video, " &#"); end > -1 {
video = video[0:end]
}
youtube(conn, nick, video, target)
} else {
command(conn, nick, line.Args[1], target)
}
}
} else if target == conn.Me.Nick {
// message to us
command(conn, nick, line.Args[1], line.Nick)
}
}
示例13: TestWithTrace
// TestWithTrace ensures that tracing has the expected values in the context.
func TestWithTrace(t *testing.T) {
pc, file, _, _ := runtime.Caller(0) // get current caller.
f := runtime.FuncForPC(pc)
base := []valueTestCase{
{
key: "trace.id",
notnilorempty: true,
},
{
key: "trace.file",
expected: file,
notnilorempty: true,
},
{
key: "trace.line",
notnilorempty: true,
},
{
key: "trace.start",
notnilorempty: true,
},
}
ctx, done := WithTrace(Background())
defer done("this will be emitted at end of test")
checkContextForValues(t, ctx, append(base, valueTestCase{
key: "trace.func",
expected: f.Name(),
}))
traced := func() {
parentID := ctx.Value("trace.id") // ensure the parent trace id is correct.
pc, _, _, _ := runtime.Caller(0) // get current caller.
f := runtime.FuncForPC(pc)
ctx, done := WithTrace(ctx)
defer done("this should be subordinate to the other trace")
time.Sleep(time.Second)
checkContextForValues(t, ctx, append(base, valueTestCase{
key: "trace.func",
expected: f.Name(),
}, valueTestCase{
key: "trace.parent.id",
expected: parentID,
}))
}
traced()
time.Sleep(time.Second)
}
示例14: TestCallFormat
func TestCallFormat(t *testing.T) {
t.Parallel()
c := stack.Caller(0)
pc, file, line, ok := runtime.Caller(0)
line--
if !ok {
t.Fatal("runtime.Caller(0) failed")
}
relFile := path.Join(importPath, filepath.Base(file))
c2, pc2, file2, line2, ok2 := testType{}.testMethod()
if !ok2 {
t.Fatal("runtime.Caller(0) failed")
}
relFile2 := path.Join(importPath, filepath.Base(file2))
data := []struct {
c stack.Call
desc string
fmt string
out string
}{
{stack.Call{}, "error", "%s", "%!s(NOFUNC)"},
{c, "func", "%s", path.Base(file)},
{c, "func", "%+s", relFile},
{c, "func", "%#s", file},
{c, "func", "%d", fmt.Sprint(line)},
{c, "func", "%n", "TestCallFormat"},
{c, "func", "%+n", runtime.FuncForPC(pc - 1).Name()},
{c, "func", "%v", fmt.Sprint(path.Base(file), ":", line)},
{c, "func", "%+v", fmt.Sprint(relFile, ":", line)},
{c, "func", "%#v", fmt.Sprint(file, ":", line)},
{c2, "meth", "%s", path.Base(file2)},
{c2, "meth", "%+s", relFile2},
{c2, "meth", "%#s", file2},
{c2, "meth", "%d", fmt.Sprint(line2)},
{c2, "meth", "%n", "testType.testMethod"},
{c2, "meth", "%+n", runtime.FuncForPC(pc2).Name()},
{c2, "meth", "%v", fmt.Sprint(path.Base(file2), ":", line2)},
{c2, "meth", "%+v", fmt.Sprint(relFile2, ":", line2)},
{c2, "meth", "%#v", fmt.Sprint(file2, ":", line2)},
}
for _, d := range data {
got := fmt.Sprintf(d.fmt, d.c)
if got != d.out {
t.Errorf("fmt.Sprintf(%q, Call(%s)) = %s, want %s", d.fmt, d.desc, got, d.out)
}
}
}
示例15: TestGoroutineSwitch
// Test that profiler does not observe runtime.gogo as "user" goroutine execution.
// If it did, it would see inconsistent state and would either record an incorrect stack
// or crash because the stack was malformed.
func TestGoroutineSwitch(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("flaky test; see http://golang.org/issue/6417")
}
// How much to try. These defaults take about 1 seconds
// on a 2012 MacBook Pro. The ones in short mode take
// about 0.1 seconds.
tries := 10
count := 1000000
if testing.Short() {
tries = 1
}
for try := 0; try < tries; try++ {
var prof bytes.Buffer
if err := StartCPUProfile(&prof); err != nil {
t.Fatal(err)
}
for i := 0; i < count; i++ {
runtime.Gosched()
}
StopCPUProfile()
// Read profile to look for entries for runtime.gogo with an attempt at a traceback.
// The special entry
parseProfile(t, prof.Bytes(), func(count uintptr, stk []uintptr) {
// An entry with two frames with 'System' in its top frame
// exists to record a PC without a traceback. Those are okay.
if len(stk) == 2 {
f := runtime.FuncForPC(stk[1])
if f != nil && f.Name() == "System" {
return
}
}
// Otherwise, should not see runtime.gogo.
// The place we'd see it would be the inner most frame.
f := runtime.FuncForPC(stk[0])
if f != nil && f.Name() == "runtime.gogo" {
var buf bytes.Buffer
for _, pc := range stk {
f := runtime.FuncForPC(pc)
if f == nil {
fmt.Fprintf(&buf, "%#x ?:0\n", pc)
} else {
file, line := f.FileLine(pc)
fmt.Fprintf(&buf, "%#x %s:%d\n", pc, file, line)
}
}
t.Fatalf("found profile entry for runtime.gogo:\n%s", buf.String())
}
})
}
}