From 5a896c009ded938059f83fbf1dd64c3d1b82766a 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 c8896d5b1..078673828 100644 --- a/go/tools/builders/compilepkg.go +++ b/go/tools/builders/compilepkg.go @@ -277,14 +277,23 @@ func compileArchive( return err } - gcFlags = append(gcFlags, "-trimpath="+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, "-trimpath=.") + // 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 @@ -472,7 +481,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) }