-
Notifications
You must be signed in to change notification settings - Fork 0
/
func_call.go
54 lines (46 loc) · 1.73 KB
/
func_call.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package logic
import (
"runtime"
)
// Get Current Function runtime.Frame
// Returns:
// runtime.Frame Selected frame or deafult <function name: unknown> fake frame
func GetCurrentFunction() runtime.Frame {
// Skip GetCurrentFunction
return getFrame(1)
}
// Get Current Function Caller runtime.Frame
// Returns:
// runtime.Frame Selected frame or deafult <function name: unknown> fake frame
func GetCallerFunction() runtime.Frame {
// Skip GetCallerFunction and the function to get the caller of
return getFrame(2)
}
// Get Current Function Caller runtime.Frame before provided back iterations, starting with 1 as caller
// Parameters:
// framesBefore (int) Number of previous callers iterations to verify
// Returns:
// runtime.Frame Selected frame or deafult <function name: unknown> fake frame
func GetCallerFunctionBeforeCurrent(framesBefore int) runtime.Frame {
// Skip GetCallerFunction before (1 is previous function call) and the function to get the caller of
return getFrame(1 + framesBefore)
}
func getFrame(skipFrames int) runtime.Frame {
// We need the frame at index skipFrames+2, since we never want runtime.Callers and getFrame
targetFrameIndex := skipFrames + 2
// Set size to targetFrameIndex+2 to ensure we have room for one more caller than we need
programCounters := make([]uintptr, targetFrameIndex+2)
n := runtime.Callers(0, programCounters)
frame := runtime.Frame{Function: "unknown"}
if n > 0 {
frames := runtime.CallersFrames(programCounters[:n])
for more, frameIndex := true, 0; more && frameIndex <= targetFrameIndex; frameIndex++ {
var frameCandidate runtime.Frame
frameCandidate, more = frames.Next()
if frameIndex == targetFrameIndex {
frame = frameCandidate
}
}
}
return frame
}