tls.go 37 KB

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