Skip to content
REFERENCE / ZLIB × LEAN

gzwrite

Accept len uncompressed bytes for output.

Full chapter and shared rules ↗
int ZEXPORT gzwrite(gzFile file, voidpc buf, unsigned len);

Accept len uncompressed bytes for output.

Return values and next calls

Return type. int — Accepted uncompressed byte count

The result counts bytes accepted from this call, which may still be buffered. Zero can mean either an empty request or failure.

gzwrite()
Returned value Meaning and conditions Caller’s next step
n = len > 0
All bytes accepted
All len requested bytes are buffered or compressed after any pending zero fill; len <= INT_MAX. Continue with subsequent input. Check flush or close for delayed output failure.
0 <= n < len
Stall after a prefix
A non-blocking write stalls and returns the accepted byte count, possibly zero. Confirm the stall with gzerror, handle writability, then retry only the unaccepted suffix at buf + n.
0
No requested bytes
len is zero and the handle passes the writer/error checks. No data is written and no pending seek is executed. No input needs resubmitting. The handle still needs its eventual close.
0
Request failed or refused
The handle is NULL, a reader, has a hard error, len exceeds INT_MAX, or allocation/seek/output fails. Oversized len records Z_DATA_ERROR. For a live handle, inspect gzerror before closing. A hard failure can consume a prefix despite returning zero; do not use zero as a retry offset.

Calling conditions and effects

Domain Restricted domain: writer/source; full unsigned len refusal range.

Effect: stateful write, buffering and possible allocation.

Pre For len <= INT_MAX, buf covers len readable bytes under the shared separation rules. The selected compression parameters are valid.

Proof goals.

  • Goal. Goal.gzwrite_safety (Safety/GzCalls.lean); required. Theorem: ZlibF.Spec.Public.GzCallSafetyProof.gzwrite_safety (public-gz-call-safety.lean). The goal has two clauses: the refusal of a NULL handle; one call on a handle (GzCallSafety, the call clause of the sequence goal for the calls of this function).
  • Applies when. The refusal has no condition. The call on a handle asks:
    1. file is a handle with a history (GzHistory, described under the safety goal);
    2. the argument condition (GzArguments): len > INT_MAX asks nothing; otherwise len == 0, or buf covers len readable bytes outside the handle's own blocks (GzRange).
  • Covered without condition. Every len, also 0 and above INT_MAX, and with those two every buf; every state a history can leave the handle in, reader or writer, with or without a pending error; every file-system world; every allocation outcome.
  • Guarantees.
    • Returns. On a NULL handle the call returns 0, whatever the other arguments are. On a handle the call returns, in every world.
    • State. On a handle, after a call that returned: the world is well formed, the set of open descriptors is the same (FdsKept), and the handle keeps its invariant, its mode and its descriptor (GzStepPost, GzInv).
    • Writes. On a NULL handle, nothing: the heap and the world are unchanged. On a handle, only the handle's own blocks.
    • Allocations. On a handle, the exact allocation account of the handle (LiveChange).
  • Not in this goal. The value the call returns on a handle, and the bytes, the position and the flags that result: functional goal Goal.gzwrite (not planned; not done).
Complete return conditions and boundaries

Post Normally returns len and advances position by that accepted count, after any pending zero-fill seek. Output is gzip, or unchanged bytes for T. Acceptance can leave data buffered; successful close is still required.

Errors and edges: Returns zero for NULL, reader, hard error, allocation failure or system write failure. len > INT_MAX returns zero and records Z_DATA_ERROR. A zero request does not write or execute a pending seek. A hard failure can consume a prefix despite returning zero. A would-block stall can return a short accepted count; retry the unaccepted suffix after handling the stall.

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.gzwrite_safety

State: done · Status of the results

/-- `int gzwrite(gzFile file, voidpc buf, unsigned len)`.
**Safety of `gzwrite`**: a `NULL` handle is refused with nothing changed (its clause of
`Goal.gz_refusal`); and one call on a handle of any history (`GzCallSafety`). -/
def Goal.gzwrite_safety : Prop :=
  (∀ (fs : Fs) (h : Heap) buf len, Zlib.Gzwrite.gzwrite none buf len fs h = .ok ((0, fs), h)) ∧
  GzCallSafety (fun | .gzwrite .. => True | _ => False)
Related definitions and source ↗

Functional contract (beyond safety)

ZlibF.Spec.Public.Goal.gzwrite

State: not done, not planned · Status of the results

/-- `int gzwrite(gzFile file, voidpc buf, unsigned len)`.
Requests above INT_MAX return zero. A positive result counts accepted bytes. Allocation,
descriptor and size-limit failures retain the prefix already accepted by the encoder. -/
def Goal.gzwrite : Prop :=
  (∀ h fs p n, Zlib.Gzwrite.gzwrite none p n fs h = .ok ((0, fs), h)) ∧
  (∀ h fs i s p n input, GzReachable h fs i → GzValid h i s → RegularOs fs →
    (n.toNat < 2 ^ 31 → Bytes h p n.toNat input ∧ GzRange h i s p n.toNat false) →
    ∃ rc fs' after s' accepted,
      Zlib.Gzwrite.gzwrite (some (.in_gzstate_x i)) p n fs h = .ok ((rc, fs'), after) ∧
      WriteEffect h after fs fs' i s s' (if n.toNat < 2 ^ 31 then input else []) accepted ∧
      0 ≤ rc.toInt ∧ rc.toInt ≤ (accepted : Int) ∧
      (rc ≠ 0 → rc.toInt = accepted) ∧
      (2 ^ 31 ≤ n.toNat ∨ s.mode ≠ GZ_WRITE → rc = 0) ∧
      (NoAllocationFailure h → WriterReady s → WriteRoom fs s n.toNat → n.toNat < 2 ^ 31 →
        rc.toInt = n.toNat))
Related definitions and source ↗
ZLIB × LEAN

Contents

READING NOWgzwrite