| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950 |
- package ebpftracer
- import (
- "bufio"
- "bytes"
- "debug/buildinfo"
- "debug/elf"
- "errors"
- "fmt"
- "os"
- "regexp"
- "strconv"
- "strings"
- "github.com/cilium/ebpf/link"
- "github.com/coroot/coroot-node-agent/ebpftracer/tracer"
- "github.com/coroot/coroot-node-agent/proc"
- . "github.com/coroot/coroot-node-agent/utils/modelse"
- klog "github.com/sirupsen/logrus"
- "golang.org/x/arch/arm64/arm64asm"
- "golang.org/x/arch/x86/x86asm"
- "golang.org/x/mod/semver"
- )
- const (
- minSupportedGoVersion = "v1.15.0"
- goTlsWriteSymbol = "crypto/tls.(*Conn).Write"
- goTlsReadSymbol = "crypto/tls.(*Conn).Read"
- goExecute = "runtime.execute"
- goNewproc1 = "runtime.newproc1"
- goRunqget = "runtime.runqget"
- goServeHTTP = "net/http.serverHandler.ServeHTTP"
- goTransport = "net/http.(*Transport).roundTrip"
- goGrpcServerHandleStream = "google.golang.org/grpc.(*Server).handleStream"
- goGrpcHttp2OperateHeader = "google.golang.org/grpc/internal/transport.(*http2Server).operateHeaders"
- goGrpcServerWritestatus = "google.golang.org/grpc/internal/transport.(*http2Server).WriteStatus"
- goGrpcClientConnInvoke = "google.golang.org/grpc.(*ClientConn).Invoke"
- goGrpcClientLoopyHeaderHandler = "google.golang.org/grpc/internal/transport.(*loopyWriter).headerHandler"
- goGrpcHttp2ClientNewStream = "google.golang.org/grpc/internal/transport.(*http2Client).NewStream"
- )
- var (
- opensslVersionRe = regexp.MustCompile(`OpenSSL\s(\d\.\d+\.\d+)`)
- )
- func (t *Tracer) AttachOpenSslUprobes(pid uint32) ([]link.Link, error) {
- if t.DisableL7Tracing() {
- return nil, nil
- }
- libPath, version := getSslLibPathAndVersion(pid)
- if libPath == "" || version == "" {
- return nil, nil
- }
- log := func(msg string, err error) {
- if err != nil {
- for _, s := range []string{"no such file or directory", "no such process", "permission denied"} {
- if strings.HasSuffix(err.Error(), s) {
- return
- }
- }
- klog.Errorf("pid=%d libssl_version=%s: %s: %s", pid, version, msg, err)
- return
- }
- klog.Infof("pid=%d libssl_version=%s: %s", pid, version, msg)
- }
- exe, err := link.OpenExecutable(libPath)
- if err != nil {
- log("failed to open executable", err)
- return nil, err
- }
- var links []link.Link
- writeEnter := "openssl_SSL_write_enter"
- readEnter := "openssl_SSL_read_enter"
- readExEnter := "openssl_SSL_read_ex_enter"
- readExit := "openssl_SSL_read_exit"
- switch {
- case semver.Compare(version, "v3.0.0") >= 0:
- writeEnter = "openssl_SSL_write_enter_v3_0"
- readEnter = "openssl_SSL_read_enter_v3_0"
- readExEnter = "openssl_SSL_read_ex_enter_v3_0"
- case semver.Compare(version, "v1.1.1") >= 0:
- writeEnter = "openssl_SSL_write_enter_v1_1_1"
- readEnter = "openssl_SSL_read_enter_v1_1_1"
- readExEnter = "openssl_SSL_read_ex_enter_v1_1_1"
- }
- type prog struct {
- symbol string
- uprobe string
- uretprobe string
- }
- progs := []prog{
- {symbol: "SSL_write", uprobe: writeEnter},
- {symbol: "SSL_read", uprobe: readEnter},
- {symbol: "SSL_read", uretprobe: readExit},
- }
- if semver.Compare(version, "v1.1.1") >= 0 {
- progs = append(progs, []prog{
- {symbol: "SSL_write_ex", uprobe: writeEnter},
- {symbol: "SSL_read_ex", uprobe: readExEnter},
- {symbol: "SSL_read_ex", uretprobe: readExit},
- }...)
- }
- for _, p := range progs {
- if p.uprobe != "" {
- l, err := exe.Uprobe(p.symbol, t.uprobes[p.uprobe], nil)
- klog.Infoln("fucktls crypto/tls uprobes attached", p.symbol)
- if err != nil {
- //log("failed to attach uprobe", err)
- klog.Infoln("fucktls crypto/tls uprobes attached error", p.symbol)
- return nil, err
- }
- links = append(links, l)
- }
- if p.uretprobe != "" {
- klog.Infoln("fucktls crypto/tls uprobes attached ret", p.symbol)
- l, err := exe.Uretprobe(p.symbol, t.uprobes[p.uretprobe], nil)
- if err != nil {
- klog.Infoln("fucktls crypto/tls uprobes attached ret error", p.symbol)
- //log("failed to attach uretprobe", err)
- return nil, err
- }
- links = append(links, l)
- }
- }
- //log("libssl uprobes attached", nil)
- return links, nil
- }
- func (t *Tracer) AttachGoTlsUprobes(pid uint32, appInfo *AppInfo, codeType uint16) ([]link.Link, error) {
- klog.Infof("[AttachGoTlsUprobes] STEP 1: Function entry, pid=%d", pid)
- if t.DisableL7Tracing() {
- klog.Infof("[AttachGoTlsUprobes] STEP 1.1: L7 tracing disabled, returning early")
- return nil, nil
- }
- path := proc.Path(pid, "exe")
- klog.Infof("[AttachGoTlsUprobes] STEP 2: Got executable path, pid=%d, path=%s", pid, path)
- instanceID := appInfo.InstanceIdHash.HashtVal
- appID := appInfo.AppIdHash.HashtVal
- var err error
- var name, version string
- log := func(msg string, err error) {
- if err != nil {
- for _, s := range []string{"not a Go executable", "no such file or directory", "no such process", "permission denied"} {
- if strings.HasSuffix(err.Error(), s) {
- return
- }
- }
- klog.Errorf("pid=%d golang_app=%s golang_version=%s: %s: %s", pid, name, version, msg, err)
- return
- }
- klog.Infof("pid=%d golang_app=%s golang_version=%s: %s", pid, name, version, msg)
- }
- klog.Infof("[AttachGoTlsUprobes] STEP 3: Reading buildinfo from %s", path)
- bi, err := buildinfo.ReadFile(path)
- if err != nil {
- klog.Errorf("[AttachGoTlsUprobes] STEP 3.1: Failed to read buildinfo, pid=%d, error=%v", pid, err)
- log("failed to read build info", err)
- return nil, err
- }
- klog.Infof("[AttachGoTlsUprobes] STEP 3.2: Buildinfo read successfully, GoVersion=%s", bi.GoVersion)
- // isGolangApp = true
- klog.Infof("[AttachGoTlsUprobes] STEP 4: Reading executable link")
- name, err = os.Readlink(path)
- if err != nil {
- klog.Errorf("[AttachGoTlsUprobes] STEP 4.1: Failed to readlink, pid=%d, error=%v", pid, err)
- log("failed to read name", err)
- return nil, err
- }
- klog.Infof("[AttachGoTlsUprobes] STEP 4.2: Executable name=%s", name)
-
- version = strings.Replace(bi.GoVersion, "go", "v", 1)
- klog.Infof("[AttachGoTlsUprobes] STEP 5: Checking version compatibility, version=%s, minSupported=%s", version, minSupportedGoVersion)
- if semver.Compare(version, minSupportedGoVersion) < 0 {
- klog.Errorf("[AttachGoTlsUprobes] STEP 5.1: Version too old, version=%s < minSupported=%s", version, minSupportedGoVersion)
- log(fmt.Sprintf("go_versions below %s are not supported", minSupportedGoVersion), nil)
- return nil, err
- }
- klog.Infof("[AttachGoTlsUprobes] STEP 5.2: Version check passed")
- klog.Infof("[AttachGoTlsUprobes] STEP 6: Opening ELF file")
- ef, err := elf.Open(path)
- if err != nil {
- klog.Errorf("[AttachGoTlsUprobes] STEP 6.1: Failed to open ELF, pid=%d, error=%v", pid, err)
- log("failed to open as elf binary", err)
- return nil, err
- }
- defer ef.Close()
- klog.Infof("[AttachGoTlsUprobes] STEP 6.2: ELF file opened successfully")
- klog.Infof("[AttachGoTlsUprobes] STEP 7: Reading symbols")
- symbols, err := ef.Symbols()
- if err != nil {
- if errors.Is(err, elf.ErrNoSymbols) {
- klog.Warnf("[AttachGoTlsUprobes] STEP 7.1: No symbol section, pid=%d", pid)
- log("no symbol section", nil)
- return nil, err
- }
- klog.Errorf("[AttachGoTlsUprobes] STEP 7.2: Failed to read symbols, pid=%d, error=%v", pid, err)
- log("failed to read symbols", err)
- return nil, err
- }
- klog.Infof("[AttachGoTlsUprobes] STEP 7.3: Symbols read successfully, count=%d", len(symbols))
- klog.Infof("[AttachGoTlsUprobes] STEP 8: Reading .text section")
- textSection := ef.Section(".text")
- if textSection == nil {
- klog.Errorf("[AttachGoTlsUprobes] STEP 8.1: No .text section, pid=%d", pid)
- log("no text section", nil)
- return nil, err
- }
- textSectionData, err := textSection.Data()
- if err != nil {
- klog.Errorf("[AttachGoTlsUprobes] STEP 8.2: Failed to read .text section data, pid=%d, error=%v", pid, err)
- log("failed to read text section", err)
- return nil, err
- }
- textSectionLen := uint64(len(textSectionData) - 1)
- klog.Infof("[AttachGoTlsUprobes] STEP 8.3: .text section read, size=%d", textSectionLen)
- klog.Infof("[AttachGoTlsUprobes] STEP 9: Opening executable for uprobe")
- exe, err := link.OpenExecutable(path)
- if err != nil {
- klog.Errorf("[AttachGoTlsUprobes] STEP 9.1: Failed to open executable for uprobe, pid=%d, error=%v", pid, err)
- log("failed to open executable", err)
- return nil, err
- }
- klog.Infof("[AttachGoTlsUprobes] STEP 9.2: Executable opened for uprobe")
- // 检测 gRPC 版本
- klog.Infof("[AttachGoTlsUprobes] STEP 10: Detecting gRPC version")
- var grpcMajorVersion, grpcMinorVersion int
- for _, dep := range bi.Deps {
- if strings.Contains(dep.Path, "grpc") {
- klog.Infoln("Found gRPC dependency:", dep.Path, "version:", dep.Version)
-
- // 解析版本号
- version := dep.Version
- if version != "" {
- // 移除可能的 "v" 前缀
- version = strings.TrimPrefix(version, "v")
- parts := strings.Split(version, ".")
-
- if len(parts) >= 2 {
- major, err := strconv.Atoi(parts[0])
- if err != nil {
- klog.WithError(err).Warnf("Error parsing major version from %s", parts[0])
- continue
- }
-
- minor, err := strconv.Atoi(parts[1])
- if err != nil {
- klog.WithError(err).Warnf("Error parsing minor version from %s", parts[1])
- continue
- }
-
- klog.Infof("Detected gRPC version: %d.%d for PID %d", major, minor, pid)
- grpcMajorVersion = major
- grpcMinorVersion = minor
- // // 根据版本选择相应的探针策略
- // if major == 1 && minor >= 69 {
- // klog.Infof("Using modern gRPC handler for version %d.%d", major, minor)
- // } else {
- // klog.Infof("Using legacy gRPC handler for version %d.%d", major, minor)
- // }
- }
- }
- }
- }
- klog.Infof("[AttachGoTlsUprobes] STEP 10.1: gRPC version detection completed, major=%d, minor=%d", grpcMajorVersion, grpcMinorVersion)
- klog.Infof("[AttachGoTlsUprobes] STEP 11: Getting offset for runtime.g.goid")
- offset, ok := tracer.GetOffset(tracer.NewID("std", "runtime", "g", "goid"), path)
- if ok {
- klog.Infof("[AttachGoTlsUprobes] STEP 11.1: Successfully got goid offset=%d", offset)
- } else {
- klog.Errorf("[AttachGoTlsUprobes] STEP 11.2: Failed to get goid offset, pid=%d, version=%s", pid, bi.GoVersion)
- }
- klog.Infof("[AttachGoTlsUprobes] STEP 12: Getting offset for runtime.hmap.buckets")
- bucketsOff, ok2 := tracer.GetOffset(tracer.NewID("std", "runtime", "hmap", "buckets"), path)
-
- // Go 1.24+ 使用新的 map 实现(Swiss Tables),使用 internal/runtime/maps.Map 而不是 runtime.hmap
- if !ok2 {
- klog.Errorf("[AttachGoTlsUprobes] STEP 12.2: Failed to get buckets offset, pid=%d, version=%s", pid, bi.GoVersion)
- klog.Infof("[AttachGoTlsUprobes] STEP 12.3: Trying Swiss Tables maps.Map.dirPtr for Go 1.24+")
-
- // Go 1.24+ Swiss Tables 使用 internal/runtime/maps.Map 结构体
- // 结构体字段:used uint64, seed uintptr, dirPtr unsafe.Pointer (相当于旧的 buckets)
- // 尝试获取 maps.Map.dirPtr 的偏移量
- // 注意:DWARF 中的包路径可能是 "internal/runtime/maps" 或 "internal/runtime/maps.Map"
- swissFields := []struct {
- pkg string
- structName string
- field string
- }{
- {"internal/runtime/maps", "Map", "dirPtr"},
- {"internal.runtime.maps", "Map", "dirPtr"},
- {"maps", "Map", "dirPtr"},
- }
-
- for _, sf := range swissFields {
- // 尝试不同的包路径格式
- swissOff, swissOk := tracer.GetOffset(tracer.NewID("std", sf.pkg, sf.structName, sf.field), path)
- if swissOk {
- klog.Infof("[AttachGoTlsUprobes] STEP 12.4: Found Swiss Tables field '%s.%s.%s' with offset=%d", sf.pkg, sf.structName, sf.field, swissOff)
- bucketsOff = swissOff
- ok2 = true
- break
- } else {
- klog.Debugf("[AttachGoTlsUprobes] STEP 12.4: Trying Swiss Tables field '%s.%s.%s' not found", sf.pkg, sf.structName, sf.field)
- }
- }
-
- // 如果还是找不到,尝试旧的 hmap 字段作为备选
- if !ok2 {
- klog.Infof("[AttachGoTlsUprobes] STEP 12.5: Trying alternative hmap field names")
- alternativeFields := []string{"table", "swiss", "swissTable", "buckets1", "oldbuckets", "bmap", "extra"}
- for _, fieldName := range alternativeFields {
- altOff, altOk := tracer.GetOffset(tracer.NewID("std", "runtime", "hmap", fieldName), path)
- if altOk {
- klog.Infof("[AttachGoTlsUprobes] STEP 12.6: Found alternative field '%s' with offset=%d", fieldName, altOff)
- bucketsOff = altOff
- ok2 = true
- break
- }
- }
- }
-
- if !ok2 {
- klog.Errorf("[AttachGoTlsUprobes] STEP 12.7: All attempts failed, Go 1.24+ Swiss Tables map structure not found")
- // 根据源码分析,maps.Map 结构体布局(64-bit):
- // - used uint64 (8 bytes, offset 0)
- // - seed uintptr (8 bytes, offset 8)
- // - dirPtr unsafe.Pointer (8 bytes, offset 16) <- 相当于旧的 buckets
- // 如果 DWARF 查找失败,使用硬编码的偏移量作为 fallback
- // 注意:这需要确认目标系统是 64-bit,且结构体对齐正确
- klog.Warnf("[AttachGoTlsUprobes] STEP 12.8: Using hardcoded offset for maps.Map.dirPtr (offset=16 on 64-bit)")
- klog.Warnf("[AttachGoTlsUprobes] STEP 12.9: This assumes: used(uint64@0) + seed(uintptr@8) + dirPtr(unsafe.Pointer@16)")
-
- // 检查 Go 版本是否 >= 1.24
- realVersion := strings.Replace(bi.GoVersion, "go", "", 1)
- parts := strings.Split(realVersion, ".")
- if len(parts) >= 2 {
- major, _ := strconv.Atoi(parts[0])
- minor, _ := strconv.Atoi(parts[1])
- if major > 1 || (major == 1 && minor >= 24) {
- // Go 1.24+ 使用 Swiss Tables,maps.Map.dirPtr 在 offset 16 (64-bit)
- // 假设是 64-bit 系统(大多数生产环境)
- bucketsOff = 16
- ok2 = true
- klog.Infof("[AttachGoTlsUprobes] STEP 12.10: Using hardcoded offset=%d for Go %s (Swiss Tables)", bucketsOff, bi.GoVersion)
- } else {
- klog.Errorf("[AttachGoTlsUprobes] STEP 12.11: Go version < 1.24 but buckets not found, this is unexpected")
- bucketsOff = 0
- }
- } else {
- klog.Errorf("[AttachGoTlsUprobes] STEP 12.12: Failed to parse Go version: %s", bi.GoVersion)
- bucketsOff = 0
- }
- }
- } else {
- klog.Infof("[AttachGoTlsUprobes] STEP 12.1: Successfully got buckets offset=%d", bucketsOff)
- }
- klog.Infof("[AttachGoTlsUprobes] STEP 13: Checking if both offsets are valid, goid_ok=%v, buckets_ok=%v", ok, ok2)
- // Go 1.24+ 兼容:如果 goid 成功但 buckets 失败,仍然继续(但记录警告)
- if ok {
- if !ok2 {
- klog.Warnf("[AttachGoTlsUprobes] STEP 13.0: buckets offset missing for Go 1.24+, but continuing with goid only")
- // 对于 Go 1.24,可能需要调整后续逻辑,暂时允许继续
- }
- klog.Infof("[AttachGoTlsUprobes] STEP 13.1: Both offsets valid, proceeding with version encoding")
- klog.Infof("[AttachGoTlsUprobes] STEP 14: Parsing Go version string")
- realVersion := strings.Replace(bi.GoVersion, "go", "", 1)
- klog.Infof("[AttachGoTlsUprobes] STEP 14.1: Real version string=%s", realVersion)
- parts := strings.Split(realVersion, ".")
- var major, minor, revision int
- if len(parts) >= 2 {
- major, err = strconv.Atoi(parts[0])
- if err != nil {
- klog.Errorf("[AttachGoTlsUprobes] STEP 14.2: Error converting major version, error=%v", err)
- log("Error converting major version:", err)
- return nil, err
- }
- minor, err = strconv.Atoi(parts[1])
- if err != nil {
- klog.Errorf("[AttachGoTlsUprobes] STEP 14.3: Error converting minor version, error=%v", err)
- log("Error converting minor version:", err)
- return nil, err
- }
- if len(parts) >= 3 {
- revision, err = strconv.Atoi(parts[2])
- if err != nil {
- klog.Warnf("[AttachGoTlsUprobes] STEP 14.4: Error converting revision version, error=%v", err)
- log("Error converting revision version:", err)
- }
- }
- klog.Infof("[AttachGoTlsUprobes] STEP 14.5: Parsed version, major=%d, minor=%d, revision=%d", major, minor, revision)
- goVersion := ((major & 0xFF) << 16) + ((minor & 0xFF) << 8) + min(revision, 255)
- klog.Infof("[AttachGoTlsUprobes] STEP 14.6: Encoded version=%d (0x%x)", goVersion, goVersion)
- klog.Infof("[AttachGoTlsUprobes] STEP 15: Initializing EbpfProcInfo structure")
- info := EbpfProcInfo{}
- info.Version = uint32(goVersion)
- info.Offsets[OFFSET_IDX_GOID_RUNTIME_G] = uint16(offset)
- info.NetTCPConnItab = uint64(0)
- info.CryptoTLSConnItab = uint64(0)
- info.CredentialsSyscallConnItab = uint64(0)
- info.InstanceId = instanceID
- info.AppId = appID
- info.CodeType = codeType
- if grpcMajorVersion >= 1 && grpcMinorVersion >= 60 {
- info.IsNewFramePos = 1
- klog.Infof("[AttachGoTlsUprobes] STEP 15.1: Using new frame position for gRPC >= 1.60")
- } else {
- info.IsNewFramePos = 0
- klog.Infof("[AttachGoTlsUprobes] STEP 15.2: Using old frame position for gRPC < 1.60")
- }
- // go
- info.BucketsPtrPos = bucketsOff
- if bucketsOff == 0 {
- klog.Warnf("[AttachGoTlsUprobes] STEP 15.3: BucketsPtrPos=0 (Go 1.24+ may not use buckets field)")
- } else {
- klog.Infof("[AttachGoTlsUprobes] STEP 15.3: Basic info initialized, BucketsPtrPos=%d", bucketsOff)
- }
-
- klog.Infof("[AttachGoTlsUprobes] STEP 16: Getting offsets for HTTP and gRPC fields")
- fields := map[*uint64]tracer.ID{
- &info.MethodPtrPos: tracer.NewID("std", "net/http", "Request", "Method"),
- &info.UrlPtrPos: tracer.NewID("std", "net/http", "Request", "URL"),
- &info.PathPtrPos: tracer.NewID("std", "net/url", "URL", "Path"),
- &info.StatusCodePos: tracer.NewID("std", "net/http", "response", "status"),
- &info.RequestHostPos: tracer.NewID("std", "net/http", "Request", "Host"),
- &info.ProtoPos: tracer.NewID("std", "net/http", "Request", "Proto"),
- &info.CtxPtrPos: tracer.NewID("std", "net/http", "Request", "ctx"),
- &info.HeadersPtrPos: tracer.NewID("std", "net/http", "Request", "Header"),
- &info.HttpClientNextidPos: tracer.NewID("google.golang.org/grpc","google.golang.org/grpc/internal/transport","http2Client","nextID"),
- &info.StreamMethodPtrPos: tracer.NewID("google.golang.org/grpc","google.golang.org/grpc/internal/transport","Stream","method"),
- &info.StreamCtxPos: tracer.NewID("google.golang.org/grpc","google.golang.org/grpc/internal/transport","Stream","ctx"),
- }
- successCount := 0
- failCount := 0
- for field, id := range fields {
- off, ok := tracer.GetOffset(id, path)
- if !ok {
- 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)
- failCount++
- } else {
- successCount++
- klog.Debugf("[AttachGoTlsUprobes] STEP 16.2: Got offset for %s.%s.%s = %d", id.PkgPath, id.Struct, id.Field, off)
- }
- *field = off
- }
- klog.Infof("[AttachGoTlsUprobes] STEP 16.3: Field offset collection completed, success=%d, failed=%d", successCount, failCount)
- klog.Infof("[AttachGoTlsUprobes] STEP 17: Allocating memory for process")
- // 获取内存地址
- if appInfo.GoProcCache.StartAddr == 0 && appInfo.GoProcCache.EndAddr == 0 {
- klog.Infof("[AttachGoTlsUprobes] STEP 17.1: Cache empty, calling Allocate")
- allocDetails, allocErr := tracer.Allocate(int(pid))
- if allocErr != nil {
- klog.Errorf("[AttachGoTlsUprobes] STEP 17.2: Allocate failed, pid=%d, error=%v", pid, allocErr)
- return nil, allocErr
- }
- if allocDetails != nil {
- appInfo.GoProcCache.StartAddr = allocDetails.StartAddr
- appInfo.GoProcCache.EndAddr = allocDetails.EndAddr
- klog.Infof("[AttachGoTlsUprobes] STEP 17.3: Allocate succeeded, StartAddr=0x%x, EndAddr=0x%x", allocDetails.StartAddr, allocDetails.EndAddr)
- } else {
- klog.Warnf("[AttachGoTlsUprobes] STEP 17.4: Allocate returned nil")
- }
- } else {
- klog.Infof("[AttachGoTlsUprobes] STEP 17.5: Using cached addresses, StartAddr=0x%x, EndAddr=0x%x", appInfo.GoProcCache.StartAddr, appInfo.GoProcCache.EndAddr)
- }
- info.StartAddr = appInfo.GoProcCache.StartAddr
- info.EndAddr = appInfo.GoProcCache.EndAddr
- klog.Debugln("Major:", major)
- klog.Debugln("Minor:", minor)
- klog.Debugln("Revision:", revision)
- klog.Debugln("goVersion", goVersion)
- klog.WithField("pid", pid).Debugln("info.StartAddr", info.StartAddr)
- klog.WithField("pid", pid).Debugln("info.EndAddr", info.EndAddr)
-
- klog.Infof("[AttachGoTlsUprobes] STEP 18: Updating proc_info map")
- _, err = tracer.UpdateProcInfoToMap(t.collection, pid, info)
- if err != nil {
- klog.Errorf("[AttachGoTlsUprobes] STEP 18.1: Failed to update proc_info map, pid=%d, error=%v", pid, err)
- klog.Error("failed to update program info", err)
- return nil, err
- }
- klog.Infof("[AttachGoTlsUprobes] STEP 18.2: Proc_info map updated successfully")
- appInfo.EBPFProcInfo = &info
- } else {
- klog.Errorf("[AttachGoTlsUprobes] STEP 13.2: Skipping proc_info initialization due to missing offsets, goid_ok=%v, buckets_ok=%v", ok, ok2)
- if !ok {
- klog.Errorf("[AttachGoTlsUprobes] STEP 13.3: runtime.g.goid offset missing - this is critical!")
- }
- if !ok2 {
- klog.Errorf("[AttachGoTlsUprobes] STEP 13.4: runtime.hmap.buckets offset missing - Go 1.24+ may use new map implementation")
- }
- }
- }
- klog.Infof("[AttachGoTlsUprobes] STEP 19: Starting symbol matching and uprobe attachment, total symbols=%d", len(symbols))
- var links []link.Link
- matchedSymbols := 0
- for i, s := range symbols {
- if elf.ST_TYPE(s.Info) != elf.STT_FUNC || s.Size == 0 {
- continue
- }
- switch s.Name {
- case goTlsWriteSymbol, goTlsReadSymbol:
- matchedSymbols++
- klog.Infof("[AttachGoTlsUprobes] STEP 19.1: Matched TLS symbol: %s (index=%d)", s.Name, i)
- case goExecute:
- matchedSymbols++
- klog.Infof("[AttachGoTlsUprobes] STEP 19.2: Matched runtime.execute symbol (index=%d)", i)
- case goNewproc1:
- matchedSymbols++
- klog.Infof("[AttachGoTlsUprobes] STEP 19.3: Matched runtime.newproc1 symbol (index=%d)", i)
- case goRunqget:
- matchedSymbols++
- klog.Infof("[AttachGoTlsUprobes] STEP 19.4: Matched runtime.runqget symbol (index=%d)", i)
- case goServeHTTP:
- matchedSymbols++
- klog.Infof("[AttachGoTlsUprobes] STEP 19.5: Matched net/http.serverHandler.ServeHTTP symbol (index=%d)", i)
- case goTransport:
- matchedSymbols++
- klog.Infof("[AttachGoTlsUprobes] STEP 19.6: Matched net/http.Transport.roundTrip symbol (index=%d)", i)
- case goGrpcClientConnInvoke:
- matchedSymbols++
- klog.Infof("[AttachGoTlsUprobes] STEP 19.7: Matched gRPC ClientConn.Invoke symbol (index=%d)", i)
- case goGrpcHttp2OperateHeader, goGrpcServerHandleStream, goGrpcServerWritestatus, goGrpcClientLoopyHeaderHandler, goGrpcHttp2ClientNewStream:
- matchedSymbols++
- klog.Infof("[AttachGoTlsUprobes] STEP 19.8: Matched gRPC symbol: %s (index=%d)", s.Name, i)
- default:
- continue
- }
- klog.Debugf("[AttachGoTlsUprobes] STEP 19.9: Processing symbol %s, Value=0x%x, Size=%d", s.Name, s.Value, s.Size)
- address := s.Value
- for _, p := range ef.Progs {
- if p.Type != elf.PT_LOAD || (p.Flags&elf.PF_X) == 0 {
- continue
- }
- if p.Vaddr <= s.Value && s.Value < (p.Vaddr+p.Memsz) {
- address = s.Value - p.Vaddr + p.Off
- break
- }
- }
- //fmt.Println("s.Name-----:", s.Name)
- switch s.Name {
- case goExecute:
- klog.Infof("[AttachGoTlsUprobes] STEP 20: Attaching uprobe for runtime.execute, address=0x%x", address)
- l, err := exe.Uprobe(s.Name, t.uprobes["runtime_execute"], &link.UprobeOptions{Address: address})
- if err != nil {
- klog.Errorf("[AttachGoTlsUprobes] STEP 20.1: Failed to attach runtime.execute uprobe, error=%v", err)
- log("failed to attach write_enter uprobe", err)
- klog.Infoln("runtime.execute no")
- return nil, err
- } else {
- klog.Infof("[AttachGoTlsUprobes] STEP 20.2: Successfully attached runtime.execute uprobe")
- klog.Infoln("runtime.execute ok")
- }
- links = append(links, l)
- case goNewproc1:
- klog.Infof("[AttachGoTlsUprobes] STEP 21: Attaching uprobe for runtime.newproc1, address=0x%x", address)
- l, err := exe.Uprobe(s.Name, t.uprobes["enter_runtime_newproc1"], &link.UprobeOptions{Address: address})
- if err != nil {
- klog.Errorf("[AttachGoTlsUprobes] STEP 21.1: Failed to attach enter_runtime_newproc1 uprobe, error=%v", err)
- log("failed to attach newproc1 uprobe", err)
- return nil, err
- }
- klog.Infof("[AttachGoTlsUprobes] STEP 21.2: Successfully attached enter_runtime_newproc1 uprobe")
- links = append(links, l)
- sStart := s.Value - textSection.Addr
- sEnd := sStart + s.Size
- if sEnd > textSectionLen {
- continue
- }
- sBytes := textSectionData[sStart:sEnd]
- returnOffsets := getReturnOffsets(ef.Machine, sBytes)
- if len(returnOffsets) == 0 {
- log("failed to attach enter_runtime_newproc1 uprobe", fmt.Errorf("no return offsets found"))
- return nil, err
- }
- for _, offset := range returnOffsets {
- l, err := exe.Uprobe(s.Name, t.uprobes["exit_runtime_newproc1"], &link.UprobeOptions{Address: address, Offset: uint64(offset)})
- if err != nil {
- log("failed to attach exit_runtime_newproc1 uprobe", err)
- return nil, err
- }
- links = append(links, l)
- }
- case goRunqget:
- l, err := exe.Uprobe(s.Name, t.uprobes["enter_runtime_runqget"], &link.UprobeOptions{Address: address})
- if err != nil {
- log("failed to attach goRunqget uprobe", err)
- return nil, err
- }
- links = append(links, l)
- //sStart := s.Value - textSection.Addr
- //sEnd := sStart + s.Size
- //if sEnd > textSectionLen {
- // continue
- //}
- //sBytes := textSectionData[sStart:sEnd]
- //returnOffsets := getReturnOffsets(ef.Machine, sBytes)
- //if len(returnOffsets) == 0 {
- // log("failed to attach enter_runtime_newproc1 uprobe", fmt.Errorf("no return offsets found"))
- // return nil
- //}
- //for _, offset := range returnOffsets {
- // l, err := exe.Uprobe(s.Name, t.uprobes["exit_runtime_newproc1"], &link.UprobeOptions{Address: address, Offset: uint64(offset)})
- // if err != nil {
- // log("failed to attach exit_runtime_newproc1 uprobe", err)
- // return nil
- // }
- // links = append(links, l)
- //}
- case goGrpcClientConnInvoke:
- // 根据 gRPC 版本选择相应的探针
- l, err := exe.Uprobe(s.Name, t.uprobes["uprobe_ClientConn_Invoke"], &link.UprobeOptions{Address: address})
- if err != nil {
- klog.WithError(err).Errorf("failed to attach uprobe_ClientConn_Invoke uprobe")
- continue
- }
- klog.Infoln("uprobe_ClientConn_Invoke ok")
- links = append(links, l)
- sStart := s.Value - textSection.Addr
- sEnd := sStart + s.Size
- if sEnd > textSectionLen {
- continue
- }
- sBytes := textSectionData[sStart:sEnd]
- returnOffsets := getReturnOffsets(ef.Machine, sBytes)
- if len(returnOffsets) == 0 {
- err = fmt.Errorf("failed to attach uprobe_ClientConn_Invoke no return offsets found")
- klog.Errorln(err)
- return nil, err
- }
- for _, offset := range returnOffsets {
- l, err := exe.Uprobe(s.Name, t.uprobes["uprobe_ClientConn_Invoke_Returns"], &link.UprobeOptions{Address: address, Offset: uint64(offset)})
- if err != nil {
- klog.WithError(err).Errorln(fmt.Errorf("failed to attach uprobe_ClientConn_Invoke_Returns uprobe"))
- return nil, err
- }
- links = append(links, l)
- }
- case goGrpcClientLoopyHeaderHandler:
- // 根据 gRPC 版本选择相应的探针
- l, err := exe.Uprobe(s.Name, t.uprobes["uprobe_LoopyWriter_HeaderHandler"], &link.UprobeOptions{Address: address})
- if err != nil {
- klog.WithError(err).Errorf("failed to attach uprobe_LoopyWriter_HeaderHandler uprobe")
- continue
- }
- klog.Infoln("uprobe_LoopyWriter_HeaderHandler ok")
- links = append(links, l)
- case goGrpcHttp2ClientNewStream:
- // 根据 gRPC 版本选择相应的探针
- l, err := exe.Uprobe(s.Name, t.uprobes["uprobe_http2Client_NewStream"], &link.UprobeOptions{Address: address})
- if err != nil {
- klog.WithError(err).Errorf("failed to attach uprobe_http2Client_NewStream uprobe")
- continue
- }
- klog.Infoln("uprobe_http2Client_NewStream ok")
- links = append(links, l)
- case goGrpcHttp2OperateHeader:
- // 根据 gRPC 版本选择相应的探针
- l, err := exe.Uprobe(s.Name, t.uprobes["uprobe_http2Server_operateHeader"], &link.UprobeOptions{Address: address})
- if err != nil {
- klog.WithError(err).Errorf("failed to attach uprobe_http2Server_operateHeader uprobe")
- continue
- }
- klog.Infoln("uprobe_http2Server_operateHeader ok")
- links = append(links, l)
- // case goGrpcServerWritestatus:
- // // 根据 gRPC 版本选择相应的 WriteStatus 探针
- // l, err := exe.Uprobe(s.Name, t.uprobes["uprobe_http2Server_WriteStatus"], &link.UprobeOptions{Address: address})
- // if err != nil {
- // klog.WithError(err).Errorf("failed to attach uprobe_http2Server_WriteStatus uprobe")
- // continue
- // }
- // links = append(links, l)
- case goGrpcServerHandleStream:
- // 根据 gRPC 版本选择相应的探针
- probeName := t.selectGRPCServerProbe(grpcMajorVersion, grpcMinorVersion)
- l, err := exe.Uprobe(s.Name, t.uprobes[probeName], &link.UprobeOptions{Address: address})
- if err != nil {
- klog.WithError(err).Errorf("failed to attach %s uprobe", probeName)
- continue
- }
- klog.Infof("%s ok (gRPC v%d.%d)", probeName, grpcMajorVersion, grpcMinorVersion)
- links = append(links, l)
- sStart := s.Value - textSection.Addr
- sEnd := sStart + s.Size
- klog.Infoln("google.golang.org/grpc.(*Server).handleStream ok----111111")
- if sEnd > textSectionLen {
- continue
- }
- klog.Infoln("google.golang.org/grpc.(*Server).handleStream ok----2222")
- sBytes := textSectionData[sStart:sEnd]
- returnOffsets := getReturnOffsets(ef.Machine, sBytes)
- if len(returnOffsets) == 0 {
- err = fmt.Errorf("failed to attach uprobe_server_handleStream2 no return offsets found")
- klog.Errorln(err)
- return nil, err
- }
- for _, offset := range returnOffsets {
- l, err := exe.Uprobe(s.Name, t.uprobes["uprobe_server_handleStream_Returns"], &link.UprobeOptions{Address: address, Offset: uint64(offset)})
- if err != nil {
- klog.WithError(err).Errorln(fmt.Errorf("failed to attach exit_runtime_newproc1 uprobe"))
- return nil, err
- }
- klog.Infoln("google.golang.org/grpc.(*Server).handleStream ok----")
- links = append(links, l)
- }
- case goServeHTTP:
- l, err := exe.Uprobe(s.Name, t.uprobes["uprobe_HandlerFunc_ServeHTTP"], &link.UprobeOptions{Address: address})
- if err != nil {
- klog.WithError(err).Errorln("failed to attach uprobe_HandlerFunc_ServeHTTP uprobe")
- continue
- }
- klog.Infoln("net/http.serverHandler.ServeHTTP ok")
- links = append(links, l)
- sStart := s.Value - textSection.Addr
- sEnd := sStart + s.Size
- if sEnd > textSectionLen {
- continue
- }
- sBytes := textSectionData[sStart:sEnd]
- returnOffsets := getReturnOffsets(ef.Machine, sBytes)
- if len(returnOffsets) == 0 {
- err = fmt.Errorf("failed to attach uprobe_HandlerFunc_ServeHTTP no return offsets found")
- klog.Errorln(err)
- return nil, err
- }
- for _, offset := range returnOffsets {
- l, err := exe.Uprobe(s.Name, t.uprobes["uprobe_HandlerFunc_ServeHTTP_Returns"], &link.UprobeOptions{Address: address, Offset: uint64(offset)})
- if err != nil {
- klog.WithError(err).Errorln(fmt.Errorf("failed to attach exit_runtime_newproc1 uprobe"))
- return nil, err
- }
- links = append(links, l)
- }
- case goTransport:
- if t.DisableE2ETracing() {
- continue
- }
- l, err := exe.Uprobe(s.Name, t.uprobes["uprobe_Transport_roundTrip"], &link.UprobeOptions{Address: address})
- if err != nil {
- klog.WithError(err).Errorln(fmt.Errorf("failed to attach write_enter uprobe"))
- continue
- } else {
- }
- klog.Infoln("net/http.uprobe_Transport_roundTrip ok")
- links = append(links, l)
- sStart := s.Value - textSection.Addr
- sEnd := sStart + s.Size
- if sEnd > textSectionLen {
- continue
- }
- sBytes := textSectionData[sStart:sEnd]
- returnOffsets := getReturnOffsets(ef.Machine, sBytes)
- if len(returnOffsets) == 0 {
- err = fmt.Errorf("failed to attach uprobe_Transport_roundTrip uprobe no return offsets found")
- klog.Errorln(err)
- return nil, err
- }
- for _, offset := range returnOffsets {
- l, err := exe.Uprobe(s.Name, t.uprobes["uprobe_Transport_roundTrip_Returns"], &link.UprobeOptions{Address: address, Offset: uint64(offset)})
- if err != nil {
- klog.WithError(err).Errorln("failed to attach exit_runtime_newproc1 uprobe")
- return nil, err
- }
- links = append(links, l)
- }
- case goTlsWriteSymbol:
- klog.Infoln("fucktls goTlsWriteSymbol crypto/tls uprobes attached")
- l, err := exe.Uprobe(s.Name, t.uprobes["go_crypto_tls_write_enter"], &link.UprobeOptions{Address: address})
- if err != nil {
- klog.WithError(err).Errorln("failed to attach write_enter uprobe")
- return nil, err
- }
- links = append(links, l)
- case goTlsReadSymbol:
- klog.Infoln("fucktls goTlsReadSymbol crypto/tls uprobes attached")
- l, err := exe.Uprobe(s.Name, t.uprobes["go_crypto_tls_read_enter"], &link.UprobeOptions{Address: address})
- if err != nil {
- klog.WithError(err).Errorln("failed to attach read_enter uprobe")
- return nil, err
- }
- links = append(links, l)
- sStart := s.Value - textSection.Addr
- sEnd := sStart + s.Size
- if sEnd > textSectionLen {
- continue
- }
- sBytes := textSectionData[sStart:sEnd]
- returnOffsets := getReturnOffsets(ef.Machine, sBytes)
- if len(returnOffsets) == 0 {
- err = fmt.Errorf("failed to attach read_exit uprobe no return offsets found")
- klog.Errorln(err)
- return nil, err
- }
- for _, offset := range returnOffsets {
- l, err := exe.Uprobe(s.Name, t.uprobes["go_crypto_tls_read_exit"], &link.UprobeOptions{Address: address, Offset: uint64(offset)})
- if err != nil {
- klog.WithError(err).Errorln("failed to attach read_exit uprobe")
- return nil, err
- }
- links = append(links, l)
- }
- }
- }
- klog.Infof("[AttachGoTlsUprobes] STEP 22: Symbol processing completed, matched symbols=%d, total links=%d", matchedSymbols, len(links))
- if len(links) == 0 {
- klog.Errorf("[AttachGoTlsUprobes] STEP 22.1: No uprobes attached, returning error")
- return nil, err
- }
- klog.Infof("[AttachGoTlsUprobes] STEP 23: Function completed successfully, attached %d uprobes", len(links))
- klog.Infoln("crypto/tls uprobes attached")
- return links, nil
- }
- func getSslLibPathAndVersion(pid uint32) (string, string) {
- f, err := os.Open(proc.Path(pid, "maps"))
- if err != nil {
- return "", ""
- }
- defer f.Close()
- scanner := bufio.NewScanner(f)
- scanner.Split(bufio.ScanLines)
- var libsslPath, libcryptoPath string
- for scanner.Scan() {
- parts := strings.Fields(scanner.Text())
- if len(parts) <= 5 {
- continue
- }
- libPath := parts[5]
- switch {
- case libsslPath == "" && strings.Contains(libPath, "libssl.so"):
- fullPath := proc.Path(pid, "root", libPath)
- if _, err = os.Stat(fullPath); err == nil {
- libsslPath = fullPath
- }
- case libcryptoPath == "" && strings.Contains(libPath, "libcrypto.so"):
- fullPath := proc.Path(pid, "root", libPath)
- if _, err = os.Stat(fullPath); err == nil {
- libcryptoPath = fullPath
- }
- default:
- continue
- }
- if libsslPath != "" && libcryptoPath != "" {
- break
- }
- }
- if libsslPath == "" || libcryptoPath == "" {
- return "", ""
- }
- ef, err := elf.Open(libcryptoPath)
- if err != nil {
- return "", ""
- }
- defer ef.Close()
- rodataSection := ef.Section(".rodata")
- if rodataSection == nil {
- return "", ""
- }
- rodataSectionData, err := rodataSection.Data()
- if err != nil {
- return "", ""
- }
- var version string
- for _, b := range bytes.Split(rodataSectionData, []byte("\x00")) {
- if len(b) == 0 {
- continue
- }
- s := string(b)
- if !strings.HasPrefix(s, "OpenSSL") {
- continue
- }
- if m := opensslVersionRe.FindStringSubmatch(s); len(m) > 1 {
- version = m[1]
- }
- }
- return libsslPath, "v" + version
- }
- // selectGRPCServerProbe 根据 gRPC 版本选择服务端探针
- func (t *Tracer) selectGRPCServerProbe(major, minor int) string {
- // 根据 gRPC 版本选择相应的探针
- if major == 1 && minor >= 69 {
- // 现代版本 (>= 1.69.0) 使用新的探针
- klog.Infof("Selecting modern gRPC server probe for version %d.%d", major, minor)
- return "uprobe_server_handleStream2"
- } else {
- // 传统版本 (< 1.69.0) 使用旧的探针
- klog.Infof("Selecting legacy gRPC server probe for version %d.%d", major, minor)
- return "uprobe_server_handleStream"
- }
- }
- func getReturnOffsets(machine elf.Machine, instructions []byte) []int {
- var res []int
- switch machine {
- case elf.EM_X86_64:
- for i := 0; i < len(instructions); {
- ins, err := x86asm.Decode(instructions[i:], 64)
- if err == nil && ins.Op == x86asm.RET {
- res = append(res, i)
- }
- i += ins.Len
- }
- case elf.EM_AARCH64:
- for i := 0; i < len(instructions); {
- ins, err := arm64asm.Decode(instructions[i:])
- if err == nil && ins.Op == arm64asm.RET {
- res = append(res, i)
- }
- i += 4
- }
- }
- return res
- }
- func min(a, b int) int {
- if a < b {
- return a
- }
- return b
- }
|