tls.go 38 KB

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