tls.go 36 KB

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