feat(go): fix parsing main module version for go >= 1.24 (#8433)

Signed-off-by: maksim.nabokikh <max.nabokih@gmail.com>
Co-authored-by: DmitriyLewen <91113035+DmitriyLewen@users.noreply.github.com>
This commit is contained in:
Maksim Nabokikh
2025-02-24 12:22:13 +01:00
committed by GitHub
parent 9c609c44a3
commit e58dcfcf9f
2 changed files with 37 additions and 2 deletions

View File

@@ -1,7 +1,6 @@
package binary
import (
"cmp"
"debug/buildinfo"
"fmt"
"runtime/debug"
@@ -104,7 +103,13 @@ func (p *Parser) Parse(r xio.ReadSeekerAt) ([]ftypes.Package, []ftypes.Dependenc
// set via `go build -ldflags='-X main.version=<semver>'`, so we fallback to this as.
// as a secondary source.
// See https://github.com/aquasecurity/trivy/issues/1837#issuecomment-1832523477.
version := cmp.Or(p.checkVersion(info.Main.Path, info.Main.Version), p.ParseLDFlags(info.Main.Path, ldflags))
version := p.checkVersion(info.Main.Path, info.Main.Version)
ldflagsVersion := p.ParseLDFlags(info.Main.Path, ldflags)
if version == "" || (strings.HasPrefix(version, "v0.0.0") && ldflagsVersion != "") {
version = ldflagsVersion
}
root := ftypes.Package{
ID: dependency.ID(ftypes.GoBinary, info.Main.Path, version),
Name: info.Main.Path,

View File

@@ -168,6 +168,36 @@ func TestParse(t *testing.T) {
},
},
},
/*
Uncomment the test after migrating to autogenerated binaries for tests
See for details: https://github.com/aquasecurity/trivy/pull/8433#discussion_r1967317284
{
name: "with -ldflags=\"-X main.version=v1.0.0\" go v1.24",
inputFile: "testdata/main-version-via-ldflags-go-1-24.elf",
wantPkgs: []ftypes.Package{
{
ID: "github.com/aquasecurity/test@v1.0.0",
Name: "github.com/aquasecurity/test",
Version: "v1.0.0",
Relationship: ftypes.RelationshipRoot,
},
{
ID: "stdlib@v1.24.0",
Name: "stdlib",
Version: "v1.24.0",
Relationship: ftypes.RelationshipDirect,
},
},
wantDeps: []ftypes.Dependency{
{
ID: "github.com/aquasecurity/test@v1.0.0",
DependsOn: []string{
"stdlib@v1.24.0",
},
},
},
},
*/
{
name: "goexperiment",
inputFile: "testdata/goexperiment",