A file or connection that the function closes elsewhere is left open on a path to a return
What it finds
``go f, err := os.Open(path) if err != nil { return err } if err := check(path); err != nil { return err // f stays open } defer f.Close() ` The function closes the file on its main path, but a return before the Close, or before the defer that closes it, leaves the file open. Each such path leaks a file descriptor until the garbage collector finds the file, which a busy program may not wait for. Deferring the Close` right after the error check covers every path.
The rule follows each function through the shared IR from a call of os.Open, os.Create, os.OpenFile, os.CreateTemp, net.Dial, net.DialTimeout or net.Listen, after the branches that check its error or compare it with nil, to every return. A path ends at a call of Close on the value, a defer of one, or wherever the value is passed to a function, stored, captured, returned or assigned to another variable, since the code there may close it. Only functions that call or defer Close on the value somewhere are checked: a value never closed is the subject of file-not-closed. Functions with constructs the lowering does not understand are skipped.
From the rule's source, resource_open_on_return.rs.
package p import ( "errors" "os") func size(path string, limit int64) (int64, error) { f, err := os.Open(path) if err != nil { return 0, err } info, err := f.Stat() if err != nil { return 0, errtx0 reports: f is still open when the function returns here } if info.Size() > limit { f.Close() return 0, errors.New("too large") } f.Close() return info.Size(), nil} func deferred(path string) error { f, err := os.Open(path) if err != nil { return err } defer f.Close() _, err = f.Stat() return err} func handed(path string) (*os.File, error) { f, err := os.Open(path) if err != nil { return nil, err } if _, err := f.Stat(); err != nil { f.Close() return nil, err } return f, nil} func kept(path string) error { f, err := os.Create(path) if err != nil { return err } register(f) return nil} func register(*os.File) {} Turn it on, off or suppress it
The rule runs from the recommended tier up. To turn it on in a lower tier, give it a level in tx0.toml:
[rules]
"tx0/go:resource-open-on-return" = "warning"To keep one finding, suppress it with a reason. tx0 suppress ID --reason "..." writes the comment on the line before the code:
// tx0: ignore[tx0/go:resource-open-on-return] reason="..."tx0 explain tx0/go:resource-open-on-return shows the same in the terminal. Found a false positive? Report it.