stack.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  1. package ebpftracer
  2. import (
  3. "context"
  4. "debug/elf"
  5. debugelf "debug/elf"
  6. "fmt"
  7. "io"
  8. "log"
  9. "os"
  10. "regexp"
  11. "sort"
  12. "strconv"
  13. "github.com/cilium/ebpf"
  14. "github.com/cilium/ebpf/link"
  15. "github.com/coroot/coroot-node-agent/ebpftracer/tracer"
  16. "github.com/coroot/coroot-node-agent/proc"
  17. "golang.org/x/sync/semaphore"
  18. )
  19. func (t *Tracer) stack() error {
  20. // uprobes := []tracer.Uprobe{}
  21. if t.disableL7Tracing {
  22. return nil
  23. }
  24. ENV_PID := os.Getenv("FILTER_PID")
  25. WHITE_LIST := os.Getenv("WHITE_LIST")
  26. if ENV_PID == "" {
  27. return nil
  28. }
  29. MatchString := ".*HandleFunc|.*main.*|testfun.*|.*serverHandler.*|.*ServeHTTP.*"
  30. if WHITE_LIST != "" {
  31. MatchString = WHITE_LIST
  32. }
  33. fmt.Println("UprobesMatchString::: init", MatchString)
  34. pid, _ := strconv.ParseInt(ENV_PID, 10, 32)
  35. path := proc.Path(uint32(pid), "exe")
  36. t.Uprobes, _ = t.getUprobes(path, MatchString)
  37. t.UprobesMap = map[string]tracer.Uprobe{}
  38. fmt.Println("UprobesMap::: init")
  39. for _, up := range t.Uprobes {
  40. fmt.Println("UprobesMap:::", up.Funcname)
  41. t.UprobesMap[fmt.Sprintf("%s", up.Funcname)] = up
  42. }
  43. links := t.attachUprobes(path, t.Uprobes)
  44. t.links = append(t.links, links...)
  45. // defer t.detachUprobes(links)
  46. return nil
  47. }
  48. func (t *Tracer) getUprobes(path string, MatchString string) ([]tracer.Uprobe, error) {
  49. uprobes := []tracer.Uprobe{}
  50. binFile, err := os.Open(path)
  51. if err != nil {
  52. return nil, err
  53. }
  54. // cache := map[string]interface{}{}
  55. // 解析 elf 文件
  56. elfFile, _ := debugelf.NewFile(binFile)
  57. // 获取所有符号表
  58. symbols, _ := elfFile.Symbols()
  59. sort.Slice(symbols, func(i, j int) bool { return symbols[i].Value < symbols[j].Value })
  60. t.Symbols = symbols
  61. // 符号表组装成键值 map,方便使用
  62. symnames := map[string]debugelf.Symbol{}
  63. for _, symbol := range symbols {
  64. fmt.Println(symbol.Name, symbol)
  65. symnames[symbol.Name] = symbol
  66. }
  67. textSection := elfFile.Section(".text")
  68. if textSection == nil {
  69. fmt.Println("no text section", nil)
  70. return nil, nil
  71. }
  72. textSectionData, err := textSection.Data()
  73. if err != nil {
  74. fmt.Println("failed to read text section", err)
  75. return nil, nil
  76. }
  77. textSectionLen := uint64(len(textSectionData) - 1)
  78. // 遍历符号表
  79. for _, symbol := range symbols {
  80. if debugelf.ST_TYPE(symbol.Info) != debugelf.STT_FUNC {
  81. continue
  82. }
  83. // fmt.Println("Hello FunName: ", symbol.Name)
  84. // 使用正则表达式匹配函数白名单列表
  85. found, err := regexp.MatchString(MatchString, symbol.Name)
  86. // found, err := regexp.MatchString("main.*", symbol.Name)
  87. if err != nil {
  88. log.Fatal(err)
  89. }
  90. if found {
  91. // 匹配到了加入 attachFuncs 列表
  92. fmt.Println("Fuck This: ", symbol.Name)
  93. // attachFuncs = append(attachFuncs, symbol.Name)
  94. // 根据函数名拿到当前函数的符号结构体
  95. sym := symnames[symbol.Name]
  96. if err != nil {
  97. fmt.Printf("symnames[symbol.Name]", symbol.Name, err)
  98. return nil, err
  99. }
  100. address := sym.Value
  101. for _, p := range elfFile.Progs {
  102. if p.Type != elf.PT_LOAD || (p.Flags&elf.PF_X) == 0 {
  103. continue
  104. }
  105. if p.Vaddr <= sym.Value && sym.Value < (p.Vaddr+p.Memsz) {
  106. address = sym.Value - p.Vaddr + p.Off
  107. break
  108. }
  109. }
  110. // 函数入口加入待 attach 列表
  111. uprobes = append(uprobes, tracer.Uprobe{
  112. Funcname: symbol.Name, // 函数名
  113. Location: tracer.AtEntry, // 入口
  114. Address: address, // 函数地址
  115. AbsOffset: 0, // 函数相对 ELF 偏移
  116. RelOffset: 0, // 函数真实偏移
  117. Wanted: true,
  118. })
  119. sStart := sym.Value - textSection.Addr
  120. sEnd := sStart + sym.Size
  121. if sEnd > textSectionLen {
  122. continue
  123. }
  124. sBytes := textSectionData[sStart:sEnd]
  125. returnOffsets := getReturnOffsets(elfFile.Machine, sBytes)
  126. for _, offset := range returnOffsets {
  127. uprobes = append(uprobes, tracer.Uprobe{
  128. Funcname: symbol.Name,
  129. Location: tracer.AtRet,
  130. Address: address,
  131. AbsOffset: uint64(offset),
  132. RelOffset: 0,
  133. })
  134. }
  135. }
  136. }
  137. return uprobes, nil
  138. }
  139. func (t *Tracer) attachUprobes(path string, uprobes []tracer.Uprobe) []link.Link {
  140. var links []link.Link
  141. ex, err := link.OpenExecutable(path)
  142. if err != nil {
  143. return nil
  144. }
  145. fmt.Println("AttachAttachAttach", path)
  146. for i, up := range t.uprobes {
  147. fmt.Println("attachingERROR---", i, up)
  148. }
  149. for i, up := range uprobes {
  150. fmt.Printf("attaching %d -> %d -> %s -> 0x%x -> 0x%x\n", i, len(uprobes), up.Funcname, up.AbsOffset, up.Address)
  151. var prog *ebpf.Program
  152. switch up.Location {
  153. case tracer.AtEntry:
  154. prog = t.uprobes["ent"]
  155. case tracer.AtRet:
  156. prog = t.uprobes["ret"]
  157. }
  158. fmt.Println("progprogprogprogprogprog---", prog)
  159. up, err := ex.Uprobe(up.Funcname, prog, &link.UprobeOptions{Address: up.Address, Offset: up.AbsOffset})
  160. if err != nil {
  161. fmt.Println("attachingERROR", err)
  162. // return nil
  163. } else {
  164. links = append(links, up)
  165. }
  166. }
  167. return links
  168. }
  169. func (t *Tracer) detachUprobes(links []link.Link) {
  170. sem := semaphore.NewWeighted(10)
  171. for i, closer := range links {
  172. fmt.Printf("detaching %d/%d\r", i+1, len(links))
  173. sem.Acquire(context.Background(), 1)
  174. go func(closer io.Closer) {
  175. defer sem.Release(1)
  176. closer.Close()
  177. }(closer)
  178. }
  179. fmt.Println()
  180. }