jvm.go 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. package ebpftracer
  2. import (
  3. "errors"
  4. "github.com/coroot/coroot-node-agent/common"
  5. "github.com/coroot/coroot-node-agent/ebpftracer/tracer/inject"
  6. klog "github.com/sirupsen/logrus"
  7. "io/ioutil"
  8. "runtime"
  9. "strings"
  10. "debug/elf"
  11. "fmt"
  12. "path/filepath"
  13. "github.com/cilium/ebpf/link"
  14. "github.com/coroot/coroot-node-agent/proc"
  15. "golang.org/x/arch/arm64/arm64asm"
  16. "golang.org/x/arch/x86/x86asm"
  17. )
  18. const (
  19. // goServeHTTP = "net/http.serverHandler.ServeHTTP"
  20. // binPath = "/root/code/jdk8u/build/linux-x86_64-normal-server-release/jdk/lib/amd64/libnio.so"
  21. symbolsocketRead0 = "Java_sun_nio_ch_FileDispatcherImpl_read0"
  22. )
  23. func (t *Tracer) AttachJavaNioReadUprobes(pid uint32, codeType common.CodeType) ([]link.Link, error) {
  24. if t.DisableL7Tracing() {
  25. return nil, nil
  26. }
  27. var links []link.Link
  28. var bpath = ""
  29. // JavaAOT 逻辑
  30. if codeType.IsJavaAotCode() {
  31. bpath = proc.Path(uint32(pid), "exe")
  32. } else {
  33. version := UsePIDToGetJDKVersion(pid)
  34. klog.Infof("[attach] java version is %s", version)
  35. bpath = getSoPath(pid, "libnio.so")
  36. if bpath == "" {
  37. return nil, errors.New("can not find nio.so")
  38. }
  39. }
  40. klog.Infof("[attach] find the nio.so path is %s", bpath)
  41. ex, err := link.OpenExecutable(bpath)
  42. if err != nil {
  43. return nil, err
  44. }
  45. ef, err := elf.Open(bpath)
  46. if err != nil {
  47. return nil, err
  48. //PID: int(pid),
  49. }
  50. defer ef.Close()
  51. symbols, err := ef.DynamicSymbols()
  52. if err != nil {
  53. if errors.Is(err, elf.ErrNoSymbols) {
  54. return nil, err
  55. }
  56. return nil, err
  57. }
  58. textSection := ef.Section(".text")
  59. if textSection == nil {
  60. return nil, errors.New("can not find .text section")
  61. }
  62. textSectionData, err := textSection.Data()
  63. if err != nil {
  64. return nil, err
  65. }
  66. textSectionLen := uint64(len(textSectionData) - 1)
  67. // opt := link.UprobeOptions{
  68. // Offset: 61,
  69. // }
  70. // upread02, err := ex.Uprobe(symbolsocketRead0, t.uprobes["uprobe_ret_Java_sun_nio_ch_FileDispatcherImpl_read0"], &opt)
  71. // if err != nil {
  72. // return nil
  73. // }
  74. // links = append(links, upread01)
  75. for _, s := range symbols {
  76. if elf.ST_TYPE(s.Info) != elf.STT_FUNC || s.Size == 0 {
  77. continue
  78. }
  79. switch s.Name {
  80. case symbolsocketRead0:
  81. default:
  82. continue
  83. }
  84. address := s.Value
  85. for _, p := range ef.Progs {
  86. if p.Type != elf.PT_LOAD || (p.Flags&elf.PF_X) == 0 {
  87. continue
  88. }
  89. if p.Vaddr <= s.Value && s.Value < (p.Vaddr+p.Memsz) {
  90. address = s.Value - p.Vaddr + p.Off
  91. break
  92. }
  93. }
  94. klog.Infof("[attach] java symbol name is %s", s.Name)
  95. switch s.Name {
  96. case symbolsocketRead0:
  97. sStart := s.Value - textSection.Addr
  98. sEnd := sStart + s.Size
  99. if sEnd > textSectionLen {
  100. continue
  101. }
  102. sBytes := textSectionData[sStart:sEnd]
  103. returnOffsets := getCallNextMoveOffsets(ef.Machine, sBytes)
  104. if len(returnOffsets) == 0 {
  105. return nil, fmt.Errorf("failed to attach uprobe_ret_Java_sun_nio_ch_FileDispatcherImpl_read0 uprobe")
  106. }
  107. for _, offset := range returnOffsets {
  108. l, err := ex.Uprobe(s.Name, t.uprobes["uprobe_ret_Java_sun_nio_ch_FileDispatcherImpl_read0"], &link.UprobeOptions{Address: address, Offset: uint64(offset), PID: int(pid)})
  109. if err != nil {
  110. return nil, fmt.Errorf("failed to attach uprobe_ret_Java_sun_nio_ch_FileDispatcherImpl_read0 uprobe")
  111. }
  112. links = append(links, l)
  113. }
  114. }
  115. }
  116. if len(links) == 0 {
  117. return nil, fmt.Errorf("no links found for %s", bpath)
  118. }
  119. klog.WithField("pid", pid).Infof("[attach] libnio attached!")
  120. return links, nil
  121. }
  122. func (t *Tracer) AttachJavaNetWriteUprobes(pid uint32) ([]link.Link, error) {
  123. if t.DisableL7Tracing() {
  124. return nil, nil
  125. }
  126. // 关闭横向串联
  127. if t.DisableE2ETracing() {
  128. return nil, nil
  129. }
  130. //inject
  131. originFunc := "Java_java_net_SocketOutputStream_socketWrite0"
  132. uProbeData := inject.UprobeData{
  133. Offset: 53,
  134. Func: originFunc,
  135. ELFPath: "/root/cwlibnet.so",
  136. }
  137. if runtime.GOARCH == "arm64" {
  138. uProbeData = inject.UprobeData{
  139. Offset: 8,
  140. Func: "CW_" + originFunc,
  141. ELFPath: "/root/cwlibnet.so",
  142. }
  143. }
  144. jvmInjector := &inject.JvmInjector{
  145. Pid: int(pid),
  146. ReleaseLibNetInfo: inject.LibNetInfo{
  147. LibName: "libnet.so",
  148. FuncSymbol: inject.InstInfo{
  149. SymName: originFunc,
  150. },
  151. },
  152. DebugLibNetInfo: inject.LibNetInfo{
  153. // TODO 根据版本设置
  154. LibName: filepath.Base(uProbeData.ELFPath),
  155. // TODO 根据版本设置
  156. LibPath: uProbeData.ELFPath,
  157. FuncSymbol: inject.InstInfo{
  158. SymName: uProbeData.Func,
  159. },
  160. },
  161. RecodeInfo: inject.LibNetInfo{FuncSymbol: inject.InstInfo{SymName: "CW_RECODE_" + originFunc}},
  162. Uprobe: uProbeData,
  163. }
  164. err := inject.JvmInject(jvmInjector)
  165. if err != nil {
  166. return nil, err
  167. }
  168. var links []link.Link
  169. ex, err := link.OpenExecutable(jvmInjector.Uprobe.ELFPath)
  170. if err != nil {
  171. return nil, err
  172. }
  173. opt := link.UprobeOptions{
  174. Offset: uint64(jvmInjector.Uprobe.Offset),
  175. PID: int(pid),
  176. }
  177. upread02, err := ex.Uprobe(jvmInjector.Uprobe.Func, t.uprobes["uprobe_Java_java_net_SocketOutputStream_socketWrite0"], &opt)
  178. if err != nil {
  179. return nil, err
  180. }
  181. links = append(links, upread02)
  182. if len(links) == 0 {
  183. return nil, errors.New("can not find uprobe_Java_net_SocketOutputStream_socketWrite0")
  184. }
  185. klog.WithField("pid", pid).Infoln("[jvm] libnet attached")
  186. return links, nil
  187. }
  188. func getCallNextMoveOffsets(machine elf.Machine, instructions []byte) []int {
  189. var res []int
  190. firstCall := 0
  191. switch machine {
  192. case elf.EM_X86_64:
  193. for i := 0; i < len(instructions); {
  194. ins, err := x86asm.Decode(instructions[i:], 64)
  195. if err == nil && ins.Op == x86asm.CALL {
  196. if firstCall == 0 {
  197. firstCall = 1
  198. } else {
  199. i += ins.Len
  200. res = append(res, i)
  201. return res
  202. }
  203. }
  204. i += ins.Len
  205. }
  206. case elf.EM_AARCH64:
  207. for i := 0; i < len(instructions); {
  208. ins, err := arm64asm.Decode(instructions[i:])
  209. if err == nil && ins.Op == arm64asm.BL {
  210. if firstCall == 0 {
  211. firstCall = 1
  212. } else {
  213. i += 4
  214. res = append(res, i)
  215. return res
  216. }
  217. }
  218. i += 4
  219. }
  220. }
  221. return res
  222. }
  223. func getSoPath(pid uint32, soname string) string {
  224. // 获取进程的maps文件路径
  225. mapsPath := fmt.Sprintf("/proc/%d/maps", pid)
  226. // 读取maps文件内容
  227. mapsData, err := ioutil.ReadFile(mapsPath)
  228. if err != nil {
  229. fmt.Println("lookup so error.")
  230. return ""
  231. }
  232. lines := strings.Split(string(mapsData), "\n")
  233. for _, line := range lines {
  234. fields := strings.Fields(line)
  235. if len(fields) >= 6 {
  236. perms := fields[1]
  237. path := fields[len(fields)-1]
  238. if strings.Contains(perms, "x") && filepath.Ext(path) == ".so" {
  239. if strings.Contains(path, soname) {
  240. return path
  241. }
  242. }
  243. }
  244. }
  245. return ""
  246. }