Skip to content

Commit 6f44cc8

Browse files
committed
archive/zip: reduce memory held by Writer.Copy
Make a copy of the argument File's FileHeader, and pass a pointer to the copy to CreateRaw. Passing the pointer directly causes the entire `File` to be referenced by the receiver. The `File` includes a reference to the `ReaderAt` underlying the `Reader`, so all its memory, which may be the entire contents of the archive, is prevented from being garbage-collected. Also, explain the issue in the doc comment for CreateRaw. We cannot change its behavior because someone may depend on the preserving the identity of its argument pointer. For #65499. Change-Id: Ieb4963a0ea30539d597547d3511accbd8c6b5c5a Reviewed-on: https://go-review.googlesource.com/c/go/+/560238 LUCI-TryBot-Result: Go LUCI <[email protected]> Reviewed-by: Damien Neil <[email protected]>
1 parent 6076edc commit 6f44cc8

File tree

1 file changed

+8
-1
lines changed

1 file changed

+8
-1
lines changed

src/archive/zip/writer.go

+8-1
Original file line numberDiff line numberDiff line change
@@ -433,6 +433,10 @@ func writeHeader(w io.Writer, h *header) error {
433433
// [Writer.CreateHeader], [Writer.CreateRaw], or [Writer.Close].
434434
//
435435
// In contrast to [Writer.CreateHeader], the bytes passed to Writer are not compressed.
436+
//
437+
// CreateRaw's argument is stored in w. If the argument is a pointer to the embedded
438+
// [FileHeader] in a [File] obtained from a [Reader] created from in-memory data,
439+
// then w will refer to all of that memory.
436440
func (w *Writer) CreateRaw(fh *FileHeader) (io.Writer, error) {
437441
if err := w.prepare(fh); err != nil {
438442
return nil, err
@@ -471,7 +475,10 @@ func (w *Writer) Copy(f *File) error {
471475
if err != nil {
472476
return err
473477
}
474-
fw, err := w.CreateRaw(&f.FileHeader)
478+
// Copy the FileHeader so w doesn't store a pointer to the data
479+
// of f's entire archive. See #65499.
480+
fh := f.FileHeader
481+
fw, err := w.CreateRaw(&fh)
475482
if err != nil {
476483
return err
477484
}

0 commit comments

Comments
 (0)