github.com/bytedance/mockey@v1.2.10/internal/tool/caller.go (about) 1 /* 2 * Copyright 2022 ByteDance Inc. 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package tool 18 19 import ( 20 "fmt" 21 "runtime" 22 "strings" 23 ) 24 25 type CallerInfo runtime.Frame 26 27 func (c CallerInfo) String() string { 28 return fmt.Sprintf("%s:%d", c.File, c.Line) 29 } 30 31 // Caller gets non-current package caller of a function 32 // For example, assume we have 3 files: a/b/foo.go, a/c/bar.go and a/c/innerBar.go, 33 // a/b/foo.Foo calls a/c/bar.Bar, and a/c/bar.Bar calls a/c/innerBar.innerBar. 34 // Here is how innerBar looks like: 35 // 36 // func innerBar() CallerInfo { /*do some thing*/ return Caller() } 37 // 38 // The return value of innerBar should represent the line in a/b/foo.go where a/b/foo.Foo calls a/c/bar.Bar 39 func OuterCaller() (info CallerInfo) { 40 defer func() { 41 if err := recover(); err != nil { 42 DebugPrintf("OuterCaller: get stack failed, err: %v", err) 43 info = CallerInfo(runtime.Frame{File: "Nan"}) 44 } 45 }() 46 47 caller, _, _, _ := runtime.Caller(1) 48 oriPkg, _ := getPackageAndFunction(caller) 49 50 pc := make([]uintptr, 10) 51 n := runtime.Callers(2, pc) 52 pc = pc[:n] 53 frames := runtime.CallersFrames(pc) 54 for frame, more := frames.Next(); more; frame, more = frames.Next() { 55 curPkg, _ := getPackageAndFunction(frame.PC) 56 if curPkg != oriPkg { 57 return CallerInfo(frame) 58 } 59 } 60 return CallerInfo(runtime.Frame{File: "Nan"}) 61 } 62 63 func Caller() CallerInfo { 64 caller, _, _, _ := runtime.Caller(1) 65 frame, _ := runtime.CallersFrames([]uintptr{caller}).Next() 66 return CallerInfo(frame) 67 } 68 69 func getPackageAndFunction(pc uintptr) (string, string) { 70 parts := strings.Split(runtime.FuncForPC(pc).Name(), ".") 71 pl := len(parts) 72 packageName := "" 73 funcName := parts[pl-1] 74 75 // if mock run in an anonymous function of a global variable, 76 // the stack will looks like a.b.c.glob..func1(), so the 77 // second last part of the caller stack would not be guaranteed 78 // always to be non-empty. 79 if len(parts[pl-2]) > 0 && parts[pl-2][0] == '(' { 80 funcName = parts[pl-2] + "." + funcName 81 packageName = strings.Join(parts[0:pl-2], ".") 82 } else { 83 packageName = strings.Join(parts[0:pl-1], ".") 84 } 85 return packageName, funcName 86 }