Open fionera opened 2 months ago
This has definitely taken me by surprise on a few occasions; the question is: how often is it not a problem that the defer doesn't run? I fear such a check might be very noisy.
Below is a quick (incomplete) patch; I ran it on my set of test code and it didn't flag anything, but that's mostly libraries rather than applications, which shouldn't call os.Exit() or log.Fatal() in the first place. Also not 100% sure my patch below will actually catch all cases.
Someone should probably run this on a whole bunch of package main
applications and see what comes rolling out.
Actually I ran it wrong >_<; it does find three cases:
https://github.com/anacrolix/missinggo/blob/master/cmd/http-file-server/main.go#L48-L51
Doesn't matter as the listener is automatically closed on exit anyway.
https://github.com/performancecopilot/speed/blob/main/examples/http_counter/server.go#L33-L44
Not entirely sure what that MustStop does; might be a bug here.
Might be a bug.
IMO it's right to flag all three of these.
Still needs more testing on applications though.
I don't think we can flag this particular one as a definite mistake. The defer may be used solely to handle panics before an eventual, intended call to os.Exit. For example a CLI command function that intends to exit when it is done, but still wants to close files it opened in case the function panics before it can exit.
We might consider this in the context of #1102.
Could this may be added as check that is disabled by default? I will try to run it against our codebase (https://github.com/monogon-dev/monogon/) next week and report if it found some actual things.
We only have non-default checks for stylistic checks because they're a matter of taste and a large number of people wanted them, coming from golint. I don't want to add checks that are non-default because they have significant false positives. People are prone to blindly enabling all checks, and while a debatable stylistic warning is harmless, incorrectly pointing out a bug is not.
I tested your patch in our codebase and noticed that it doesn't complain at all since it doesn't build a full graph of the execution. I know it's not possible to do completely since interface types exist but at least for "normal" functions it would be nice to have
The following code is not executing its defer function as log.Fatal calls syscall.Exit. This can prevent cleanup functions to run and could be unexpected to some developers.