tls.go 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926
  1. package ebpftracer
  2. import (
  3. "bufio"
  4. "bytes"
  5. "debug/buildinfo"
  6. "debug/elf"
  7. "errors"
  8. "fmt"
  9. "os"
  10. "regexp"
  11. "strconv"
  12. "strings"
  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. . "github.com/coroot/coroot-node-agent/utils/modelse"
  18. klog "github.com/sirupsen/logrus"
  19. "golang.org/x/arch/arm64/arm64asm"
  20. "golang.org/x/arch/x86/x86asm"
  21. "golang.org/x/mod/semver"
  22. )
  23. const (
  24. minSupportedGoVersion = "v1.15.0"
  25. goTlsWriteSymbol = "crypto/tls.(*Conn).Write"
  26. goTlsReadSymbol = "crypto/tls.(*Conn).Read"
  27. goExecute = "runtime.execute"
  28. goNewproc1 = "runtime.newproc1"
  29. goRunqget = "runtime.runqget"
  30. goGoready = "runtime.goready"
  31. goServeHTTP = "net/http.serverHandler.ServeHTTP"
  32. goTransport = "net/http.(*Transport).roundTrip"
  33. goGrpcServerHandleStream = "google.golang.org/grpc.(*Server).handleStream"
  34. goGrpcHttp2OperateHeader = "google.golang.org/grpc/internal/transport.(*http2Server).operateHeaders"
  35. goGrpcServerWritestatus = "google.golang.org/grpc/internal/transport.(*http2Server).WriteStatus"
  36. goGrpcClientConnInvoke = "google.golang.org/grpc.(*ClientConn).Invoke"
  37. goGrpcClientLoopyHeaderHandler = "google.golang.org/grpc/internal/transport.(*loopyWriter).headerHandler"
  38. goGrpcHttp2ClientNewStream = "google.golang.org/grpc/internal/transport.(*http2Client).NewStream"
  39. goReadContinuedLineSlice = "net/textproto.(*Reader).readContinuedLineSlice"
  40. goGocqlSessionExecuteQuery = "github.com/gocql/gocql.(*Session).executeQuery"
  41. )
  42. var (
  43. opensslVersionRe = regexp.MustCompile(`OpenSSL\s(\d\.\d+\.\d+)`)
  44. )
  45. func (t *Tracer) AttachOpenSslUprobes(pid uint32) ([]link.Link, error) {
  46. if t.DisableL7Tracing() {
  47. return nil, nil
  48. }
  49. libPath, version := getSslLibPathAndVersion(pid)
  50. if libPath == "" || version == "" {
  51. return nil, nil
  52. }
  53. log := func(msg string, err error) {
  54. if err != nil {
  55. for _, s := range []string{"no such file or directory", "no such process", "permission denied"} {
  56. if strings.HasSuffix(err.Error(), s) {
  57. return
  58. }
  59. }
  60. klog.Errorf("pid=%d libssl_version=%s: %s: %s", pid, version, msg, err)
  61. return
  62. }
  63. klog.Infof("pid=%d libssl_version=%s: %s", pid, version, msg)
  64. }
  65. exe, err := link.OpenExecutable(libPath)
  66. if err != nil {
  67. log("failed to open executable", err)
  68. return nil, err
  69. }
  70. var links []link.Link
  71. writeEnter := "openssl_SSL_write_enter"
  72. readEnter := "openssl_SSL_read_enter"
  73. readExEnter := "openssl_SSL_read_ex_enter"
  74. readExit := "openssl_SSL_read_exit"
  75. switch {
  76. case semver.Compare(version, "v3.0.0") >= 0:
  77. writeEnter = "openssl_SSL_write_enter_v3_0"
  78. readEnter = "openssl_SSL_read_enter_v3_0"
  79. readExEnter = "openssl_SSL_read_ex_enter_v3_0"
  80. case semver.Compare(version, "v1.1.1") >= 0:
  81. writeEnter = "openssl_SSL_write_enter_v1_1_1"
  82. readEnter = "openssl_SSL_read_enter_v1_1_1"
  83. readExEnter = "openssl_SSL_read_ex_enter_v1_1_1"
  84. }
  85. type prog struct {
  86. symbol string
  87. uprobe string
  88. uretprobe string
  89. }
  90. progs := []prog{
  91. {symbol: "SSL_write", uprobe: writeEnter},
  92. {symbol: "SSL_read", uprobe: readEnter},
  93. {symbol: "SSL_read", uretprobe: readExit},
  94. }
  95. if semver.Compare(version, "v1.1.1") >= 0 {
  96. progs = append(progs, []prog{
  97. {symbol: "SSL_write_ex", uprobe: writeEnter},
  98. {symbol: "SSL_read_ex", uprobe: readExEnter},
  99. {symbol: "SSL_read_ex", uretprobe: readExit},
  100. }...)
  101. }
  102. for _, p := range progs {
  103. if p.uprobe != "" {
  104. l, err := exe.Uprobe(p.symbol, t.uprobes[p.uprobe], nil)
  105. klog.Infoln("fucktls crypto/tls uprobes attached", p.symbol)
  106. if err != nil {
  107. //log("failed to attach uprobe", err)
  108. klog.Infoln("fucktls crypto/tls uprobes attached error", p.symbol)
  109. return nil, err
  110. }
  111. links = append(links, l)
  112. }
  113. if p.uretprobe != "" {
  114. klog.Infoln("fucktls crypto/tls uprobes attached ret", p.symbol)
  115. l, err := exe.Uretprobe(p.symbol, t.uprobes[p.uretprobe], nil)
  116. if err != nil {
  117. klog.Infoln("fucktls crypto/tls uprobes attached ret error", p.symbol)
  118. //log("failed to attach uretprobe", err)
  119. return nil, err
  120. }
  121. links = append(links, l)
  122. }
  123. }
  124. //log("libssl uprobes attached", nil)
  125. return links, nil
  126. }
  127. func (t *Tracer) AttachGoTlsUprobes(pid uint32, appInfo *AppInfo, codeType uint16) ([]link.Link, error) {
  128. klog.Infof("[AttachGoTlsUprobes] STEP 1: Function entry, pid=%d", pid)
  129. if t.DisableL7Tracing() {
  130. klog.Infof("[AttachGoTlsUprobes] STEP 1.1: L7 tracing disabled, returning early")
  131. return nil, nil
  132. }
  133. path := proc.Path(pid, "exe")
  134. klog.Infof("[AttachGoTlsUprobes] STEP 2: Got executable path, pid=%d, path=%s", pid, path)
  135. instanceID := appInfo.InstanceIdHash.HashtVal
  136. appID := appInfo.AppIdHash.HashtVal
  137. var err error
  138. var name, version string
  139. var major, minor, revision int
  140. log := func(msg string, err error) {
  141. if err != nil {
  142. for _, s := range []string{"not a Go executable", "no such file or directory", "no such process", "permission denied"} {
  143. if strings.HasSuffix(err.Error(), s) {
  144. return
  145. }
  146. }
  147. klog.Errorf("pid=%d golang_app=%s golang_version=%s: %s: %s", pid, name, version, msg, err)
  148. return
  149. }
  150. klog.Infof("pid=%d golang_app=%s golang_version=%s: %s", pid, name, version, msg)
  151. }
  152. klog.Infof("[AttachGoTlsUprobes] STEP 3: Reading buildinfo from %s", path)
  153. bi, err := buildinfo.ReadFile(path)
  154. if err != nil {
  155. klog.Errorf("[AttachGoTlsUprobes] STEP 3.1: Failed to read buildinfo, pid=%d, error=%v", pid, err)
  156. log("failed to read build info", err)
  157. return nil, err
  158. }
  159. klog.Infof("[AttachGoTlsUprobes] STEP 3.2: Buildinfo read successfully, GoVersion=%s", bi.GoVersion)
  160. // isGolangApp = true
  161. klog.Infof("[AttachGoTlsUprobes] STEP 4: Reading executable link")
  162. name, err = os.Readlink(path)
  163. if err != nil {
  164. klog.Errorf("[AttachGoTlsUprobes] STEP 4.1: Failed to readlink, pid=%d, error=%v", pid, err)
  165. log("failed to read name", err)
  166. return nil, err
  167. }
  168. klog.Infof("[AttachGoTlsUprobes] STEP 4.2: Executable name=%s", name)
  169. version = strings.Replace(bi.GoVersion, "go", "v", 1)
  170. klog.Infof("[AttachGoTlsUprobes] STEP 5: Checking version compatibility, version=%s, minSupported=%s", version, minSupportedGoVersion)
  171. if semver.Compare(version, minSupportedGoVersion) < 0 {
  172. klog.Errorf("[AttachGoTlsUprobes] STEP 5.1: Version too old, version=%s < minSupported=%s", version, minSupportedGoVersion)
  173. log(fmt.Sprintf("go_versions below %s are not supported", minSupportedGoVersion), nil)
  174. return nil, err
  175. }
  176. klog.Infof("[AttachGoTlsUprobes] STEP 5.2: Version check passed")
  177. klog.Infof("[AttachGoTlsUprobes] STEP 6: Opening ELF file")
  178. ef, err := elf.Open(path)
  179. if err != nil {
  180. klog.Errorf("[AttachGoTlsUprobes] STEP 6.1: Failed to open ELF, pid=%d, error=%v", pid, err)
  181. log("failed to open as elf binary", err)
  182. return nil, err
  183. }
  184. defer ef.Close()
  185. klog.Infof("[AttachGoTlsUprobes] STEP 6.2: ELF file opened successfully")
  186. klog.Infof("[AttachGoTlsUprobes] STEP 7: Reading symbols")
  187. symbols, err := ef.Symbols()
  188. if err != nil {
  189. if errors.Is(err, elf.ErrNoSymbols) {
  190. klog.Warnf("[AttachGoTlsUprobes] STEP 7.1: No symbol section, pid=%d", pid)
  191. log("no symbol section", nil)
  192. return nil, err
  193. }
  194. klog.Errorf("[AttachGoTlsUprobes] STEP 7.2: Failed to read symbols, pid=%d, error=%v", pid, err)
  195. log("failed to read symbols", err)
  196. return nil, err
  197. }
  198. klog.Infof("[AttachGoTlsUprobes] STEP 7.3: Symbols read successfully, count=%d", len(symbols))
  199. klog.Infof("[AttachGoTlsUprobes] STEP 8: Reading .text section")
  200. textSection := ef.Section(".text")
  201. if textSection == nil {
  202. klog.Errorf("[AttachGoTlsUprobes] STEP 8.1: No .text section, pid=%d", pid)
  203. log("no text section", nil)
  204. return nil, err
  205. }
  206. textSectionData, err := textSection.Data()
  207. if err != nil {
  208. klog.Errorf("[AttachGoTlsUprobes] STEP 8.2: Failed to read .text section data, pid=%d, error=%v", pid, err)
  209. log("failed to read text section", err)
  210. return nil, err
  211. }
  212. textSectionLen := uint64(len(textSectionData) - 1)
  213. klog.Infof("[AttachGoTlsUprobes] STEP 8.3: .text section read, size=%d", textSectionLen)
  214. klog.Infof("[AttachGoTlsUprobes] STEP 9: Opening executable for uprobe")
  215. exe, err := link.OpenExecutable(path)
  216. if err != nil {
  217. klog.Errorf("[AttachGoTlsUprobes] STEP 9.1: Failed to open executable for uprobe, pid=%d, error=%v", pid, err)
  218. log("failed to open executable", err)
  219. return nil, err
  220. }
  221. klog.Infof("[AttachGoTlsUprobes] STEP 9.2: Executable opened for uprobe")
  222. // 检测 gRPC 版本
  223. klog.Infof("[AttachGoTlsUprobes] STEP 10: Detecting gRPC version")
  224. var grpcMajorVersion, grpcMinorVersion int
  225. for _, dep := range bi.Deps {
  226. if strings.Contains(dep.Path, "grpc") {
  227. klog.Infoln("Found gRPC dependency:", dep.Path, "version:", dep.Version)
  228. // 解析版本号
  229. version := dep.Version
  230. if version != "" {
  231. // 移除可能的 "v" 前缀
  232. version = strings.TrimPrefix(version, "v")
  233. parts := strings.Split(version, ".")
  234. if len(parts) >= 2 {
  235. major, err := strconv.Atoi(parts[0])
  236. if err != nil {
  237. klog.WithError(err).Warnf("Error parsing major version from %s", parts[0])
  238. continue
  239. }
  240. minor, err := strconv.Atoi(parts[1])
  241. if err != nil {
  242. klog.WithError(err).Warnf("Error parsing minor version from %s", parts[1])
  243. continue
  244. }
  245. klog.Infof("Detected gRPC version: %d.%d for PID %d", major, minor, pid)
  246. grpcMajorVersion = major
  247. grpcMinorVersion = minor
  248. // // 根据版本选择相应的探针策略
  249. // if major == 1 && minor >= 69 {
  250. // klog.Infof("Using modern gRPC handler for version %d.%d", major, minor)
  251. // } else {
  252. // klog.Infof("Using legacy gRPC handler for version %d.%d", major, minor)
  253. // }
  254. }
  255. }
  256. }
  257. }
  258. klog.Infof("[AttachGoTlsUprobes] STEP 10.1: gRPC version detection completed, major=%d, minor=%d", grpcMajorVersion, grpcMinorVersion)
  259. klog.Infof("[AttachGoTlsUprobes] STEP 11: Getting offset for runtime.g.goid")
  260. offset, ok := tracer.GetOffset(tracer.NewID("std", "runtime", "g", "goid"), path)
  261. if ok {
  262. klog.Infof("[AttachGoTlsUprobes] STEP 11.1: Successfully got goid offset=%d", offset)
  263. } else {
  264. klog.Errorf("[AttachGoTlsUprobes] STEP 11.2: Failed to get goid offset, pid=%d, version=%s", pid, bi.GoVersion)
  265. }
  266. // 获取 runtime.p.goidcache 偏移量
  267. klog.Infof("[AttachGoTlsUprobes] STEP 11.3: Getting offset for runtime.p.goidcache")
  268. goidcacheOffset, okGoidcache := tracer.GetOffset(tracer.NewID("std", "runtime", "p", "goidcache"), path)
  269. if okGoidcache {
  270. klog.Infof("[AttachGoTlsUprobes] STEP 11.4: Successfully got goidcache offset=%d", goidcacheOffset)
  271. } else {
  272. klog.Warnf("[AttachGoTlsUprobes] STEP 11.5: Failed to get goidcache offset, pid=%d, version=%s, using fallback", pid, bi.GoVersion)
  273. goidcacheOffset = 384 // fallback value
  274. }
  275. // 获取 runtime.p.runnext 偏移量
  276. klog.Infof("[AttachGoTlsUprobes] STEP 11.6: Getting offset for runtime.p.runnext")
  277. runnextOffset, okRunnext := tracer.GetOffset(tracer.NewID("std", "runtime", "p", "runnext"), path)
  278. if okRunnext {
  279. klog.Infof("[AttachGoTlsUprobes] STEP 11.7: Successfully got runnext offset=%d", runnextOffset)
  280. } else {
  281. klog.Warnf("[AttachGoTlsUprobes] STEP 11.8: Failed to get runnext offset, pid=%d, version=%s, using fallback", pid, bi.GoVersion)
  282. runnextOffset = 2456 // fallback value
  283. }
  284. klog.Infof("[AttachGoTlsUprobes] STEP 12: Getting offset for runtime.hmap.buckets")
  285. bucketsOff, ok2 := tracer.GetOffset(tracer.NewID("std", "runtime", "hmap", "buckets"), path)
  286. // Go 1.24+ 使用新的 map 实现(Swiss Tables),使用 internal/runtime/maps.Map 而不是 runtime.hmap
  287. if !ok2 {
  288. klog.Errorf("[AttachGoTlsUprobes] STEP 12.2: Failed to get buckets offset, pid=%d, version=%s", pid, bi.GoVersion)
  289. klog.Infof("[AttachGoTlsUprobes] STEP 12.3: Trying Swiss Tables maps.Map.dirPtr for Go 1.24+")
  290. // Go 1.24+ Swiss Tables 使用 internal/runtime/maps.Map 结构体
  291. // 结构体字段:used uint64, seed uintptr, dirPtr unsafe.Pointer (相当于旧的 buckets)
  292. // 尝试获取 maps.Map.dirPtr 的偏移量
  293. // 注意:DWARF 中的包路径可能是 "internal/runtime/maps" 或 "internal/runtime/maps.Map"
  294. swissFields := []struct {
  295. pkg string
  296. structName string
  297. field string
  298. }{
  299. {"internal/runtime/maps", "Map", "dirPtr"},
  300. {"internal.runtime.maps", "Map", "dirPtr"},
  301. {"maps", "Map", "dirPtr"},
  302. }
  303. for _, sf := range swissFields {
  304. // 尝试不同的包路径格式
  305. swissOff, swissOk := tracer.GetOffset(tracer.NewID("std", sf.pkg, sf.structName, sf.field), path)
  306. if swissOk {
  307. klog.Infof("[AttachGoTlsUprobes] STEP 12.4: Found Swiss Tables field '%s.%s.%s' with offset=%d", sf.pkg, sf.structName, sf.field, swissOff)
  308. bucketsOff = swissOff
  309. ok2 = true
  310. break
  311. } else {
  312. klog.Debugf("[AttachGoTlsUprobes] STEP 12.4: Trying Swiss Tables field '%s.%s.%s' not found", sf.pkg, sf.structName, sf.field)
  313. }
  314. }
  315. // 如果还是找不到,尝试旧的 hmap 字段作为备选
  316. if !ok2 {
  317. klog.Infof("[AttachGoTlsUprobes] STEP 12.5: Trying alternative hmap field names")
  318. alternativeFields := []string{"table", "swiss", "swissTable", "buckets1", "oldbuckets", "bmap", "extra"}
  319. for _, fieldName := range alternativeFields {
  320. altOff, altOk := tracer.GetOffset(tracer.NewID("std", "runtime", "hmap", fieldName), path)
  321. if altOk {
  322. klog.Infof("[AttachGoTlsUprobes] STEP 12.6: Found alternative field '%s' with offset=%d", fieldName, altOff)
  323. bucketsOff = altOff
  324. ok2 = true
  325. break
  326. }
  327. }
  328. }
  329. if !ok2 {
  330. klog.Errorf("[AttachGoTlsUprobes] STEP 12.7: All attempts failed, Go 1.24+ Swiss Tables map structure not found")
  331. // 根据源码分析,maps.Map 结构体布局(64-bit):
  332. // - used uint64 (8 bytes, offset 0)
  333. // - seed uintptr (8 bytes, offset 8)
  334. // - dirPtr unsafe.Pointer (8 bytes, offset 16) <- 相当于旧的 buckets
  335. // 如果 DWARF 查找失败,使用硬编码的偏移量作为 fallback
  336. // 注意:这需要确认目标系统是 64-bit,且结构体对齐正确
  337. klog.Warnf("[AttachGoTlsUprobes] STEP 12.8: Using hardcoded offset for maps.Map.dirPtr (offset=16 on 64-bit)")
  338. klog.Warnf("[AttachGoTlsUprobes] STEP 12.9: This assumes: used(uint64@0) + seed(uintptr@8) + dirPtr(unsafe.Pointer@16)")
  339. // 检查 Go 版本是否 >= 1.24
  340. realVersion := strings.Replace(bi.GoVersion, "go", "", 1)
  341. parts := strings.Split(realVersion, ".")
  342. if len(parts) >= 2 {
  343. major, _ = strconv.Atoi(parts[0])
  344. minor, _ = strconv.Atoi(parts[1])
  345. if major > 1 || (major == 1 && minor >= 24) {
  346. // Go 1.24+ 使用 Swiss Tables,maps.Map.dirPtr 在 offset 16 (64-bit)
  347. // 假设是 64-bit 系统(大多数生产环境)
  348. bucketsOff = 16
  349. ok2 = true
  350. klog.Infof("[AttachGoTlsUprobes] STEP 12.10: Using hardcoded offset=%d for Go %s (Swiss Tables)", bucketsOff, bi.GoVersion)
  351. } else {
  352. klog.Errorf("[AttachGoTlsUprobes] STEP 12.11: Go version < 1.24 but buckets not found, this is unexpected")
  353. bucketsOff = 0
  354. }
  355. } else {
  356. klog.Errorf("[AttachGoTlsUprobes] STEP 12.12: Failed to parse Go version: %s", bi.GoVersion)
  357. bucketsOff = 0
  358. }
  359. }
  360. } else {
  361. klog.Infof("[AttachGoTlsUprobes] STEP 12.1: Successfully got buckets offset=%d", bucketsOff)
  362. }
  363. klog.Infof("[AttachGoTlsUprobes] STEP 13: Checking if both offsets are valid, goid_ok=%v, buckets_ok=%v", ok, ok2)
  364. // Go 1.24+ 兼容:如果 goid 成功但 buckets 失败,仍然继续(但记录警告)
  365. if ok {
  366. if !ok2 {
  367. klog.Warnf("[AttachGoTlsUprobes] STEP 13.0: buckets offset missing for Go 1.24+, but continuing with goid only")
  368. // 对于 Go 1.24,可能需要调整后续逻辑,暂时允许继续
  369. }
  370. klog.Infof("[AttachGoTlsUprobes] STEP 13.1: Both offsets valid, proceeding with version encoding")
  371. klog.Infof("[AttachGoTlsUprobes] STEP 14: Parsing Go version string")
  372. realVersion := strings.Replace(bi.GoVersion, "go", "", 1)
  373. klog.Infof("[AttachGoTlsUprobes] STEP 14.1: Real version string=%s", realVersion)
  374. parts := strings.Split(realVersion, ".")
  375. if len(parts) >= 2 {
  376. major, err = strconv.Atoi(parts[0])
  377. if err != nil {
  378. klog.Errorf("[AttachGoTlsUprobes] STEP 14.2: Error converting major version, error=%v", err)
  379. log("Error converting major version:", err)
  380. return nil, err
  381. }
  382. minor, err = strconv.Atoi(parts[1])
  383. if err != nil {
  384. klog.Errorf("[AttachGoTlsUprobes] STEP 14.3: Error converting minor version, error=%v", err)
  385. log("Error converting minor version:", err)
  386. return nil, err
  387. }
  388. if len(parts) >= 3 {
  389. revision, err = strconv.Atoi(parts[2])
  390. if err != nil {
  391. klog.Warnf("[AttachGoTlsUprobes] STEP 14.4: Error converting revision version, error=%v", err)
  392. log("Error converting revision version:", err)
  393. }
  394. }
  395. klog.Infof("[AttachGoTlsUprobes] STEP 14.5: Parsed version, major=%d, minor=%d, revision=%d", major, minor, revision)
  396. goVersion := ((major & 0xFF) << 16) + ((minor & 0xFF) << 8) + min(revision, 255)
  397. klog.Infof("[AttachGoTlsUprobes] STEP 14.6: Encoded version=%d (0x%x)", goVersion, goVersion)
  398. klog.Infof("[AttachGoTlsUprobes] STEP 15: Initializing EbpfProcInfo structure")
  399. info := EbpfProcInfo{}
  400. info.Version = uint32(goVersion)
  401. info.Offsets[OFFSET_IDX_GOID_RUNTIME_G] = uint16(offset)
  402. info.Offsets[OFFSET_IDX_P_GOIDCACHE] = uint16(goidcacheOffset)
  403. info.Offsets[OFFSET_IDX_P_RUNNEXT] = uint16(runnextOffset)
  404. info.NetTCPConnItab = uint64(0)
  405. info.CryptoTLSConnItab = uint64(0)
  406. info.CredentialsSyscallConnItab = uint64(0)
  407. info.InstanceId = instanceID
  408. info.AppId = appID
  409. info.CodeType = codeType
  410. if major == 1 && minor >= 24 {
  411. info.UseSwissMap = uint64(1)
  412. }
  413. if grpcMajorVersion >= 1 && grpcMinorVersion >= 60 {
  414. info.IsNewFramePos = 1
  415. klog.Infof("[AttachGoTlsUprobes] STEP 15.1: Using new frame position for gRPC >= 1.60")
  416. } else {
  417. info.IsNewFramePos = 0
  418. klog.Infof("[AttachGoTlsUprobes] STEP 15.2: Using old frame position for gRPC < 1.60")
  419. }
  420. // go
  421. info.BucketsPtrPos = bucketsOff
  422. if bucketsOff == 0 {
  423. klog.Warnf("[AttachGoTlsUprobes] STEP 15.3: BucketsPtrPos=0 (Go 1.24+ may not use buckets field)")
  424. } else {
  425. klog.Infof("[AttachGoTlsUprobes] STEP 15.3: Basic info initialized, BucketsPtrPos=%d", bucketsOff)
  426. }
  427. klog.Infof("[AttachGoTlsUprobes] STEP 16: Getting offsets for HTTP and gRPC fields")
  428. fields := map[*uint64]tracer.ID{
  429. &info.MethodPtrPos: tracer.NewID("std", "net/http", "Request", "Method"),
  430. &info.UrlPtrPos: tracer.NewID("std", "net/http", "Request", "URL"),
  431. &info.PathPtrPos: tracer.NewID("std", "net/url", "URL", "Path"),
  432. &info.StatusCodePos: tracer.NewID("std", "net/http", "response", "status"),
  433. &info.RequestHostPos: tracer.NewID("std", "net/http", "Request", "Host"),
  434. &info.ProtoPos: tracer.NewID("std", "net/http", "Request", "Proto"),
  435. &info.CtxPtrPos: tracer.NewID("std", "net/http", "Request", "ctx"),
  436. &info.HeadersPtrPos: tracer.NewID("std", "net/http", "Request", "Header"),
  437. &info.HttpClientNextidPos: tracer.NewID("google.golang.org/grpc", "google.golang.org/grpc/internal/transport", "http2Client", "nextID"),
  438. &info.StreamMethodPtrPos: tracer.NewID("google.golang.org/grpc", "google.golang.org/grpc/internal/transport", "Stream", "method"),
  439. &info.StreamCtxPos: tracer.NewID("google.golang.org/grpc", "google.golang.org/grpc/internal/transport", "Stream", "ctx"),
  440. }
  441. successCount := 0
  442. failCount := 0
  443. for field, id := range fields {
  444. off, ok := tracer.GetOffset(id, path)
  445. if !ok {
  446. klog.Warnf("[AttachGoTlsUprobes] STEP 16.1: Failed to get offset for ID: %v (PkgPath=%s, Struct=%s, Field=%s)", id, id.PkgPath, id.Struct, id.Field)
  447. failCount++
  448. } else {
  449. successCount++
  450. klog.Debugf("[AttachGoTlsUprobes] STEP 16.2: Got offset for %s.%s.%s = %d", id.PkgPath, id.Struct, id.Field, off)
  451. }
  452. *field = off
  453. }
  454. klog.Infof("[AttachGoTlsUprobes] STEP 16.3: Field offset collection completed, success=%d, failed=%d", successCount, failCount)
  455. klog.Infof("[AttachGoTlsUprobes] STEP 17: Allocating memory for process")
  456. // 获取内存地址
  457. if appInfo.GoProcCache.StartAddr == 0 && appInfo.GoProcCache.EndAddr == 0 {
  458. klog.Infof("[AttachGoTlsUprobes] STEP 17.1: Cache empty, calling Allocate")
  459. allocDetails, allocErr := tracer.Allocate(int(pid))
  460. if allocErr != nil {
  461. klog.Errorf("[AttachGoTlsUprobes] STEP 17.2: Allocate failed, pid=%d, error=%v", pid, allocErr)
  462. return nil, allocErr
  463. }
  464. if allocDetails != nil {
  465. appInfo.GoProcCache.StartAddr = allocDetails.StartAddr
  466. appInfo.GoProcCache.EndAddr = allocDetails.EndAddr
  467. klog.Infof("[AttachGoTlsUprobes] STEP 17.3: Allocate succeeded, StartAddr=0x%x, EndAddr=0x%x", allocDetails.StartAddr, allocDetails.EndAddr)
  468. } else {
  469. klog.Warnf("[AttachGoTlsUprobes] STEP 17.4: Allocate returned nil")
  470. }
  471. } else {
  472. klog.Infof("[AttachGoTlsUprobes] STEP 17.5: Using cached addresses, StartAddr=0x%x, EndAddr=0x%x", appInfo.GoProcCache.StartAddr, appInfo.GoProcCache.EndAddr)
  473. }
  474. info.StartAddr = appInfo.GoProcCache.StartAddr
  475. info.EndAddr = appInfo.GoProcCache.EndAddr
  476. klog.Debugln("Major:", major)
  477. klog.Debugln("Minor:", minor)
  478. klog.Debugln("Revision:", revision)
  479. klog.Debugln("goVersion", goVersion)
  480. klog.WithField("pid", pid).Debugln("info.StartAddr", info.StartAddr)
  481. klog.WithField("pid", pid).Debugln("info.EndAddr", info.EndAddr)
  482. klog.Infof("[AttachGoTlsUprobes] STEP 18: Updating proc_info map")
  483. _, err = tracer.UpdateProcInfoToMap(t.collection, pid, info)
  484. if err != nil {
  485. klog.Errorf("[AttachGoTlsUprobes] STEP 18.1: Failed to update proc_info map, pid=%d, error=%v", pid, err)
  486. klog.Error("failed to update program info", err)
  487. return nil, err
  488. }
  489. klog.Infof("[AttachGoTlsUprobes] STEP 18.2: Proc_info map updated successfully")
  490. appInfo.EBPFProcInfo = &info
  491. } else {
  492. klog.Errorf("[AttachGoTlsUprobes] STEP 13.2: Skipping proc_info initialization due to missing offsets, goid_ok=%v, buckets_ok=%v", ok, ok2)
  493. if !ok {
  494. klog.Errorf("[AttachGoTlsUprobes] STEP 13.3: runtime.g.goid offset missing - this is critical!")
  495. }
  496. if !ok2 {
  497. klog.Errorf("[AttachGoTlsUprobes] STEP 13.4: runtime.hmap.buckets offset missing - Go 1.24+ may use new map implementation")
  498. }
  499. }
  500. }
  501. klog.Infof("[AttachGoTlsUprobes] STEP 19: Starting symbol matching and uprobe attachment, total symbols=%d", len(symbols))
  502. var links []link.Link
  503. matchedSymbols := 0
  504. for i, s := range symbols {
  505. if elf.ST_TYPE(s.Info) != elf.STT_FUNC || s.Size == 0 {
  506. continue
  507. }
  508. switch s.Name {
  509. case goTlsWriteSymbol, goTlsReadSymbol:
  510. matchedSymbols++
  511. klog.Infof("[AttachGoTlsUprobes] STEP 19.1: Matched TLS symbol: %s (index=%d)", s.Name, i)
  512. case goExecute:
  513. matchedSymbols++
  514. klog.Infof("[AttachGoTlsUprobes] STEP 19.2: Matched runtime.execute symbol (index=%d)", i)
  515. case goNewproc1:
  516. matchedSymbols++
  517. klog.Infof("[AttachGoTlsUprobes] STEP 19.3: Matched runtime.newproc1 symbol (index=%d)", i)
  518. case goRunqget:
  519. matchedSymbols++
  520. klog.Infof("[AttachGoTlsUprobes] STEP 19.4: Matched runtime.runqget symbol (index=%d)", i)
  521. case goServeHTTP:
  522. matchedSymbols++
  523. klog.Infof("[AttachGoTlsUprobes] STEP 19.6: Matched net/http.serverHandler.ServeHTTP symbol (index=%d)", i)
  524. case goTransport:
  525. matchedSymbols++
  526. klog.Infof("[AttachGoTlsUprobes] STEP 19.7: Matched net/http.Transport.roundTrip symbol (index=%d)", i)
  527. case goGrpcClientConnInvoke:
  528. matchedSymbols++
  529. klog.Infof("[AttachGoTlsUprobes] STEP 19.8: Matched gRPC ClientConn.Invoke symbol (index=%d)", i)
  530. case goGrpcHttp2OperateHeader, goGrpcServerHandleStream, goGrpcServerWritestatus, goGrpcClientLoopyHeaderHandler, goGrpcHttp2ClientNewStream:
  531. matchedSymbols++
  532. klog.Infof("[AttachGoTlsUprobes] STEP 19.9: Matched gRPC symbol: %s (index=%d)", s.Name, i)
  533. case goGocqlSessionExecuteQuery:
  534. matchedSymbols++
  535. klog.Infof("[AttachGoTlsUprobes] STEP 19.10: Matched gocql Session.executeQuery symbol (index=%d)", i)
  536. case goReadContinuedLineSlice:
  537. default:
  538. continue
  539. }
  540. klog.Debugf("[AttachGoTlsUprobes] STEP 19.9: Processing symbol %s, Value=0x%x, Size=%d", s.Name, s.Value, s.Size)
  541. address := s.Value
  542. for _, p := range ef.Progs {
  543. if p.Type != elf.PT_LOAD || (p.Flags&elf.PF_X) == 0 {
  544. continue
  545. }
  546. if p.Vaddr <= s.Value && s.Value < (p.Vaddr+p.Memsz) {
  547. address = s.Value - p.Vaddr + p.Off
  548. break
  549. }
  550. }
  551. //fmt.Println("s.Name-----:", s.Name)
  552. switch s.Name {
  553. case goExecute:
  554. klog.Infof("[AttachGoTlsUprobes] STEP 20: Attaching uprobe for runtime.execute, address=0x%x", address)
  555. l, err := attachUprobe(exe, s.Name, "runtime_execute", t.uprobes, address, "failed to attach write_enter uprobe", true)
  556. if err != nil {
  557. klog.Infoln("runtime.execute no")
  558. return nil, err
  559. }
  560. klog.Infof("[AttachGoTlsUprobes] STEP 20.2: Successfully attached runtime.execute uprobe")
  561. klog.Infoln("runtime.execute ok")
  562. links = append(links, l)
  563. case goNewproc1:
  564. klog.Infof("[AttachGoTlsUprobes] STEP 21: Attaching uprobe for runtime.newproc1, address=0x%x", address)
  565. retLinks, err := attachUprobeWithReturns(exe, s.Name, "enter_runtime_newproc1", "exit_runtime_newproc1", t.uprobes, address, s, textSection, textSectionLen, textSectionData, ef.Machine, "failed to attach newproc1 uprobe", true)
  566. if err != nil {
  567. return nil, err
  568. }
  569. links = append(links, retLinks...)
  570. klog.Infof("[AttachGoTlsUprobes] STEP 21.2: Successfully attached enter_runtime_newproc1 uprobe")
  571. case goRunqget:
  572. l, err := attachUprobe(exe, s.Name, "enter_runtime_runqget", t.uprobes, address, "failed to attach goRunqget uprobe", true)
  573. if err != nil {
  574. return nil, err
  575. }
  576. links = append(links, l)
  577. //case goGoready:
  578. //klog.Infof("[AttachGoTlsUprobes] STEP 22: Attaching uprobe for runtime.goready, address=0x%x", address)
  579. //l, err := attachUprobe(exe, s.Name, "runtime_goready", t.uprobes, address, "failed to attach runtime.goready uprobe", true)
  580. //if err != nil {
  581. // klog.Infoln("runtime.goready no")
  582. // return nil, err
  583. //}
  584. //klog.Infof("[AttachGoTlsUprobes] STEP 22.2: Successfully attached runtime.goready uprobe")
  585. //klog.Infoln("runtime.goready ok")
  586. //links = append(links, l)
  587. case goGrpcClientConnInvoke:
  588. retLinks, err := attachUprobeWithReturns(exe, s.Name, "uprobe_ClientConn_Invoke", "uprobe_ClientConn_Invoke_Returns", t.uprobes, address, s, textSection, textSectionLen, textSectionData, ef.Machine, "failed to attach uprobe_ClientConn_Invoke uprobe", true)
  589. if err != nil {
  590. return nil, err
  591. }
  592. if retLinks != nil {
  593. klog.Infoln("uprobe_ClientConn_Invoke ok")
  594. links = append(links, retLinks...)
  595. }
  596. case goGrpcClientLoopyHeaderHandler:
  597. l, err := attachUprobe(exe, s.Name, "uprobe_LoopyWriter_HeaderHandler", t.uprobes, address, "failed to attach uprobe_LoopyWriter_HeaderHandler uprobe", false)
  598. if err == nil && l != nil {
  599. klog.Infoln("uprobe_LoopyWriter_HeaderHandler ok")
  600. links = append(links, l)
  601. }
  602. case goGrpcHttp2ClientNewStream:
  603. l, err := attachUprobe(exe, s.Name, "uprobe_http2Client_NewStream", t.uprobes, address, "failed to attach uprobe_http2Client_NewStream uprobe", false)
  604. if err == nil && l != nil {
  605. klog.Infoln("uprobe_http2Client_NewStream ok")
  606. links = append(links, l)
  607. }
  608. case goGrpcHttp2OperateHeader:
  609. l, err := attachUprobe(exe, s.Name, "uprobe_http2Server_operateHeader", t.uprobes, address, "failed to attach uprobe_http2Server_operateHeader uprobe", false)
  610. if err == nil && l != nil {
  611. klog.Infoln("uprobe_http2Server_operateHeader ok")
  612. links = append(links, l)
  613. }
  614. // case goGrpcServerWritestatus:
  615. // // 根据 gRPC 版本选择相应的 WriteStatus 探针
  616. // l, err := exe.Uprobe(s.Name, t.uprobes["uprobe_http2Server_WriteStatus"], &link.UprobeOptions{Address: address})
  617. // if err != nil {
  618. // klog.WithError(err).Errorf("failed to attach uprobe_http2Server_WriteStatus uprobe")
  619. // continue
  620. // }
  621. // links = append(links, l)
  622. case goGrpcServerHandleStream:
  623. probeName := t.selectGRPCServerProbe(grpcMajorVersion, grpcMinorVersion)
  624. retLinks, err := attachUprobeWithReturns(exe, s.Name, probeName, "uprobe_server_handleStream_Returns", t.uprobes, address, s, textSection, textSectionLen, textSectionData, ef.Machine, fmt.Sprintf("failed to attach %s uprobe", probeName), true)
  625. if err != nil {
  626. return nil, err
  627. }
  628. if retLinks != nil {
  629. klog.Infof("%s ok (gRPC v%d.%d)", probeName, grpcMajorVersion, grpcMinorVersion)
  630. klog.Infoln("google.golang.org/grpc.(*Server).handleStream ok----")
  631. links = append(links, retLinks...)
  632. }
  633. case goServeHTTP:
  634. retLinks, err := attachUprobeWithReturns(exe, s.Name, "uprobe_HandlerFunc_ServeHTTP", "uprobe_HandlerFunc_ServeHTTP_Returns", t.uprobes, address, s, textSection, textSectionLen, textSectionData, ef.Machine, "failed to attach uprobe_HandlerFunc_ServeHTTP uprobe", true)
  635. if err != nil {
  636. return nil, err
  637. }
  638. if retLinks != nil {
  639. klog.Infoln("net/http.serverHandler.ServeHTTP ok")
  640. links = append(links, retLinks...)
  641. }
  642. case goTransport:
  643. if t.DisableE2ETracing() {
  644. continue
  645. }
  646. retLinks, err := attachUprobeWithReturns(exe, s.Name, "uprobe_Transport_roundTrip", "uprobe_Transport_roundTrip_Returns", t.uprobes, address, s, textSection, textSectionLen, textSectionData, ef.Machine, "failed to attach write_enter uprobe", true)
  647. if err != nil {
  648. return nil, err
  649. }
  650. if retLinks != nil {
  651. klog.Infoln("net/http.uprobe_Transport_roundTrip ok")
  652. links = append(links, retLinks...)
  653. }
  654. case goTlsWriteSymbol:
  655. klog.Infoln("fucktls goTlsWriteSymbol crypto/tls uprobes attached")
  656. l, err := attachUprobe(exe, s.Name, "go_crypto_tls_write_enter", t.uprobes, address, "failed to attach write_enter uprobe", true)
  657. if err != nil {
  658. return nil, err
  659. }
  660. links = append(links, l)
  661. case goTlsReadSymbol:
  662. klog.Infoln("fucktls goTlsReadSymbol crypto/tls uprobes attached")
  663. retLinks, err := attachUprobeWithReturns(exe, s.Name, "go_crypto_tls_read_enter", "go_crypto_tls_read_exit", t.uprobes, address, s, textSection, textSectionLen, textSectionData, ef.Machine, "failed to attach read_enter uprobe", true)
  664. if err != nil {
  665. return nil, err
  666. }
  667. if retLinks != nil {
  668. links = append(links, retLinks...)
  669. }
  670. case goReadContinuedLineSlice:
  671. if major == 1 && minor >= 24 {
  672. retLinks, err := attachUprobeWithReturns(exe, s.Name, "", "uprobe_textproto_Reader_readContinuedLineSlice_Returns", t.uprobes, address, s, textSection, textSectionLen, textSectionData, ef.Machine, "failed to attach read_exit uprobe", true)
  673. if err != nil {
  674. return nil, err
  675. }
  676. if retLinks != nil {
  677. links = append(links, retLinks...)
  678. }
  679. }
  680. case goGocqlSessionExecuteQuery:
  681. retLinks, err := attachUprobeWithReturns(exe, s.Name, "uprobe_Session_executeQuery", "uprobe_Session_executeQuery_Returns", t.uprobes, address, s, textSection, textSectionLen, textSectionData, ef.Machine, "failed to attach uprobe_Session_executeQuery uprobe", true)
  682. if err != nil {
  683. return nil, err
  684. }
  685. if retLinks != nil {
  686. klog.Infoln("uprobe_Session_executeQuery ok")
  687. links = append(links, retLinks...)
  688. }
  689. }
  690. }
  691. klog.Infof("[AttachGoTlsUprobes] STEP 22: Symbol processing completed, matched symbols=%d, total links=%d", matchedSymbols, len(links))
  692. if len(links) == 0 {
  693. klog.Errorf("[AttachGoTlsUprobes] STEP 22.1: No uprobes attached, returning error")
  694. return nil, err
  695. }
  696. klog.Infof("[AttachGoTlsUprobes] STEP 23: Function completed successfully, attached %d uprobes", len(links))
  697. klog.Infoln("crypto/tls uprobes attached")
  698. return links, nil
  699. }
  700. func getSslLibPathAndVersion(pid uint32) (string, string) {
  701. f, err := os.Open(proc.Path(pid, "maps"))
  702. if err != nil {
  703. return "", ""
  704. }
  705. defer f.Close()
  706. scanner := bufio.NewScanner(f)
  707. scanner.Split(bufio.ScanLines)
  708. var libsslPath, libcryptoPath string
  709. for scanner.Scan() {
  710. parts := strings.Fields(scanner.Text())
  711. if len(parts) <= 5 {
  712. continue
  713. }
  714. libPath := parts[5]
  715. switch {
  716. case libsslPath == "" && strings.Contains(libPath, "libssl.so"):
  717. fullPath := proc.Path(pid, "root", libPath)
  718. if _, err = os.Stat(fullPath); err == nil {
  719. libsslPath = fullPath
  720. }
  721. case libcryptoPath == "" && strings.Contains(libPath, "libcrypto.so"):
  722. fullPath := proc.Path(pid, "root", libPath)
  723. if _, err = os.Stat(fullPath); err == nil {
  724. libcryptoPath = fullPath
  725. }
  726. default:
  727. continue
  728. }
  729. if libsslPath != "" && libcryptoPath != "" {
  730. break
  731. }
  732. }
  733. if libsslPath == "" || libcryptoPath == "" {
  734. return "", ""
  735. }
  736. ef, err := elf.Open(libcryptoPath)
  737. if err != nil {
  738. return "", ""
  739. }
  740. defer ef.Close()
  741. rodataSection := ef.Section(".rodata")
  742. if rodataSection == nil {
  743. return "", ""
  744. }
  745. rodataSectionData, err := rodataSection.Data()
  746. if err != nil {
  747. return "", ""
  748. }
  749. var version string
  750. for _, b := range bytes.Split(rodataSectionData, []byte("\x00")) {
  751. if len(b) == 0 {
  752. continue
  753. }
  754. s := string(b)
  755. if !strings.HasPrefix(s, "OpenSSL") {
  756. continue
  757. }
  758. if m := opensslVersionRe.FindStringSubmatch(s); len(m) > 1 {
  759. version = m[1]
  760. }
  761. }
  762. return libsslPath, "v" + version
  763. }
  764. // selectGRPCServerProbe 根据 gRPC 版本选择服务端探针
  765. func (t *Tracer) selectGRPCServerProbe(major, minor int) string {
  766. // 根据 gRPC 版本选择相应的探针
  767. if major == 1 && minor >= 69 {
  768. // 现代版本 (>= 1.69.0) 使用新的探针
  769. klog.Infof("Selecting modern gRPC server probe for version %d.%d", major, minor)
  770. return "uprobe_server_handleStream2"
  771. } else {
  772. // 传统版本 (< 1.69.0) 使用旧的探针
  773. klog.Infof("Selecting legacy gRPC server probe for version %d.%d", major, minor)
  774. return "uprobe_server_handleStream"
  775. }
  776. }
  777. // attachUprobe 附加单个 uprobe,处理错误
  778. func attachUprobe(exe *link.Executable, symbolName string, probeName string, uprobes map[string]*ebpf.Program, address uint64, onError string, returnOnError bool) (link.Link, error) {
  779. l, err := exe.Uprobe(symbolName, uprobes[probeName], &link.UprobeOptions{Address: address})
  780. if err != nil {
  781. if returnOnError {
  782. klog.WithError(err).Errorf("failed to attach %s uprobe: %s", probeName, onError)
  783. return nil, err
  784. } else {
  785. klog.WithError(err).Errorf("failed to attach %s uprobe: %s", probeName, onError)
  786. return nil, nil
  787. }
  788. }
  789. return l, nil
  790. }
  791. // attachUprobeWithReturns 附加 uprobe 并附加返回探针
  792. // enterProbeName 为空字符串时,只附加返回探针
  793. func attachUprobeWithReturns(exe *link.Executable, symbolName string, enterProbeName, returnProbeName string, uprobes map[string]*ebpf.Program, address uint64, s elf.Symbol, textSection *elf.Section, textSectionLen uint64, textSectionData []byte, machine elf.Machine, onError string, returnOnError bool) ([]link.Link, error) {
  794. var links []link.Link
  795. // 附加入口探针(如果提供了入口探针名称)
  796. if enterProbeName != "" {
  797. l, err := attachUprobe(exe, symbolName, enterProbeName, uprobes, address, onError, returnOnError)
  798. if err != nil {
  799. return nil, err
  800. }
  801. if l == nil {
  802. return nil, nil
  803. }
  804. links = append(links, l)
  805. }
  806. // 计算符号在 text section 中的位置
  807. sStart := s.Value - textSection.Addr
  808. sEnd := sStart + s.Size
  809. if sEnd > textSectionLen {
  810. return links, nil
  811. }
  812. // 读取符号字节码
  813. sBytes := textSectionData[sStart:sEnd]
  814. returnOffsets := getReturnOffsets(machine, sBytes)
  815. if len(returnOffsets) == 0 {
  816. if returnOnError {
  817. err := fmt.Errorf("failed to attach %s: no return offsets found", returnProbeName)
  818. klog.Errorln(err)
  819. return nil, err
  820. }
  821. return links, nil
  822. }
  823. // 为每个返回点附加探针
  824. for _, offset := range returnOffsets {
  825. l, err := exe.Uprobe(symbolName, uprobes[returnProbeName], &link.UprobeOptions{Address: address, Offset: uint64(offset)})
  826. if err != nil {
  827. if returnOnError {
  828. klog.WithError(err).Errorf("failed to attach %s uprobe", returnProbeName)
  829. return nil, err
  830. }
  831. continue
  832. }
  833. links = append(links, l)
  834. }
  835. return links, nil
  836. }
  837. func getReturnOffsets(machine elf.Machine, instructions []byte) []int {
  838. var res []int
  839. switch machine {
  840. case elf.EM_X86_64:
  841. for i := 0; i < len(instructions); {
  842. ins, err := x86asm.Decode(instructions[i:], 64)
  843. if err == nil && ins.Op == x86asm.RET {
  844. res = append(res, i)
  845. }
  846. i += ins.Len
  847. }
  848. case elf.EM_AARCH64:
  849. for i := 0; i < len(instructions); {
  850. ins, err := arm64asm.Decode(instructions[i:])
  851. if err == nil && ins.Op == arm64asm.RET {
  852. res = append(res, i)
  853. }
  854. i += 4
  855. }
  856. }
  857. return res
  858. }
  859. func min(a, b int) int {
  860. if a < b {
  861. return a
  862. }
  863. return b
  864. }