jvm.go 7.2 KB

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