inflate
Consume compressed bytes and write decoded bytes, preserving state across calls.
Full chapter and shared rules ↗int ZEXPORT inflate(z_streamp strm, int flush);
Consume compressed bytes and write decoded bytes, preserving state across calls.
A call uses only the input and the output room given to it. On return, look first at how far it
got, then at the return code, to decide whether to continue, supply a dictionary, stop or handle
an error. flush asks for a stopping point or a way of finishing; it is not a compression level.
A full output buffer does not mean that the stream is decoded, and running out of input does not
mean that the data is damaged.
Return values and next calls
Return type. int — zlib status code
The result distinguishes progress, completion of one stream, a dictionary request and errors; progress does not mean decoding is finished.
inflate()| Returned value | Meaning and conditions | Caller’s next step |
|---|---|---|
Z_OKProgress, not completion |
Input was consumed or output produced, but one stream is not yet complete; a requested block/header boundary can also stop the call. | Continue inflate with more input or output space as needed. |
Z_STREAM_ENDOne stream or member complete |
One stream of the selected format is complete, including enabled trailer checks; repeated calls on a completed stream also return this value. | Preserve unread trailing input; call inflateEnd, or reset before decoding the next gzip member. |
Z_NEED_DICTZlib dictionary required |
The zlib header requests a preset dictionary; strm->adler gives its identifier. | Supply the correct dictionary with inflateSetDictionary and continue after success; call inflateEnd if abandoning decoding. |
Z_BUF_ERRORRequired progress or completion unavailable |
The call made no input/output progress, or a Z_FINISH request could not complete; Z_FINISH changes an otherwise Z_OK result to this value. | Continue with input or output space as needed; this value alone does not establish corrupt data. |
Z_DATA_ERRORData error detected |
A format error or enabled checksum/length error was detected, possibly after output; the data-error state is sticky. | Abandon the current stream with inflateReset, attempt recovery with inflateSync, or call inflateEnd. |
Z_MEM_ERRORHistory-window allocation failed |
Window allocation failed; input may already have been consumed or output written, and the error state is sticky. | Observe the updated pointers and available counts; reset before starting again, or call inflateEnd. |
Z_STREAM_ERRORStream or buffer conditions failed |
A stream/buffer check failed, or an inflateSync recovery search remains unfinished. | Correct buffer arguments for a valid stream; continue inflateSync for an unfinished recovery search; otherwise establish a valid stream first. |
Calling conditions and effects
Domain Restricted domain: live streams with common buffer/header lifetimes;
arbitrary compressed bytes, input/output splits and signed flush values.
Effects Mutates stream, output and registered header storage; may allocate the history window.
Pre next_in describes avail_in readable bytes and may be NULL only when
that count is zero. next_out is non-NULL even for zero avail_out, and describes
that many writable bytes. A registered header and its buffers remain writable.
Calls may continue with more input/room, supply a requested dictionary, or follow
successful reset/recovery. Terminal/error repeats have the behavior below.
Accounting Normal returns, including data and buffer errors, update totals by
consumed/produced bytes and update the enabled output checksum. Z_NEED_DICT
accounts for consumed header bytes and leaves adler as the dictionary identifier.
A late window-allocation failure can follow input consumption and output writes:
pointers/counts already reflect them, but normal final total/checksum/data_type
accounting is skipped.
The input a call has consumed need not all belong to a valid stream: a later call can reject
the stream without consuming more input.
Ownership New window storage belongs to the stream and remains available for
reset/end, including after errors. A one-call Z_FINISH completion may need no
window. Concatenated gzip members require reset between members. Error messages
are borrowed static strings. Buffer and stream check refusals change nothing.
Proof goals.
- Goal.
Goal.inflate_safety(Safety/Streams.lean); required. Theorem:ZlibF.Spec.Public.StreamCallSafetyProof.inflate_safety(public-stream-call-safety.lean). The goal has two clauses: the refusal of a refused stream, and one call on a reachable stream.Goal.inflate_refusal(Safety/Refusals.lean), also required, states the same refusal. - Applies when. The refusal asks that
strmis a refused stream (RefusedInflate), and that the model's memory has no allocated block at or above its next unused block number (Fresh, a condition on the model, not on the caller). The call on a reachable stream asks (StreamCallDomain):strmis a reachable stream (StreamReachable);- the platform size bound holds (
ByteObjectsFit); next_inis NULL or points toavail_inreadable bytes, andnext_outis NULL or points toavail_outwritable bytes; neither range lies in the stream's own blocks, and the two ranges do not overlap (StreamBuffers);- if a header record is attached (given to
inflateGetHeader, and not detached since by a reset): the record is live and is not one of the stream's own blocks, and each of itsextra,nameandcommentpointers is NULL or points toextra_max,name_maxorcomm_maxwritable bytes outside the stream's own blocks (HeaderMemory). The goal asks this at every call, also after the header is complete; - while the gzip header is being read into that record: the
extrabuffer does not overlap the unread input, and while the extra field is read the record'sextra_lenis not below the length still to be read (InflateHeaderProgress). This is a condition on the record at the call, whoever wrote the field:inflatewritesextra_lenin the record attached to the stream, so two streams attached to one record, as afterinflateCopy, are outside the goals. Conditions 4 and 5 together areActiveHeader.
- Covered without condition. Every
flushvalue; every sequence of input bytes, well formed or not; every allocation outcome. The goal is wider than Pre:next_outmay be NULL, andnext_inmay be NULL with a nonzeroavail_in. The C refuses both withZ_STREAM_ERROR. In the refusal: every refused stream and every value of the other arguments. - Guarantees (
StreamCallSafefor the call on a reachable stream).- Returns. On a refused stream the call returns
Z_STREAM_ERROR. On a reachable stream the call returns. - State. On a reachable stream, the stream keeps its invariant (
StreamInvariant). - Writes. On a refused stream, no block that was allocated before the call (
Frame); the clause is not stated as an unchanged heap, because the translation makes and frees a local four-byte array. On a reachable stream, only the stream record, the stream's own blocks, the attached header record, theavail_outbytes atnext_out, and the header'sextra,nameandcommentbuffers (extra_max,name_maxandcomm_maxbytes). - Allocations. On a refused stream, the allocated blocks are the same as before the call (
LiveChange). On a reachable stream, the exact allocation account (LiveChange).
- Returns. On a refused stream the call returns
- Not in this goal. A stream record with
zallocandzfreeset whosestateis a garbage pointer, points to a freed state, or points to a deflate state: no goal covers this call on such a record (deviations). Which code is returned and which bytes are written: functional goalGoal.inflate(not planned; a theorem proves it).
Complete return conditions and boundaries
Post Reads/writes within the stated ranges. Advances pointers and reduces
available counts by bytes consumed/produced. In an ordinary run from init/reset,
with a valid selected format and the correct dictionary, accumulated output is a
prefix of the decoded data and equals it at Z_STREAM_END. Malformed bytes are
part of the domain: detected format or enabled checksum/length failures return
Z_DATA_ERROR, possibly after output. Incomplete input alone needs more input;
it need not be reported as a data error.
The table under Return values and next calls gives the meaning of each code and the next action.
Edges Zero input or output room is allowed. Z_BLOCK stops at a header or
block boundary; Z_TREES also stops after block descriptions. Z_FINISH changes an
otherwise Z_OK result to Z_BUF_ERROR. Other signed flush values are accepted
and behave like Z_NO_FLUSH. data_type on normal returns records unused bits,
plus 64 for the last block, 128 at a header/block boundary, and 256 after a block
header. Data and memory errors are sticky; completed streams repeat Z_STREAM_END.
Shared conditions and scope
Use an inflate stream to decode input in pieces while controlling output space. Select zlib,
gzip or raw DEFLATE at initialization, then continue with more input or room until completion,
a dictionary request or an error. inflateEnd releases the decoder after any of those outcomes.
For whole-buffer zlib decoding, see uncompress.
| Task | Entries |
|---|---|
| Start or reuse | Init, configured init, reset, new configuration, keep history |
| Decode or provide metadata | Inflate, set dictionary, read history, gzip header |
| Recover or inspect | Sync search, sync point, mark, table use |
| Adjust or branch | Prime bits, validation, distance option, copy |
| Release storage | End |
The contracts follow the pinned inflate.c with patch 0001 applied and zlib.h, in the default
LP64 Linux build, with gzip enabled and without the optional invalid-distance or strict-distance
modes. Patch 0001 changes inflateCopy only (patches).
These are focused contracts: Pre describes ordinary correct use and is deliberately narrower than
what the function accepts. Cases outside Pre that the C still handles appear under Errors or Edges.
A call outside Pre is not thereby undefined, and it need not return an error code.
See how to read a contract for the labels.
What is proved. Safety only: each call returns without undefined behaviour or a memory error, writes only what its goal names, and leaks nothing (safety). Each entry gives its goal under Proof goals, in the five items and with the fixed phrases that Reading a Proof goals paragraph defines: the goal and its theorem; the conditions under which it applies, in the order of the Lean statement; what it covers for every value; what it guarantees (returns, state, writes, allocations); and what it leaves to another goal. The proof assumes the conditions listed there, not the documentary Pre. Post, the return tables and the notes describe functional behaviour. They are read from the C, are to confirm where no theorem states them, and are not required for the safety results. Progress says which goals are done.
Common conditions
The caller and the decoder keep different things. The caller supplies the input and output buffers of each call. The decoder keeps the current parsing stage, the bits not yet used, and the history that later copies may need. Giving it a different output array does not start a new decoding task.
next_in is the start of the unread input and avail_in the number of readable bytes. next_out
is the next output position and avail_out the number of writable bytes that remain from there.
For example, a 5-byte output array that returns with 2 bytes of room has received 3 bytes. Take
those bytes first, then set the pointer and the count to the next writable region.
All contracts below have a Restricted domain. A C pointer type alone does not supply the storage, lifetime or call history required here.
- A live stream was successfully initialised or copied, has not been ended, retains its library-owned state, and is used without concurrent calls. Use the default allocator and free function. Init takes a writable, non-live stream with allocator fields set to NULL or the default functions.
- A readable or writable range has the stated capacity for the whole call. Caller ranges are separate from the stream and its owned storage. Input and output ranges do not overlap. Dictionary destinations, the registered header record and its destination buffers are separate from each other and from the stream. Registered header storage is also separate from input/output ranges on calls using it. These restrictions are part of Pre; each entry's Proof goals says which of them its goal assumes.
- The caller owns its stream object and buffers. The library owns the state and optional window. A call changes only its stream, owned storage, stated output ranges and any registered header destination. It never frees caller buffers.
- A rejected stream check returns
Z_STREAM_ERRORwithout changes, unless a query or copy contract says otherwise. This covers NULL and safely readable records rejected by the check; it does not cover dangling or arbitrary pointers. The check requires allocators, state, the state's back-pointer and a valid mode. - Counters use the C unsigned widths and wrap. No contract assumes allocation succeeds. End remains available after decoding, dictionary or allocation errors.
- The proof goals speak of a reachable stream where the contracts say live stream
(how to read a contract). A call that a goal covers extends the
stream's history: when it returns, with any code, the stream is reachable again
and the goal of the next call applies.
inflateEndends the history. - Result cells as values.
inflateGetDictionaryreports a length throughuInt *dictLength. The translation does not model that cell as memory: the function takes the cell's old value, or the fact that the pointer is NULL, and returns the new value. So the goal says nothing about the address of the cell, and a cell that overlaps another object cannot be expressed.
flowchart LR
I["Init"] --> F["inflate"]
F -->|"Z_NEED_DICT"| D["SetDictionary"] --> F
F -->|"more room or input"| F
F -->|"end or abandon"| E["End"]
F -->|"data error"| R["Reset or Sync"] --> F
Safety goal
ZlibF.Spec.Public.Goal.inflate_safety
State: done · Status of the results
/-- `int inflate(z_streamp strm, int flush)`.
**Safety of `inflate`**: a `NULL` or inconsistent stream (`RefusedInflate`) is refused with
`Z_STREAM_ERROR`; on a `Fresh` heap it writes no block that was live and leaves the live blocks as
they were (the local array it makes is freed); and on every reachable inflate stream, with the
caller's arguments as `zlib.h` asks, the call is safe (`StreamCallSafe`). -/
def Goal.inflate_safety : Prop :=
(∀ h p flush, Fresh h → RefusedInflate h p →
∃ after, C.run (Zlib.Inflate.inflate p flush) h = .ok (Z_STREAM_ERROR, after) ∧
Frame h after (fun _ => False) ∧ LiveChange h after (fun _ => False) (fun _ => False)) ∧
(∀ h r flush,
StreamCallDomain .inflate h r (.inflate (some r) flush) →
StreamCallSafe .inflate h r (.inflate (some r) flush))Related definitions and source ↗Functional contract (beyond safety)
ZlibF.Spec.Public.Goal.inflate
State: done · Status of the results
/-- `int inflate(z_streamp strm, int flush)`.
The domain is actual init/call history, not an arbitrary hand-built decoder state.
The selected LP64 platform scope explicitly requires every live represented
byte object to have at most PTRDIFF_MAX bytes (size < 2^63), including caller
storage from non-malloc origins. See docs/en/deviations.md.
Includes all signed flush arguments, progress, terminal/error modes, output bounds,
counter timing on late memory failure, caller frame and ownership of a new window.
`Z_STREAM_ERROR` is characterized exactly: a NULL output pointer, NULL input with
pending input, or a decoder left in `SYNC` by a failed `inflateSync`; such a call changes
neither the stream nor the decoder state. `Z_BUF_ERROR` means no progress, or an
unfinished `Z_FINISH` call. With input and output space available, and a flush other than
`Z_BLOCK`/`Z_TREES` (which may stop at a block boundary using only held bits), a call that
does not end, request a dictionary or fail makes progress.
The sequence target states format correctness across all input/output splits. -/
def Goal.inflate : Prop :=
∀ h r i z s flush,
StreamReachable .inflate h r → Zlib.Inflate.Spec.Good h r i z s →
ZlibF.PlatformMemory.ByteObjectsFit h →
Zlib.Inflate.Spec.DefAlloc z → StreamBuffers h r → ActiveHeader h r →
∃ rc after z' s' used out,
C.run (Zlib.Inflate.inflate (some r) flush) h = .ok (rc, after) ∧
Zlib.Inflate.Spec.Good after r i z' s' ∧ StreamAccounting z z' used out.length ∧
Bytes after z.next_out out.length out ∧
(rc = Z_OK ∨ rc = Z_STREAM_END ∨ rc = Z_NEED_DICT ∨ rc = Z_STREAM_ERROR ∨
rc = Z_DATA_ERROR ∨ rc = Z_MEM_ERROR ∨ rc = Z_BUF_ERROR) ∧
(rc = Z_OK → (used ≠ 0 ∨ out ≠ []) ∧ flush ≠ Z_FINISH) ∧
(rc = Z_STREAM_ERROR ↔
z.next_out = .null ∨ (z.next_in = .null ∧ z.avail_in ≠ 0) ∨ s.mode = SYNC) ∧
(rc = Z_STREAM_ERROR → z' = z ∧ s' = s ∧ used = 0 ∧ out = []) ∧
(rc = Z_BUF_ERROR → (used = 0 ∧ out = []) ∨ flush = Z_FINISH) ∧
(z.avail_in ≠ 0 → z.avail_out ≠ 0 → flush ≠ Z_BLOCK → flush ≠ Z_TREES →
rc = Z_BUF_ERROR → used ≠ 0 ∨ out ≠ []) ∧
(rc = Z_STREAM_END → s'.mode = DONE) ∧
(rc = Z_NEED_DICT → s'.mode = DICT) ∧
(rc = Z_DATA_ERROR → s'.mode = BAD) ∧
(rc = Z_MEM_ERROR → s'.mode = MEM ∧ z'.total_in = z.total_in ∧ z'.total_out = z.total_out) ∧
(rc = Z_OK ∨ rc = Z_STREAM_END ∨ rc = Z_DATA_ERROR ∨ rc = Z_BUF_ERROR →
z'.total_in = z.total_in + UInt64.ofNat used ∧
z'.total_out = z.total_out + UInt64.ofNat out.length) ∧
BufferFrame h after
(fun b => StreamRoot r b ∨ InflateOwned i s b ∨ s.head = some (.tab b))
(⟨z.next_out, out.length⟩ :: HeaderRegions h s.head) ∧
LiveChange h after (fun b => InflateOwned i s' b ∧ ¬ h.live b) (fun _ => False)Related definitions and source ↗