tls.go 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013
  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. // 构建 sysvc 值:{app_name_len}:app_name:{appServiceType_len}:appServiceType:{SysTagLen}[:SysTag]
  476. // appServiceType 固定为 "APPLICATION"
  477. appName := appInfo.AppName
  478. nodeInfo := NODE_INFO.GetNodeInfo()
  479. sysTag := ""
  480. if nodeInfo != nil {
  481. sysTag = nodeInfo.SysTag
  482. }
  483. appServiceType := "APPLICATION"
  484. appNameLen := len(appName)
  485. appServiceTypeLen := len(appServiceType)
  486. sysTagLen := len(sysTag)
  487. // 限制长度,避免超出数组大小
  488. if appNameLen > 32 {
  489. appNameLen = 32
  490. appName = appName[:32]
  491. }
  492. if sysTagLen > 32 {
  493. sysTagLen = 32
  494. sysTag = sysTag[:32]
  495. }
  496. // 格式:{app_name_len}:app_name:{appServiceType_len}:appServiceType[:{SysTagLen}:SysTag]
  497. // 如果 sysTag 为空,则为 {app_name_len}:app_name:{appServiceType_len}:appServiceType
  498. // 如果 sysTag 不为空,则为 {app_name_len}:app_name:{appServiceType_len}:appServiceType:{SysTagLen}:SysTag
  499. // 长度不足2位时前面补0,例如:08:service:12:APPLICATION 或 08:service:12:APPLICATION:03:tag
  500. var sysvcStr string
  501. if sysTagLen == 0 {
  502. sysvcStr = fmt.Sprintf("%02d:%s:%02d:%s", appNameLen, appName, appServiceTypeLen, appServiceType)
  503. } else {
  504. sysvcStr = fmt.Sprintf("%02d:%s:%02d:%s:%02d:%s", appNameLen, appName, appServiceTypeLen, appServiceType, sysTagLen, sysTag)
  505. }
  506. // 复制到字节数组,确保不超过 76 字节
  507. sysvcBytes := []byte(sysvcStr)
  508. if len(sysvcBytes) > 76 {
  509. sysvcBytes = sysvcBytes[:76]
  510. }
  511. copy(info.Sysvc[:], sysvcBytes)
  512. klog.Debugf("[AttachGoTlsUprobes] Sysvc constructed: %s", sysvcStr)
  513. klog.Infof("[AttachGoTlsUprobes] Updating proc_info map")
  514. _, err = tracer.UpdateProcInfoToMap(t.collection, pid, info)
  515. if err != nil {
  516. klog.Error("failed to update program info", err)
  517. return nil, err
  518. }
  519. klog.Infof("[AttachGoTlsUprobes] Proc_info map updated successfully")
  520. appInfo.EBPFProcInfo = &info
  521. } else {
  522. klog.Errorf("[AttachGoTlsUprobes] Skipping proc_info initialization due to missing offsets, goid_ok=%v, buckets_ok=%v", ok, ok2)
  523. if !ok {
  524. klog.Errorf("[AttachGoTlsUprobes] runtime.g.goid offset missing - this is critical!")
  525. }
  526. if !ok2 {
  527. klog.Errorf("[AttachGoTlsUprobes] runtime.hmap.buckets offset missing - Go 1.24+ may use new map implementation")
  528. }
  529. }
  530. }
  531. klog.Infof("[AttachGoTlsUprobes] Starting symbol matching and uprobe attachment, total symbols=%d", len(symbols))
  532. var links []link.Link
  533. matchedSymbols := 0
  534. for i, s := range symbols {
  535. if elf.ST_TYPE(s.Info) != elf.STT_FUNC || s.Size == 0 {
  536. continue
  537. }
  538. switch s.Name {
  539. case goTlsWriteSymbol, goTlsReadSymbol:
  540. matchedSymbols++
  541. klog.Infof("[AttachGoTlsUprobes] STEP 19.1: Matched TLS symbol: %s (index=%d)", s.Name, i)
  542. case goExecute:
  543. matchedSymbols++
  544. klog.Infof("[AttachGoTlsUprobes] STEP 19.2: Matched runtime.execute symbol (index=%d)", i)
  545. case goNewproc1:
  546. matchedSymbols++
  547. klog.Infof("[AttachGoTlsUprobes] STEP 19.3: Matched runtime.newproc1 symbol (index=%d)", i)
  548. case goRunqget:
  549. matchedSymbols++
  550. klog.Infof("[AttachGoTlsUprobes] STEP 19.4: Matched runtime.runqget symbol (index=%d)", i)
  551. case goServeHTTP:
  552. matchedSymbols++
  553. klog.Infof("[AttachGoTlsUprobes] STEP 19.6: Matched net/http.serverHandler.ServeHTTP symbol (index=%d)", i)
  554. case goTransport, goHeaderWriteSubset:
  555. matchedSymbols++
  556. klog.Infof("[AttachGoTlsUprobes] STEP 19.7: Matched net/http.Transport.roundTrip writeSubset symbol (index=%d)", i)
  557. case goGrpcClientConnInvoke:
  558. matchedSymbols++
  559. klog.Infof("[AttachGoTlsUprobes] STEP 19.8: Matched gRPC ClientConn.Invoke symbol (index=%d)", i)
  560. case goGrpcHttp2OperateHeader, goGrpcServerHandleStream, goGrpcServerWritestatus, goGrpcClientLoopyHeaderHandler, goGrpcHttp2ClientNewStream:
  561. matchedSymbols++
  562. klog.Infof("[AttachGoTlsUprobes] STEP 19.9: Matched gRPC symbol: %s (index=%d)", s.Name, i)
  563. case goGocqlSessionExecuteQuery:
  564. matchedSymbols++
  565. klog.Infof("[AttachGoTlsUprobes] STEP 19.10: Matched gocql Session.executeQuery symbol (index=%d)", i)
  566. case goGocqlSessionExecuteQueryV2:
  567. matchedSymbols++
  568. klog.Infof("[AttachGoTlsUprobes] STEP 19.11: Matched cassandra Session.executeQuery symbol (index=%d)", i)
  569. case goKafkaWriterWriteMessages:
  570. matchedSymbols++
  571. klog.Infof("[AttachGoTlsUprobes] STEP 19.13: Matched kafka Writer.WriteMessages symbol (index=%d)", i)
  572. case goKafkaReaderFetchMessage:
  573. matchedSymbols++
  574. klog.Infof("[AttachGoTlsUprobes] STEP 19.14: Matched kafka Reader.FetchMessage symbol (index=%d)", i)
  575. case goReadContinuedLineSlice:
  576. default:
  577. continue
  578. }
  579. klog.Debugf("[AttachGoTlsUprobes] Processing symbol %s, Value=0x%x, Size=%d", s.Name, s.Value, s.Size)
  580. address := s.Value
  581. for _, p := range ef.Progs {
  582. if p.Type != elf.PT_LOAD || (p.Flags&elf.PF_X) == 0 {
  583. continue
  584. }
  585. if p.Vaddr <= s.Value && s.Value < (p.Vaddr+p.Memsz) {
  586. address = s.Value - p.Vaddr + p.Off
  587. break
  588. }
  589. }
  590. //fmt.Println("s.Name-----:", s.Name)
  591. switch s.Name {
  592. case goExecute:
  593. klog.Infof("[AttachGoTlsUprobes] STEP 20: Attaching uprobe for runtime.execute, address=0x%x", address)
  594. l, err := attachUprobe(exe, s.Name, "runtime_execute", t.uprobes, address, "failed to attach write_enter uprobe", true)
  595. if err != nil {
  596. klog.Infoln("runtime.execute no")
  597. return nil, err
  598. }
  599. klog.Infof("[AttachGoTlsUprobes] STEP 20.2: Successfully attached runtime.execute uprobe")
  600. klog.Infoln("runtime.execute ok")
  601. links = append(links, l)
  602. case goNewproc1:
  603. klog.Infof("[AttachGoTlsUprobes] STEP 21: Attaching uprobe for runtime.newproc1, address=0x%x", address)
  604. 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)
  605. if err != nil {
  606. log("failed to attach newproc1 uprobe", err)
  607. return nil, err
  608. }
  609. links = append(links, retLinks...)
  610. klog.Infof("[AttachGoTlsUprobes] STEP 21.2: Successfully attached enter_runtime_newproc1 uprobe")
  611. case goRunqget:
  612. l, err := attachUprobe(exe, s.Name, "enter_runtime_runqget", t.uprobes, address, "failed to attach goRunqget uprobe", true)
  613. if err != nil {
  614. log("failed to attach goRunqget uprobe", err)
  615. return nil, err
  616. }
  617. links = append(links, l)
  618. //case goGoready:
  619. //klog.Infof("[AttachGoTlsUprobes] STEP 22: Attaching uprobe for runtime.goready, address=0x%x", address)
  620. //l, err := attachUprobe(exe, s.Name, "runtime_goready", t.uprobes, address, "failed to attach runtime.goready uprobe", true)
  621. //if err != nil {
  622. // klog.Infoln("runtime.goready no")
  623. // return nil, err
  624. //}
  625. //klog.Infof("[AttachGoTlsUprobes] STEP 22.2: Successfully attached runtime.goready uprobe")
  626. //klog.Infoln("runtime.goready ok")
  627. //links = append(links, l)
  628. case goGrpcClientConnInvoke:
  629. 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)
  630. if err != nil {
  631. return nil, err
  632. }
  633. if retLinks != nil {
  634. klog.Infoln("uprobe_ClientConn_Invoke ok")
  635. links = append(links, retLinks...)
  636. }
  637. case goGrpcClientLoopyHeaderHandler:
  638. l, err := attachUprobe(exe, s.Name, "uprobe_LoopyWriter_HeaderHandler", t.uprobes, address, "failed to attach uprobe_LoopyWriter_HeaderHandler uprobe", false)
  639. if err == nil && l != nil {
  640. klog.Infoln("uprobe_LoopyWriter_HeaderHandler ok")
  641. links = append(links, l)
  642. }
  643. case goGrpcHttp2ClientNewStream:
  644. l, err := attachUprobe(exe, s.Name, "uprobe_http2Client_NewStream", t.uprobes, address, "failed to attach uprobe_http2Client_NewStream uprobe", false)
  645. if err == nil && l != nil {
  646. klog.Infoln("uprobe_http2Client_NewStream ok")
  647. links = append(links, l)
  648. }
  649. case goGrpcHttp2OperateHeader:
  650. l, err := attachUprobe(exe, s.Name, "uprobe_http2Server_operateHeader", t.uprobes, address, "failed to attach uprobe_http2Server_operateHeader uprobe", false)
  651. if err == nil && l != nil {
  652. klog.Infoln("uprobe_http2Server_operateHeader ok")
  653. links = append(links, l)
  654. }
  655. // case goGrpcServerWritestatus:
  656. // // 根据 gRPC 版本选择相应的 WriteStatus 探针
  657. // l, err := exe.Uprobe(s.Name, t.uprobes["uprobe_http2Server_WriteStatus"], &link.UprobeOptions{Address: address})
  658. // if err != nil {
  659. // klog.WithError(err).Errorf("failed to attach uprobe_http2Server_WriteStatus uprobe")
  660. // continue
  661. // }
  662. // links = append(links, l)
  663. case goGrpcServerHandleStream:
  664. // 根据 gRPC 版本选择相应的探针
  665. probeName := t.selectGRPCServerProbe(grpcMajorVersion, grpcMinorVersion)
  666. 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)
  667. if err != nil {
  668. return nil, err
  669. }
  670. if retLinks != nil {
  671. klog.Infof("%s ok (gRPC v%d.%d)", probeName, grpcMajorVersion, grpcMinorVersion)
  672. klog.Infoln("google.golang.org/grpc.(*Server).handleStream ok----")
  673. links = append(links, retLinks...)
  674. }
  675. case goServeHTTP:
  676. 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)
  677. if err != nil {
  678. return nil, err
  679. }
  680. if retLinks != nil {
  681. klog.Infoln("net/http.serverHandler.ServeHTTP ok")
  682. links = append(links, retLinks...)
  683. }
  684. case goTransport:
  685. if t.DisableE2ETracing() {
  686. continue
  687. }
  688. 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)
  689. if err != nil {
  690. return nil, err
  691. }
  692. if retLinks != nil {
  693. klog.Infoln("net/http.uprobe_Transport_roundTrip ok")
  694. links = append(links, retLinks...)
  695. }
  696. case goHeaderWriteSubset:
  697. if t.DisableE2ETracing() {
  698. continue
  699. }
  700. l, err := attachUprobe(exe, s.Name, "uprobe_writeSubset", t.uprobes, address, "failed to attach write_enter uprobe", true)
  701. if err != nil {
  702. klog.WithError(err).Errorln("failed to attach uprobe_writeSubset")
  703. return nil, err
  704. }
  705. klog.Infoln("net/http.Header.writeSubset ok")
  706. links = append(links, l)
  707. case goTlsWriteSymbol:
  708. klog.Infoln("fucktls goTlsWriteSymbol crypto/tls uprobes attached")
  709. l, err := attachUprobe(exe, s.Name, "go_crypto_tls_write_enter", t.uprobes, address, "failed to attach write_enter uprobe", true)
  710. if err != nil {
  711. klog.WithError(err).Errorln("failed to attach write_enter uprobe")
  712. return nil, err
  713. }
  714. links = append(links, l)
  715. case goTlsReadSymbol:
  716. klog.Infoln("fucktls goTlsReadSymbol crypto/tls uprobes attached")
  717. 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)
  718. if err != nil {
  719. klog.WithError(err).Errorln("failed to attach read_enter uprobe")
  720. return nil, err
  721. }
  722. if retLinks != nil {
  723. links = append(links, retLinks...)
  724. }
  725. case goReadContinuedLineSlice:
  726. if major == 1 && minor >= 24 {
  727. 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)
  728. if err != nil {
  729. return nil, err
  730. }
  731. if retLinks != nil {
  732. links = append(links, retLinks...)
  733. }
  734. }
  735. case goGocqlSessionExecuteQuery:
  736. 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)
  737. if err != nil {
  738. return nil, err
  739. }
  740. if retLinks != nil {
  741. klog.Infoln("uprobe_Session_executeQuery ok")
  742. links = append(links, retLinks...)
  743. }
  744. case goGocqlSessionExecuteQueryV2:
  745. 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)
  746. if err != nil {
  747. return nil, err
  748. }
  749. if retLinks != nil {
  750. klog.Infoln("uprobe_Session_executeQuery_cassandra ok")
  751. links = append(links, retLinks...)
  752. }
  753. case goKafkaWriterWriteMessages:
  754. 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)
  755. if err != nil {
  756. return nil, err
  757. }
  758. if retLinks != nil {
  759. klog.Infoln("uprobe_WriteMessages ok")
  760. links = append(links, retLinks...)
  761. }
  762. case goKafkaReaderFetchMessage:
  763. 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)
  764. if err != nil {
  765. return nil, err
  766. }
  767. if retLinks != nil {
  768. klog.Infoln("uprobe_FetchMessage ok")
  769. links = append(links, retLinks...)
  770. }
  771. }
  772. }
  773. klog.Infof("[AttachGoTlsUprobes] Symbol processing completed, matched symbols=%d, total links=%d", matchedSymbols, len(links))
  774. if len(links) == 0 {
  775. klog.Errorf("[AttachGoTlsUprobes] No uprobes attached, returning error")
  776. return nil, err
  777. }
  778. klog.Infof("[AttachGoTlsUprobes] Function completed successfully, attached %d uprobes", len(links))
  779. klog.Infoln("crypto/tls uprobes attached")
  780. return links, nil
  781. }
  782. func getSslLibPathAndVersion(pid uint32) (string, string) {
  783. f, err := os.Open(proc.Path(pid, "maps"))
  784. if err != nil {
  785. return "", ""
  786. }
  787. defer f.Close()
  788. scanner := bufio.NewScanner(f)
  789. scanner.Split(bufio.ScanLines)
  790. var libsslPath, libcryptoPath string
  791. for scanner.Scan() {
  792. parts := strings.Fields(scanner.Text())
  793. if len(parts) <= 5 {
  794. continue
  795. }
  796. libPath := parts[5]
  797. switch {
  798. case libsslPath == "" && strings.Contains(libPath, "libssl.so"):
  799. fullPath := proc.Path(pid, "root", libPath)
  800. if _, err = os.Stat(fullPath); err == nil {
  801. libsslPath = fullPath
  802. }
  803. case libcryptoPath == "" && strings.Contains(libPath, "libcrypto.so"):
  804. fullPath := proc.Path(pid, "root", libPath)
  805. if _, err = os.Stat(fullPath); err == nil {
  806. libcryptoPath = fullPath
  807. }
  808. default:
  809. continue
  810. }
  811. if libsslPath != "" && libcryptoPath != "" {
  812. break
  813. }
  814. }
  815. if libsslPath == "" || libcryptoPath == "" {
  816. return "", ""
  817. }
  818. ef, err := elf.Open(libcryptoPath)
  819. if err != nil {
  820. return "", ""
  821. }
  822. defer ef.Close()
  823. rodataSection := ef.Section(".rodata")
  824. if rodataSection == nil {
  825. return "", ""
  826. }
  827. rodataSectionData, err := rodataSection.Data()
  828. if err != nil {
  829. return "", ""
  830. }
  831. var version string
  832. for _, b := range bytes.Split(rodataSectionData, []byte("\x00")) {
  833. if len(b) == 0 {
  834. continue
  835. }
  836. s := string(b)
  837. if !strings.HasPrefix(s, "OpenSSL") {
  838. continue
  839. }
  840. if m := opensslVersionRe.FindStringSubmatch(s); len(m) > 1 {
  841. version = m[1]
  842. }
  843. }
  844. return libsslPath, "v" + version
  845. }
  846. // selectGRPCServerProbe 根据 gRPC 版本选择服务端探针
  847. func (t *Tracer) selectGRPCServerProbe(major, minor int) string {
  848. // 根据 gRPC 版本选择相应的探针
  849. if major == 1 && minor >= 69 {
  850. // 现代版本 (>= 1.69.0) 使用新的探针
  851. klog.Infof("Selecting modern gRPC server probe for version %d.%d", major, minor)
  852. return "uprobe_server_handleStream2"
  853. } else {
  854. // 传统版本 (< 1.69.0) 使用旧的探针
  855. klog.Infof("Selecting legacy gRPC server probe for version %d.%d", major, minor)
  856. return "uprobe_server_handleStream"
  857. }
  858. }
  859. // attachUprobe 附加单个 uprobe,处理错误
  860. func attachUprobe(exe *link.Executable, symbolName string, probeName string, uprobes map[string]*ebpf.Program, address uint64, onError string, returnOnError bool) (link.Link, error) {
  861. l, err := exe.Uprobe(symbolName, uprobes[probeName], &link.UprobeOptions{Address: address})
  862. if err != nil {
  863. if returnOnError {
  864. klog.WithError(err).Errorf("failed to attach %s uprobe: %s", probeName, onError)
  865. return nil, err
  866. } else {
  867. klog.WithError(err).Errorf("failed to attach %s uprobe: %s", probeName, onError)
  868. return nil, nil
  869. }
  870. }
  871. return l, nil
  872. }
  873. // attachUprobeWithReturns 附加 uprobe 并附加返回探针
  874. // enterProbeName 为空字符串时,只附加返回探针
  875. 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) {
  876. var links []link.Link
  877. // 附加入口探针(如果提供了入口探针名称)
  878. if enterProbeName != "" {
  879. l, err := attachUprobe(exe, symbolName, enterProbeName, uprobes, address, onError, returnOnError)
  880. if err != nil {
  881. return nil, err
  882. }
  883. if l == nil {
  884. return nil, nil
  885. }
  886. links = append(links, l)
  887. }
  888. // 计算符号在 text section 中的位置
  889. sStart := s.Value - textSection.Addr
  890. sEnd := sStart + s.Size
  891. if sEnd > textSectionLen {
  892. return links, nil
  893. }
  894. // 读取符号字节码
  895. sBytes := textSectionData[sStart:sEnd]
  896. returnOffsets := getReturnOffsets(machine, sBytes)
  897. if len(returnOffsets) == 0 {
  898. if returnOnError {
  899. err := fmt.Errorf("failed to attach %s: no return offsets found", returnProbeName)
  900. klog.Errorln(err)
  901. return nil, err
  902. }
  903. return links, nil
  904. }
  905. // 为每个返回点附加探针
  906. for _, offset := range returnOffsets {
  907. l, err := exe.Uprobe(symbolName, uprobes[returnProbeName], &link.UprobeOptions{Address: address, Offset: uint64(offset)})
  908. if err != nil {
  909. if returnOnError {
  910. klog.WithError(err).Errorf("failed to attach %s uprobe", returnProbeName)
  911. return nil, err
  912. }
  913. continue
  914. }
  915. links = append(links, l)
  916. }
  917. return links, nil
  918. }
  919. func getReturnOffsets(machine elf.Machine, instructions []byte) []int {
  920. var res []int
  921. switch machine {
  922. case elf.EM_X86_64:
  923. for i := 0; i < len(instructions); {
  924. ins, err := x86asm.Decode(instructions[i:], 64)
  925. if err == nil && ins.Op == x86asm.RET {
  926. res = append(res, i)
  927. }
  928. i += ins.Len
  929. }
  930. case elf.EM_AARCH64:
  931. for i := 0; i < len(instructions); {
  932. ins, err := arm64asm.Decode(instructions[i:])
  933. if err == nil && ins.Op == arm64asm.RET {
  934. res = append(res, i)
  935. }
  936. i += 4
  937. }
  938. }
  939. return res
  940. }
  941. func min(a, b int) int {
  942. if a < b {
  943. return a
  944. }
  945. return b
  946. }