gzclose_w
Finish buffered output, release a writer and close its descriptor.
Full chapter and shared rules ↗int ZEXPORT gzclose_w(gzFile file);
Finish buffered output, release a writer and close its descriptor.
Return values and next calls
Return type. int — zlib close status code
The status reports final zero-fill/finish work and descriptor closing. Once a live writer is accepted, cleanup destroys it even if final output fails.
gzclose_w()| Returned value | Meaning and conditions | Caller’s next step |
|---|---|---|
Z_OKWriter finalized and released |
Pending zero fill, final output and descriptor close succeed. Earlier errors are not automatically returned when final work succeeds. | The handle has been destroyed. Do not query it, reuse it, or retry close. |
Z_MEM_ERRORAllocation failed during final work |
Final zero-fill or finish work reports Z_MEM_ERROR, including buffer/codec initialization or diagnostic-message allocation failure, and descriptor close does not override it. | The handle has been destroyed. Do not query it, reuse it, or retry close. Final output is not confirmed complete. |
Z_ERRNOFinal system operation failed |
Final writing fails with Z_ERRNO, or descriptor close fails. Descriptor close failure takes precedence over any earlier finalization result. | The handle has been destroyed. Do not query it, reuse it, or retry close. Handle the system failure externally; this code does not identify a reusable gzip handle. |
Z_STREAM_ERRORWriter released after finish failure |
A valid writer reaches final compression work and that work reports Z_STREAM_ERROR; descriptor close succeeds. | The handle has been destroyed. Do not query it, reuse it, or retry close. This differs from rejecting a reader before cleanup. |
Z_STREAM_ERRORNo writer was closed |
The argument is NULL or is a live reader. The reader is not destroyed. | NULL requires no cleanup. A live reader still needs exactly one gzclose_r or gzclose call. |
Calling conditions and effects
Domain Restricted domain: writer; NULL and reader refusal included.
Effect: stateful output, possible allocation, deallocation and descriptor close.
Pre A live writer meets the shared requirements and is closed once.
Proof goals.
- Goal.
Goal.gzclose_w_safety(Safety/GzCalls.lean); required. Theorem:ZlibF.Spec.Public.GzCallSafetyProof.gzclose_w_safety(public-gz-call-safety.lean). The goal has two clauses: the refusal of a NULL handle; and a close of a handle (GzCloseCallSafety, the close clause of the sequence goal for this function). - Applies when. The refusal has no condition. The close of a handle asks (no argument condition and no read budget):
fileis a handle with a history (GzHistory, described under the safety goal).
- Covered without condition. Every state a history can leave the handle in, reader or writer, with or without a pending error; every file-system world, including a system
closethat reports failure; every allocation outcome. - Guarantees.
- Returns. On a NULL handle the call returns
Z_STREAM_ERROR. On a handle the call returns, in every world. No return code is claimed for a handle. - State. On a handle that is not a writer, the call refuses: the heap and the world are unchanged, and the handle stays as it was. Otherwise the handle is gone: its record is removed, the world is well formed, the handle's descriptor, when its number is not negative, is not open after the call, also when the system
closereports failure, and every other descriptor is open exactly when it was before (GzReleased). - Writes. On a NULL handle and in a refusal, nothing: the heap and the world are unchanged. Otherwise only the handle's own blocks.
- Allocations. In a refusal, none. Otherwise exactly the handle's own blocks are freed, the record included, and nothing is allocated (
LiveChange).
- Returns. On a NULL handle the call returns
- Not in this goal. A use of the handle after the call that closed it: the history has ended, and no goal covers it. The return code, and which bytes reach the file before the close: functional goal
Goal.gzclose_w(not planned; not done).
Complete return conditions and boundaries
Post Attempts pending zero fill and Z_FINISH, then releases owned
codec state, buffers/messages/path and handle, and attempts descriptor close.
This cleanup occurs even if output fails. An unused gzip writer normally
emits an empty member; an unused transparent writer emits no payload.
Errors and edges: Returns Z_OK when final work succeeds. Seek-fill or
finish failure returns its error, including Z_MEM_ERROR, Z_ERRNO or
Z_STREAM_ERROR; descriptor close failure takes precedence as Z_ERRNO.
Earlier errors are not automatically returned if final work succeeds.
NULL or reader returns Z_STREAM_ERROR without destroying the reader.
A valid writer is destroyed even when its result is Z_STREAM_ERROR.
Shared conditions and scope
Use a gzFile handle for buffered gzip file I/O. Open acquires a file descriptor and private
state; data operations initialize buffers and codec state as needed; close releases the
handle even if final I/O fails. Reading can also accept transparent, uncompressed input: the
bytes of the file are delivered as the result without decompression.
| Task | Entries |
|---|---|
| Open or configure | Open path, open descriptor, buffer size, compression parameters |
| Read | Bytes, items, character, pushback, line |
| Write | Bytes, items, character, string, formatted text, flush |
| Position | Seek, rewind, uncompressed position, file offset |
| Inspect or clear status | EOF, transparent mode, error, clear error |
| Close | Any mode, reader, writer |
These contracts follow the pinned source with the listed patches and zlib.h.
What is proved. Safety of every history of a handle: no undefined behaviour, no memory error, no leak, and termination (the safety goal). The return values, bytes and positions described in the entries are functional behaviour. They are read from the C and are to confirm where no theorem states them. They are not a planned proof target. Progress says which goals are done.
The safety goal
Every function on this page that the default build compiles has its own required safety goal,
Goal.<function>_safety (Safety/GzCalls.lean). Its
entry states it under Proof goals. gzopen_w is Windows-only and has none. Each of these goals restricts one clause of the sequence goal
Goal.gz_sequence_safety (GzSafety.lean) to the calls
of one function. The goal of a function that takes a handle also has that function's clause of
Goal.gz_refusal, the refusal of a NULL handle. The sequence goal is required as well. It adds
the invariant clause of the table below, which is about histories and not about one call.
This section describes the sequence goal, because the entries refer to its histories, its argument conditions and its read budget. Each of these goals has a theorem of exactly its type. They are about the patched source (caveats).
Histories (GzHistory). The goal ranges over every history of one handle. A history starts
with a successful gzopen, gzopen64 or gzdopen on a well-formed heap whose byte objects have
fewer than 2^63 bytes, with its string arguments (path, mode) NUL-terminated. It continues with any of:
- a call of a non-closing gz function on the handle, with arguments as the table below asks, that returned, with any result;
- a use of the
gzgetc()macro; - a caller edit: any change to storage the handle does not own. The caller may free its own
buffers, also the buffer of its last
gzread; - a step of the outside world: the file system becomes any well-formed state. Another party may close the handle's descriptor or open another file under its number. The next read or write then gets an error or reaches the other file, as in C.
What the goal states.
| Clause | Statement |
|---|---|
| Invariant | Every history leaves a well-formed world and the handle in its invariant (GzInv). |
| No fault | The next call, in every world, does not end in undefined behaviour or a memory error. The only error it can end in is running out of loop fuel. No premise beyond the arguments. |
| Termination | The next call returns. gzread, gzfread, gzgetc, gzgetc_, gzgets and gzungetc need the read budget below for this. Every other call returns in every world. |
| Frame and ledger | A call that returns keeps the set of open descriptors, keeps GzInv, the mode and the descriptor, writes only the handle's own blocks and the caller regions named below, and changes the live blocks exactly by the handle's ledger (GzStepPost). The ledger is the allocation account (safety): every block the call allocates is owned by the handle afterwards, and every block it frees was owned by the handle before. |
gzerror |
The pointer it returns is a readable NUL-terminated string in the heap after the call. In the C it is a literal or the handle's message; the goal states only that it is a readable string. |
| Close | gzclose, gzclose_r and gzclose_w return in every world. A close of the wrong mode refuses and changes nothing. Otherwise the handle record and every owned block are freed, nothing else changes, and the descriptor is released, also when the system close fails. No return code is claimed. |
| Open | gzopen, gzopen64 and gzdopen return for every world and every allocation outcome and change no existing block. A NULL result leaves no new block; for gzopen and gzopen64 it also leaves the same open descriptors. A handle is in GzInv and owns exactly the new blocks. gzdopen opens and closes no descriptor. |
Argument conditions (GzArguments). A caller range must lie outside the blocks the handle
owns (GzOwned: the handle record, its path, its message, its buffers and its codec state).
The string gzerror returns is the handle's message. An entry that clears the error frees that
message before it touches its buffer: the writing entries do so on every call that passes their
mode and error test, the reading entries only after a stalled read
(the table). Passing the string
back can then be a use after free in the C
(deviations, rows "Gz caller buffers" and "Gz printf strings").
| Call | Condition |
|---|---|
gzread(file, buf, len) |
len > INT_MAX: none. Otherwise len == 0, or buf covers len writable bytes outside the handle's blocks. |
gzwrite(file, buf, len) |
len > INT_MAX: none. Otherwise len == 0, or buf covers len readable bytes outside the handle's blocks. |
gzfread, gzfwrite |
size * nitems >= 2^64: none. Otherwise the product is zero, or buf covers that many bytes (writable for gzfread, readable for gzfwrite) outside the handle's blocks. |
gzgets(file, buf, len) |
buf == NULL or len < 1: none. Otherwise buf covers len writable bytes outside the handle's blocks. |
gzputs(file, s) |
s is a NUL-terminated string outside the handle's blocks. |
gzprintf, gzvprintf |
On a file open for writing and not in error, the format is a NUL-terminated string and every pointer argument points into a block that is not freed. The format string and every pointer argument lie outside the handle's blocks. The vsnprintf call is defined in C, with no %n: the caller's obligation. |
gzerror(file, errnum) |
errnum is NULL or covers 4 writable bytes outside the handle's blocks. |
| every other call | none: every value of every scalar argument is covered. |
The gzprintf condition is asked at every gzprintf step. On a reader or a handle in error the
C returns before it reads the format, and the condition then asks only that the format pointer
and the pointer arguments lie outside the handle's blocks. The model does not parse the format:
every format for which the vsnprintf call is defined in C and whose arguments are integers or
strings is covered, with the h and hh modifiers and * widths. The model's argument type
(VaArg) has no floating-point or void * case, so floating conversions and %p are not
covered. %n is not covered: with %n the call writes caller memory, which the frame of the
conclusion does not describe, so the caller's obligation excludes it. A format that
does not match its arguments is not covered either, and the model does not detect one
(deviations, row "Gz printf call").
Read budget (ReadsFinite). The termination clause for the six reading calls assumes that
the handle's descriptor can still deliver fewer than 2^61 bytes. The premise is needed: a
source that delivers empty gzip members forever keeps one gzread running forever in C. It goes
by call name, so it is asked also where the C returns at once, for example on a writer or for a
length of zero. 2^61 is the model's figure, not zlib's: it keeps the loop measures below the
2^64 iterations of loop fuel (safety). The premise also
says that the descriptor number is not negative (HasBudget); every handle the library returns
has such a number, because gzdopen returns NULL for a negative descriptor. The no-fault
clause and the frame and ledger clause do not use the premise.
The gzgetc macro. zlib.h defines gzgetc as a macro, which is how an application
normally calls it. The goal has a separate clause for the macro (Zlib.ZlibH.gzgetc). With
buffered output (have != 0) the macro takes a byte from the buffer with no library call, and
returns with no premise. With have == 0 it calls the function gzgetc, and returns under the
read budget. Its frame and ledger are those of the function, which writes no caller region. The
macro on a NULL handle reads file->have and is undefined in C; only the function refuses NULL.
Zero-length reads name no region. For gzread with len == 0 and gzfread with a zero
product, the frame names no caller region (GzWriteRegions), and buf may be any pointer, also
one into a block that the call frees. A frame that named buf would be false there.
gzgets names len bytes at buf when len >= 1, and gzerror names 4 bytes at errnum.
NULL handle and non-vacuity. Goal.gz_refusal
(GzRefusal.lean) states that every gz function
that takes a handle returns its documented value on NULL, with the heap and the world unchanged.
The own goal of each such function repeats its clause. Goal.gz_sequence_nonvacuity shows that the premises can be met: a gzopen reader with a finite
read budget and a one-byte gzread, and a gzdopen writer and a one-byte gzwrite.
Functional contracts. The per-function goals Goal.gzread, Goal.gzwrite and the others
state which bytes are read and written and which values are returned. They are stated for a
regular file with no outside interference (RegularOs) and rest on a hand-made model of the file
system. They are not planned. Each entry says whether a theorem proves its functional goal.
Common handle conditions
There are two positions. The logical position counts uncompressed bytes; ordinary reads and writes advance it by the amount consumed or accepted, and a seek can also record a forward move that is not yet carried out. The underlying file has a physical offset, which counts bytes of the file. gztell queries the first. gzoffset reports the second, less the compressed input that a reader has read from the file but not yet used. The library reads ahead and buffers, so the two values usually differ; a compression ratio cannot convert one into the other.
For example, with no seek and no pushback, a reader that has delivered 1000 decompressed bytes to the application has logical position 1000; to produce them it may already have read compressed bytes that lie further on. In the other direction, a successful write means that the library accepted the input; it does not show that all of those bytes were written to the descriptor.
The arguments below use these units: len and the buffer configuration size count bytes; in the item interfaces size is the number of bytes of one item and nitems the number of items, so the total request is size * nitems bytes. offset is a signed displacement in uncompressed bytes; whence says whether it is taken from the start (SEEK_SET) or from the current position (SEEK_CUR). INT_MAX is the largest value of a signed int in this build, 2^31 - 1.
This page keeps a non-blocking stall apart from a hard error. After a stall the next data call can retry directly. A hard error is a recorded error that a stall did not leave and that makes later data calls fail, for a reader once its buffered bytes are used up: any code for a writer, any code other than Z_BUF_ERROR (truncation) for a reader. The distinction says how the call returns; it does not remove the requirements on state, retry and cleanup after an error.
This page uses the default x86_64 Linux build. int and unsigned have
32 bits. long, z_off_t, z_off64_t and z_size_t have 64 bits.
The large-file declarations are enabled. Plain and *64 entry points have
the same offset range here. Other configurations need separate contracts.
gzopen_w is a Windows-only entry and is scoped separately below.
Restricted domain means ordinary use with these common requirements:
- A non-NULL handle is live, returned by a successful open, and not closed. It is used serially and its private state is not modified by the caller.
- A reader or writer has the access mode named by the entry. NULL and wrong-mode refusals are documented separately. A stale or arbitrary pointer is outside this domain; checking a mode field does not validate a pointer.
- Buffers cover the requested readable or writable extent. They are separate from handle-owned memory. Strings have a readable terminating NUL. The caller retains ownership of these objects.
- Position arithmetic and requested extents are representable in the stated C types. Explicit oversized-request and multiplication-overflow refusals remain part of the contracts below.
- The descriptor belongs to the handle until close. No other operation changes its data or position during a call. OS failures and allocation failures remain possible; a successful open does not guarantee that later I/O succeeds. The first two sentences are conditions of the functional contracts only. The safety goal lets the outside world change any descriptor between calls.
Every entry carries a domain label. “Full scalar range” applies only to the named scalar argument, under these pointer and lifetime requirements. Partial-read errors and negative positions created by pushback are inside the safety goal.
Effects. Read, write, open, seek, control and close operations are stateful,
including operations without a caller output buffer. Tell, offset and EOF
queries read state; gzerror may also write its optional code output.
gzdirect can read the file and allocate, so it is stateful.
stateDiagram-v2
[*] --> Fresh: successful open
Fresh --> Active: first I/O or format inspection
Active --> Active: read, write, seek, control
Fresh --> Closed: close
Active --> Closed: close, including final I/O failure
Closed --> [*]
Format and buffering. Opening does no payload I/O. Buffers and codec state
are allocated lazily, with a default requested buffer size of 8192 bytes.
The requested size is a configuration value; the internal storage also includes the doubled
buffers described under gzbuffer and the codec state.
Allocation can fail at first use or later in decompression. Closing releases
owned allocations even when final I/O fails.
An ordinary reader detects gzip from a plausible four-byte header; otherwise
it returns the input unchanged. Empty input is transparent. Detection waits
when non-blocking input stalls before four bytes are available. A gzip member
is one complete stream with its own header, compressed data and trailer with check
values; a file can hold several members one after another. The uncompressed data of
the members is concatenated in order in the output. Trailing non-member data is ignored when the
attempted following member produces no output before its format error.
G requires gzip; T selects transparent output and is invalid for reading.
Read results. Reads advance the uncompressed position by bytes consumed,
including a final partial item. Buffered bytes can be returned before a
recorded error is reported. gzeof reports an attempted read beyond available
data, not simply the delivery of the final byte. gzerror distinguishes EOF,
corruption (Z_DATA_ERROR), truncation (Z_BUF_ERROR), allocation failure
(Z_MEM_ERROR) and system failure (Z_ERRNO). Zero-length reads do not consume
input or carry out a pending seek.
Write results. Success means input was accepted by the handle. It can still be buffered. Flush or close can fail later. A hard error can return failure after consuming a prefix; the return value alone is not always a retry offset. A non-blocking stall can instead return the number consumed so far.
Errors normally persist until cleared. A recorded would-block condition permits
the next data I/O call to retry. Seek and rewind still refuse that recorded
Z_ERRNO. Constructing an error message can itself fail and replace the code
with Z_MEM_ERROR. errno is meaningful for the associated system failure,
not as a general explanation of every failed API call.
What a retry or a recovery yields after a partial read, after a parameter change that the compressor did not apply, or after a failed finish (which bytes reach the file, which position is reported) is functional behaviour. It is to confirm. That the next call is safe, after any call that returned with any result, is part of the safety goal.
The source is gzlib.c,
gzread.c, gzwrite.c,
gzclose.c and zlib.h.
The sequence safety goal is Goal.gz_sequence_safety
(GzSafety), the safety goal of each function is
Goal.<function>_safety (GzCalls) and the
NULL-handle goal is Goal.gz_refusal (GzRefusal).
The abstract contracts are the relations over the abstract handle GzHandle
(Functional/Api/Gz.lean).
The functional goals are Goal.<function>
(GzOpen,
GzRead,
GzWrite,
GzControl,
GzClose).
Safety goal
ZlibF.Spec.Public.Goal.gzclose_w_safety
State: done · Status of the results
/-- `int gzclose_w(gzFile file)`.
**Safety of `gzclose_w`**: a `NULL` handle is refused with nothing changed (its clause of
`Goal.gz_refusal`); and it returns on a handle of any history, and either refuses on the wrong mode
with nothing changed or frees every owned block and releases the descriptor (`GzCloseCallSafety`). -/
def Goal.gzclose_w_safety : Prop :=
(∀ (fs : Fs) (h : Heap), Zlib.Gzwrite.gzclose_w none fs h = .ok ((Z_STREAM_ERROR, fs), h)) ∧
GzCloseCallSafety (fun | .gzclose_w .. => True | _ => False)Related definitions and source ↗Functional contract (beyond safety)
ZlibF.Spec.Public.Goal.gzclose_w
State: not done, not planned · Status of the results
/-- `int gzclose_w(gzFile file)`.
Reject a reader without closing it. Complete pending zeros and the final member, then release
all storage and close the descriptor, including every error path. -/
def Goal.gzclose_w : Prop := CloseContract Zlib.Gzwrite.gzclose_w (some GZ_WRITE)Related definitions and source ↗