10000 fix(go): merge nested flags into string for ldflags for Go binaries (… · aquasecurity/trivy@b675b06 · GitHub
[go: up one dir, main page]

Skip to content

Commit

Permalink
fix(go): merge nested flags into string for ldflags for Go binaries (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
DmitriyLewen authored Feb 13, 2025
1 parent f9c5043 commit b675b06
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
11 changes: 10 additions & 1 deletion pkg/dependency/parser/golang/binary/parse.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"sort"
"strings"

"github.com/mattn/go-shellwords"
"github.com/samber/lo"
"github.com/spf13/pflag"
"golang.org/x/mod/semver"
Expand Down Expand Up @@ -145,7 +146,13 @@ func (p *Parser) ldFlags(settings []debug.BuildSetting) []string {
continue
}

return strings.Fields(setting.Value)
flags, err := shellwords.Parse(setting.Value)
if err != nil {
p.logger.Error("Could not parse -ldflags found in build info", log.Err(err))
return nil
}

return flags
}
return nil
}
Expand All @@ -163,6 +170,8 @@ func (p *Parser) ParseLDFlags(name string, flags []string) string {
// to handle that edge case.
var x map[string]string
fset.StringToStringVarP(&x, "", "X", nil, "")
// Init `help` flag to avoid error in flags with `h` (e.g. `-lpthread`)
fset.BoolP("help", "h", false, "just to disable the built-in help flag")
if err := fset.Parse(flags); err != nil {
p.logger.Error("Could not parse -ldflags found in build info", log.Err(err))
return ""
Expand Down
15 changes: 15 additions & 0 deletions pkg/dependency/parser/golang/binary/parse_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -390,6 +390,21 @@ func TestParser_ParseLDFlags(t *testing.T) {
},
want: "",
},
{
name: "flag with nested flags",
args: args{
name: "github.com/k3s-io/k3s",
flags: []string{
"-X",
"github.com/k3s-io/k3s/version.Version=v1.28.6+k3s2",
"-w",
"-s",
"-extldflags",
"-static -lm -ldl -lz -lpthread",
},
},
want: "v1.28.6+k3s2",
},
{
name: "with no flags",
args: args{
Expand Down

0 comments on commit b675b06

Please sign in to comment.
0