tls.go 36 KB

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