From ddc183d91c9ec183145cd795fec185b723bd2c25 Mon Sep 17 00:00:00 2001 From: "alex.schade" <39062967+aschade92@users.noreply.github.com> Date: Mon, 7 Feb 2022 15:14:43 -0800 Subject: [PATCH] cmd/go/internal/modfetch: avoid leaking a lockedfile.File in case of write errors The go modules download command has a method called hashZip which checks the hash of a zipped directory versus an expected value, and then writes it out to a file. In the event that the write operation is not successful, we do not close the file, leading to it being leaked. This could happen if the user runs out of disk space, causing the underlying OS write command to return an error. Ultimately, this led to a panic in lockfile.OpenFile which was invoked from a finalizer garbage collecting the leaked file. The result was a stack trace that didn't show the call stack from where the write operation actually failed. Fixes issue #50858 --- src/cmd/go/internal/modfetch/fetch.go | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/src/cmd/go/internal/modfetch/fetch.go b/src/cmd/go/internal/modfetch/fetch.go index f5423b48ad..0d1d875b81 100644 --- a/src/cmd/go/internal/modfetch/fetch.go +++ b/src/cmd/go/internal/modfetch/fetch.go @@ -331,16 +331,14 @@ func hashZip(mod module.Version, zipfile, ziphashfile string) error { if err != nil { return err } + // issue 50858: lockedfile.File leaked in case of write error + defer hf.Close() if err := hf.Truncate(int64(len(hash))); err != nil { return err } if _, err := hf.WriteAt([]byte(hash), 0); err != nil { return err } - if err := hf.Close(); err != nil { - return err - } - return nil }