Skip to content

Commit a4cbd6a

Browse files
authored
fix: close file descriptors and pipes on error paths (#9536)
Co-authored-by: knqyf263 <[email protected]>
1 parent eba48af commit a4cbd6a

File tree

2 files changed

+23
-3
lines changed

2 files changed

+23
-3
lines changed

pkg/fanal/artifact/vm/file.go

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,12 +35,19 @@ type ImageFile struct {
3535
reader *io.SectionReader
3636
}
3737

38-
func newFile(filePath string, storage Storage) (*ImageFile, error) {
38+
func newFile(filePath string, storage Storage) (imgFile *ImageFile, err error) {
3939
f, err := os.Open(filePath)
4040
if err != nil {
4141
return nil, xerrors.Errorf("file open error: %w", err)
4242
}
4343

44+
// Close file on error
45+
defer func() {
46+
if err != nil && f != nil {
47+
f.Close()
48+
}
49+
}()
50+
4451
c, err := lru.New[string, []byte](storageFILECacheSize)
4552
if err != nil {
4653
return nil, xerrors.Errorf("failed to create new lru cache: %w", err)

pkg/flag/options.go

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -579,10 +579,23 @@ func (o *Options) GetUsedFlags() []Flagger {
579579
return o.usedFlags
580580
}
581581

582-
func (o *Options) outputPluginWriter(ctx context.Context) (io.Writer, func() error, error) {
582+
func (o *Options) outputPluginWriter(ctx context.Context) (writer io.Writer, cleanup func() error, err error) {
583583
pluginName := strings.TrimPrefix(o.Output, "plugin=")
584584

585585
pr, pw := io.Pipe()
586+
587+
// Close pipes on error
588+
defer func() {
589+
if err != nil {
590+
if pr != nil {
591+
pr.Close()
592+
}
593+
if pw != nil {
594+
pw.Close()
595+
}
596+
}
597+
}()
598+
586599
wait, err := plugin.Start(ctx, pluginName, plugin.Options{
587600
Args: o.OutputPluginArgs,
588601
Stdin: pr,
@@ -591,7 +604,7 @@ func (o *Options) outputPluginWriter(ctx context.Context) (io.Writer, func() err
591604
return nil, nil, xerrors.Errorf("plugin start: %w", err)
592605
}
593606

594-
cleanup := func() error {
607+
cleanup = func() error {
595608
if err = pw.Close(); err != nil {
596609
return xerrors.Errorf("failed to close pipe: %w", err)
597610
}

0 commit comments

Comments
 (0)