From 9e31cf15c0007d35845737546df4a155364ec58c Mon Sep 17 00:00:00 2001 From: Radu Berinde Date: Thu, 13 Jan 2022 20:59:06 -0800 Subject: [PATCH] compilepkg: fix stored file path truncation This fixes the issue described in cockroachdb/cockroach#64379 where the internal paths of the files don't include the `github.com/cockroachdb/cockroach` prefix. We fix this by using the rewrite syntax of `-trimpath`, e.g. `-trimpath=/sandbox/execroot=>github.com/cockroachdb/cockroach`. Figuring out the replacement part is not trivial. We use the package path and strip out the relative path of the source file directory. --- go/tools/builders/compilepkg.go | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/go/tools/builders/compilepkg.go b/go/tools/builders/compilepkg.go index 990c437eed..353c244a4d 100644 --- a/go/tools/builders/compilepkg.go +++ b/go/tools/builders/compilepkg.go @@ -300,14 +300,23 @@ func compileArchive( return err } - gcFlags = append(gcFlags, createTrimPath(gcFlags, srcDir)) + gcFlags = append(gcFlags, fmt.Sprintf("-trimpath=%s=>%s", abs(srcDir), packagePath)) } else { if cgoExportHPath != "" { if err := ioutil.WriteFile(cgoExportHPath, nil, 0666); err != nil { return err } } - gcFlags = append(gcFlags, createTrimPath(gcFlags, ".")) + // We want the source files to show up (e.g. in stack traces) with the package + // path. We use -trimpath to replace the root path with the correct prefix + // of the package path. + root := abs(".") + relSrcPath, err := filepath.Rel(root, srcs.goSrcs[0].filename) + if err != nil { + return err + } + rootPkgPath := filepath.Clean(strings.TrimSuffix(packagePath, filepath.Dir(relSrcPath))) + gcFlags = append(gcFlags, fmt.Sprintf("-trimpath=%s=>%s", root, rootPkgPath)) } // Check that the filtered sources don't import anything outside of @@ -495,7 +504,7 @@ func compileGo(goenv *env, srcs []string, packagePath, importcfgPath, embedcfgPa args = append(args, "-o", outPath) args = append(args, "--") args = append(args, srcs...) - absArgs(args, []string{"-I", "-o", "-trimpath", "-importcfg"}) + absArgs(args, []string{"-I", "-o", "-importcfg"}) return goenv.runCommand(args) }