fix: close file descriptors and pipes on error paths (#9536)

Co-authored-by: knqyf263 <knqyf263@users.noreply.github.com>
This commit is contained in:
Teppei Fukuda
2025-09-26 16:31:59 +04:00
committed by GitHub
parent eba48afd58
commit a4cbd6a138
2 changed files with 23 additions and 3 deletions

View File

@@ -35,12 +35,19 @@ type ImageFile struct {
reader *io.SectionReader
}
func newFile(filePath string, storage Storage) (*ImageFile, error) {
func newFile(filePath string, storage Storage) (imgFile *ImageFile, err error) {
f, err := os.Open(filePath)
if err != nil {
return nil, xerrors.Errorf("file open error: %w", err)
}
// Close file on error
defer func() {
if err != nil && f != nil {
f.Close()
}
}()
c, err := lru.New[string, []byte](storageFILECacheSize)
if err != nil {
return nil, xerrors.Errorf("failed to create new lru cache: %w", err)

View File

@@ -579,10 +579,23 @@ func (o *Options) GetUsedFlags() []Flagger {
return o.usedFlags
}
func (o *Options) outputPluginWriter(ctx context.Context) (io.Writer, func() error, error) {
func (o *Options) outputPluginWriter(ctx context.Context) (writer io.Writer, cleanup func() error, err error) {
pluginName := strings.TrimPrefix(o.Output, "plugin=")
pr, pw := io.Pipe()
// Close pipes on error
defer func() {
if err != nil {
if pr != nil {
pr.Close()
}
if pw != nil {
pw.Close()
}
}
}()
wait, err := plugin.Start(ctx, pluginName, plugin.Options{
Args: o.OutputPluginArgs,
Stdin: pr,
@@ -591,7 +604,7 @@ func (o *Options) outputPluginWriter(ctx context.Context) (io.Writer, func() err
return nil, nil, xerrors.Errorf("plugin start: %w", err)
}
cleanup := func() error {
cleanup = func() error {
if err = pw.Close(); err != nil {
return xerrors.Errorf("failed to close pipe: %w", err)
}