tls.go 36 KB

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