Skip to content

detect Close calls in helper functions that receive resp.Body#80

Open
hugowetterberg wants to merge 1 commit intotimakin:masterfrom
hugowetterberg:feature/close-helper
Open

detect Close calls in helper functions that receive resp.Body#80
hugowetterberg wants to merge 1 commit intotimakin:masterfrom
hugowetterberg:feature/close-helper

Conversation

@hugowetterberg
Copy link
Copy Markdown

When resp.Body is passed as an argument to a helper function that calls Close on that parameter, bodyclose currently reports a false positive (see #30).

This happens because isBodyProperlyHandled only checks direct referrers of the body value for Close calls, but does not follow the body into function arguments.

This change adds two methods:

  • closedViaHelper: checks if the body (or an interface-converted form of it) is passed to a function that closes it.
  • argClosedInCallee: resolves the static callee, maps the argument to the corresponding parameter, and checks if Close is called on that parameter's referrers.

This covers common patterns like:

defer safeClose("label", resp.Body)

where safeClose calls body.Close() internally, as well as patterns where the body is first converted to io.Closer or io.ReadCloser before being passed to the helper.

Test cases added for:

  • helper taking io.ReadCloser that closes it (should pass)
  • helper taking io.Closer that closes it (should pass)
  • helper taking io.ReadCloser that does NOT close it (should fail)

When resp.Body is passed as an argument to a helper function that calls
Close on that parameter, bodyclose currently reports a false positive
(see timakin#30).

This happens because isBodyProperlyHandled only checks direct referrers
of the body value for Close calls, but does not follow the body into
function arguments.

This change adds two methods:

- closedViaHelper: checks if the body (or an interface-converted form of
  it) is passed to a function that closes it.
- argClosedInCallee: resolves the static callee, maps the argument to
  the corresponding parameter, and checks if Close is called on that
  parameter's referrers.

This covers common patterns like:

    defer safeClose("label", resp.Body)

where safeClose calls body.Close() internally, as well as patterns
where the body is first converted to io.Closer or io.ReadCloser before
being passed to the helper.

Test cases added for:
- helper taking io.ReadCloser that closes it (should pass)
- helper taking io.Closer that closes it (should pass)
- helper taking io.ReadCloser that does NOT close it (should fail)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant