diff --git a/hash.go b/hash.go index 0075e67..58582ef 100644 --- a/hash.go +++ b/hash.go @@ -93,15 +93,15 @@ func addGarbleToHash(inputHash []byte) []byte { // content ID. hasher.Reset() hasher.Write(inputHash) - if len(cache.BinaryContentID) == 0 { + if len(sharedCache.BinaryContentID) == 0 { panic("missing binary content ID") } - hasher.Write(cache.BinaryContentID) + hasher.Write(sharedCache.BinaryContentID) // We also need to add the selected options to the full version string, // because all of them result in different output. We use spaces to // separate the env vars and flags, to reduce the chances of collisions. - fmt.Fprintf(hasher, " GOGARBLE=%s", cache.GOGARBLE) + fmt.Fprintf(hasher, " GOGARBLE=%s", sharedCache.GOGARBLE) appendFlags(hasher, true) // addGarbleToHash returns the sum buffer, so we need a new copy. // Otherwise the next use of the global sumBuffer would conflict. @@ -198,7 +198,7 @@ func toUpper(b byte) byte { return b - ('a' - 'A') } func runtimeHashWithCustomSalt(salt []byte) uint32 { hasher.Reset() if !flagSeed.present() { - hasher.Write(cache.ListedPackages["runtime"].GarbleActionID) + hasher.Write(sharedCache.ListedPackages["runtime"].GarbleActionID) } else { hasher.Write(flagSeed.bytes) } diff --git a/main.go b/main.go index 38206e1..5b6126e 100644 --- a/main.go +++ b/main.go @@ -270,7 +270,7 @@ func goVersionOK() bool { // rxVersion looks for a version like "go1.2" or "go1.2.3" rxVersion := regexp.MustCompile(`go\d+\.\d+(?:\.\d+)?`) - toolchainVersionFull := cache.GoEnv.GOVERSION + toolchainVersionFull := sharedCache.GoEnv.GOVERSION toolchainVersion := rxVersion.FindString(toolchainVersionFull) if toolchainVersion == "" { // Go 1.15.x and older do not have GOVERSION yet. @@ -280,8 +280,8 @@ func goVersionOK() bool { return false } - cache.GoVersionSemver = "v" + strings.TrimPrefix(toolchainVersion, "go") - if semver.Compare(cache.GoVersionSemver, minGoVersionSemver) < 0 { + sharedCache.GoVersionSemver = "v" + strings.TrimPrefix(toolchainVersion, "go") + if semver.Compare(sharedCache.GoVersionSemver, minGoVersionSemver) < 0 { fmt.Fprintf(os.Stderr, "Go version %q is too old; please upgrade to Go %s or newer\n", toolchainVersionFull, suggestedGoVersion) return false } @@ -299,7 +299,7 @@ func goVersionOK() bool { return true } builtVersionSemver := "v" + strings.TrimPrefix(builtVersion, "go") - if semver.Compare(builtVersionSemver, cache.GoVersionSemver) < 0 { + if semver.Compare(builtVersionSemver, sharedCache.GoVersionSemver) < 0 { fmt.Fprintf(os.Stderr, ` garble was built with %q and is being used with %q; rebuild it with a command like: garble install mvdan.cc/garble@latest @@ -428,7 +428,7 @@ func mainErr(args []string) error { } toolexecImportPath := os.Getenv("TOOLEXEC_IMPORTPATH") - curPkg = cache.ListedPackages[toolexecImportPath] + curPkg = sharedCache.ListedPackages[toolexecImportPath] if curPkg == nil { return fmt.Errorf("TOOLEXEC_IMPORTPATH not found in listed packages: %s", toolexecImportPath) } @@ -444,7 +444,7 @@ func mainErr(args []string) error { executablePath := args[0] if tool == "link" { - modifiedLinkPath, unlock, err := linker.PatchLinker(cache.GoEnv.GOROOT, cache.GoEnv.GOVERSION, sharedTempDir) + modifiedLinkPath, unlock, err := linker.PatchLinker(sharedCache.GoEnv.GOROOT, sharedCache.GoEnv.GOVERSION, sharedTempDir) if err != nil { return fmt.Errorf("cannot get modified linker: %v", err) } @@ -509,13 +509,13 @@ This command wraps "go %s". Below is its help: // Here is the only place we initialize the cache. // The sub-processes will parse it from a shared gob file. - cache = &sharedCache{} + sharedCache = &sharedCacheType{} // Note that we also need to pass build flags to 'go list', such // as -tags. - cache.ForwardBuildFlags, _ = filterForwardBuildFlags(flags) + sharedCache.ForwardBuildFlags, _ = filterForwardBuildFlags(flags) if command == "test" { - cache.ForwardBuildFlags = append(cache.ForwardBuildFlags, "-test") + sharedCache.ForwardBuildFlags = append(sharedCache.ForwardBuildFlags, "-test") } if err := fetchGoEnv(); err != nil { @@ -527,16 +527,16 @@ This command wraps "go %s". Below is its help: } var err error - cache.ExecPath, err = os.Executable() + sharedCache.ExecPath, err = os.Executable() if err != nil { return nil, err } - binaryBuildID, err := buildidOf(cache.ExecPath) + binaryBuildID, err := buildidOf(sharedCache.ExecPath) if err != nil { return nil, err } - cache.BinaryContentID = decodeHash(splitContentID(binaryBuildID)) + sharedCache.BinaryContentID = decodeHash(splitContentID(binaryBuildID)) if err := appendListedPackages(args, true); err != nil { return nil, err @@ -578,7 +578,7 @@ This command wraps "go %s". Below is its help: // We can add extra flags to the end of the same -toolexec argument. var toolexecFlag strings.Builder toolexecFlag.WriteString("-toolexec=") - quotedExecPath, err := cmdgoQuotedJoin([]string{cache.ExecPath}) + quotedExecPath, err := cmdgoQuotedJoin([]string{sharedCache.ExecPath}) if err != nil { // Can only happen if the absolute path to the garble binary contains // both single and double quotes. Seems extremely unlikely. @@ -1394,7 +1394,7 @@ func (tf *transformer) prefillObjectMaps(files []*ast.File) error { // If we do confirm this theoretical bug, // the solution will be to either find a different solution for -literals, // or to force including -ldflags into the build cache key. - ldflags, err := cmdgoQuotedSplit(flagValue(cache.ForwardBuildFlags, "-ldflags")) + ldflags, err := cmdgoQuotedSplit(flagValue(sharedCache.ForwardBuildFlags, "-ldflags")) if err != nil { return err } @@ -1953,7 +1953,7 @@ func transformLink(args []string) ([]string, error) { // Otherwise, find it in the cache. lpkg := curPkg if path != "main" { - lpkg = cache.ListedPackages[path] + lpkg = sharedCache.ListedPackages[path] } if lpkg == nil { // We couldn't find the package. @@ -2191,12 +2191,12 @@ To install Go, see: https://go.dev/doc/install `, err) return errJustExit(1) } - if err := json.Unmarshal(out, &cache.GoEnv); err != nil { + if err := json.Unmarshal(out, &sharedCache.GoEnv); err != nil { return fmt.Errorf(`cannot unmarshal from "go env -json": %w`, err) } - cache.GOGARBLE = os.Getenv("GOGARBLE") - if cache.GOGARBLE == "" { - cache.GOGARBLE = "*" // we default to obfuscating everything + sharedCache.GOGARBLE = os.Getenv("GOGARBLE") + if sharedCache.GOGARBLE == "" { + sharedCache.GOGARBLE = "*" // we default to obfuscating everything } return nil } diff --git a/reverse.go b/reverse.go index b638636..138410f 100644 --- a/reverse.go +++ b/reverse.go @@ -66,7 +66,7 @@ One can reverse a captured panic stack trace as follows: // so it's unnecessary to try to avoid this cost. var replaces []string - for _, lpkg := range cache.ListedPackages { + for _, lpkg := range sharedCache.ListedPackages { if !lpkg.ToObfuscate { continue } diff --git a/runtime_patch.go b/runtime_patch.go index d53539f..f47bf90 100644 --- a/runtime_patch.go +++ b/runtime_patch.go @@ -238,7 +238,7 @@ func stripRuntime(basename string, file *ast.File) { "printAncestorTracebackFuncInfo", "goroutineheader", "tracebackothers", "tracebackHexdump", "printCgoTraceback": funcDecl.Body.List = nil case "printOneCgoTraceback": - if semver.Compare(cache.GoVersionSemver, "v1.21") >= 0 { + if semver.Compare(sharedCache.GoVersionSemver, "v1.21") >= 0 { funcDecl.Body = ah.BlockStmt(ah.ReturnStmt(ast.NewIdent("false"))) } else { funcDecl.Body = ah.BlockStmt(ah.ReturnStmt(ah.IntLit(0))) diff --git a/shared.go b/shared.go index 54f4957..b6e3bc9 100644 --- a/shared.go +++ b/shared.go @@ -21,13 +21,13 @@ import ( //go:generate ./scripts/gen-go-std-tables.sh -// sharedCache is shared as a read-only cache between the many garble toolexec +// sharedCacheType is shared as a read-only cache between the many garble toolexec // sub-processes. // // Note that we fill this cache once from the root process in saveListedPackages, // store it into a temporary file via gob encoding, and then reuse that file // in each of the garble toolexec sub-processes. -type sharedCache struct { +type sharedCacheType struct { ExecPath string // absolute path to the garble binary being used ForwardBuildFlags []string // build flags fed to the original "garble ..." command @@ -64,11 +64,11 @@ type sharedCache struct { } } -var cache *sharedCache +var sharedCache *sharedCacheType // loadSharedCache the shared data passed from the entry garble process func loadSharedCache() error { - if cache != nil { + if sharedCache != nil { panic("shared cache loaded twice?") } startTime := time.Now() @@ -80,7 +80,7 @@ func loadSharedCache() error { log.Printf("shared cache loaded in %s from %s", debugSince(startTime), f.Name()) }() defer f.Close() - if err := gob.NewDecoder(f).Decode(&cache); err != nil { + if err := gob.NewDecoder(f).Decode(&sharedCache); err != nil { return fmt.Errorf("cannot decode shared file: %v", err) } return nil @@ -89,7 +89,7 @@ func loadSharedCache() error { // saveSharedCache creates a temporary directory to share between garble processes. // This directory also includes the gob-encoded cache global. func saveSharedCache() (string, error) { - if cache == nil { + if sharedCache == nil { panic("saving a missing cache?") } dir, err := os.MkdirTemp("", "garble-shared") @@ -97,8 +97,8 @@ func saveSharedCache() (string, error) { return "", err } - sharedCache := filepath.Join(dir, "main-cache.gob") - if err := writeGobExclusive(sharedCache, &cache); err != nil { + cachePath := filepath.Join(dir, "main-cache.gob") + if err := writeGobExclusive(cachePath, &sharedCache); err != nil { return "", err } return dir, nil @@ -220,7 +220,7 @@ func appendListedPackages(packages []string, mainBuild bool) error { args = append(args, "-deps") } args = append(args, garbleBuildFlags...) - args = append(args, cache.ForwardBuildFlags...) + args = append(args, sharedCache.ForwardBuildFlags...) if !mainBuild { // If the top-level build included the -mod or -modfile flags, @@ -251,8 +251,8 @@ func appendListedPackages(packages []string, mainBuild bool) error { } dec := json.NewDecoder(stdout) - if cache.ListedPackages == nil { - cache.ListedPackages = make(map[string]*listedPackage) + if sharedCache.ListedPackages == nil { + sharedCache.ListedPackages = make(map[string]*listedPackage) } var pkgErrors []string for dec.More() { @@ -315,7 +315,7 @@ func appendListedPackages(packages []string, mainBuild bool) error { // because some like crypto/internal/boring/fipstls simply fall under // "build constraints exclude all Go files" and can be ignored. // Real build errors will still be surfaced by `go build -toolexec` later. - if cache.ListedPackages[pkg.ImportPath] != nil { + if sharedCache.ListedPackages[pkg.ImportPath] != nil { return fmt.Errorf("duplicate package: %q", pkg.ImportPath) } if pkg.BuildID != "" { @@ -323,7 +323,7 @@ func appendListedPackages(packages []string, mainBuild bool) error { pkg.GarbleActionID = addGarbleToHash(actionID) } - cache.ListedPackages[pkg.ImportPath] = &pkg + sharedCache.ListedPackages[pkg.ImportPath] = &pkg } if err := cmd.Wait(); err != nil { @@ -334,7 +334,7 @@ func appendListedPackages(packages []string, mainBuild bool) error { } anyToObfuscate := false - for path, pkg := range cache.ListedPackages { + for path, pkg := range sharedCache.ListedPackages { // If "GOGARBLE=foo/bar", "foo/bar_test" should also match. if pkg.ForTest != "" { path = pkg.ForTest @@ -357,7 +357,7 @@ func appendListedPackages(packages []string, mainBuild bool) error { case pkg.Name == "main" && strings.HasSuffix(path, ".test"), path == "command-line-arguments", strings.HasPrefix(path, "plugin/unnamed"), - module.MatchPrefixPatterns(cache.GOGARBLE, path): + module.MatchPrefixPatterns(sharedCache.GOGARBLE, path): pkg.ToObfuscate = true anyToObfuscate = true @@ -368,8 +368,8 @@ func appendListedPackages(packages []string, mainBuild bool) error { } // Don't error if the user ran: GOGARBLE='*' garble build runtime - if !anyToObfuscate && !module.MatchPrefixPatterns(cache.GOGARBLE, "runtime") { - return fmt.Errorf("GOGARBLE=%q does not match any packages to be built", cache.GOGARBLE) + if !anyToObfuscate && !module.MatchPrefixPatterns(sharedCache.GOGARBLE, "runtime") { + return fmt.Errorf("GOGARBLE=%q does not match any packages to be built", sharedCache.GOGARBLE) } return nil @@ -394,7 +394,7 @@ func listPackage(path string) (*listedPackage, error) { path = path2 } - pkg, ok := cache.ListedPackages[path] + pkg, ok := sharedCache.ListedPackages[path] // The runtime may list any package in std, even those it doesn't depend on. // This is due to how it linkname-implements std packages, @@ -412,11 +412,11 @@ func listPackage(path string) (*listedPackage, error) { missing := make([]string, 0, len(runtimeLinknamed)) for _, linknamed := range runtimeLinknamed { switch { - case cache.ListedPackages[linknamed] != nil: + case sharedCache.ListedPackages[linknamed] != nil: // We already have it; skip. - case cache.GoEnv.GOOS != "js" && linknamed == "syscall/js": + case sharedCache.GoEnv.GOOS != "js" && linknamed == "syscall/js": // GOOS-specific package. - case cache.GoEnv.GOOS != "darwin" && linknamed == "crypto/x509/internal/macos": + case sharedCache.GoEnv.GOOS != "darwin" && linknamed == "crypto/x509/internal/macos": // GOOS-specific package. default: missing = append(missing, linknamed) @@ -426,7 +426,7 @@ func listPackage(path string) (*listedPackage, error) { if err := appendListedPackages(missing, false); err != nil { panic(err) // should never happen } - pkg, ok := cache.ListedPackages[path] + pkg, ok := sharedCache.ListedPackages[path] if !ok { panic(fmt.Sprintf("runtime listed a std package we can't find: %s", path)) } @@ -453,7 +453,7 @@ func listPackage(path string) (*listedPackage, error) { if pkg.ImportPath == "runtime" { return pkg, nil } - for _, dep := range cache.ListedPackages["runtime"].Deps { + for _, dep := range sharedCache.ListedPackages["runtime"].Deps { if dep == pkg.ImportPath { return pkg, nil }