cockroachdb / cockroachdb/cockroach

File descriptor leak on early return in updateCmdFunc (late defer after Chmod)

Open
#164,231 3 comments 0 reactions 0 assignees View on GitHub
autosolve C-bug O-community T-testeng
Dominant language
Go
Stars
32.5k
Forks
4.1k
PR merge metrics
PR metrics pending

Description

In pkg/cmd/roachprod/cli/update.go (function updateCmdFunc), a file descriptor can be leaked due to a defer being registered after a possible early return.

The file is opened:

f, err := os.Create(toFile)

There is an early return path before defer f.Close() is registered:

return errors.Wrap(err, "unable to chmod destination file: %q", toFile)

The defer f.Close() call is placed after the Chmod check. If Chmod fails, the function returns before the defer is registered, and f is not closed.

To Reproduce

Code pattern:

f, err := os.Create(toFile)
if err != nil {
return err
}

if err := f.Chmod(0700); err != nil {
return errors.Wrap(err, "unable to chmod destination file: %q", toFile)
}

defer f.Close()

If f.Chmod returns an error, the function exits before defer f.Close() is registered, leaking the file descriptor.

Expected behavior

The file descriptor should be closed on all return paths.

Specifically, the defer f.Close() should be registered immediately after the successful os.Create, before any subsequent operations that may return.

For example:

f, err := os.Create(toFile)
if err != nil {
return err
}
defer f.Close()

if err := f.Chmod(0700); err != nil {
return errors.Wrap(err, "unable to chmod destination file: %q", toFile)
}

Additional data

This is a static code path issue. No runtime logs required.

Jira issue: CRDB-60701

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.