inflateCopy
Create a decoder that can resume from the source position.
Full chapter and shared rules ↗int ZEXPORT inflateCopy(z_streamp dest, z_streamp source);
Create a decoder that can resume from the source position.
Return values and next calls
Return type. int — zlib status code
The result says whether the destination acquired an independently endable decoder copy.
inflateCopy()| Returned value | Meaning and conditions | Caller’s next step |
|---|---|---|
Z_OKDecoder state copied |
The valid source was copied to a distinct non-live destination; the destination owns independent state and any required window, and the source is unchanged. | Eventually call inflateEnd on both streams; provide separate writable destinations before continuing and preserve shared pointer lifetimes. |
Z_STREAM_ERRORCopy request refused |
dest is NULL or the source stream check failed; a non-NULL dest has state cleared and other fields unchanged, and the source is unchanged. | Correct source and destination before copying again; this failure created no destination stream requiring end. |
Z_MEM_ERRORCopy allocation failed |
State or window allocation failed; all allocations from this attempt are freed, destination state is NULL, and source is unchanged. | Copy may be tried again when resources are available; the failed destination needs no inflateEnd, while the source still needs normal cleanup. |
Calling conditions and effects
Domain Restricted domain: live source, distinct writable non-live destination.
Effects Allocates independent state and, if present, a window.
Pre The common conditions hold for source. Destination does not overlap source or its owned storage. Shared input/output and header pointers retain their caller lifetimes; give the streams separate writable destinations before use.
Proof goals.
- Goal.
Goal.inflateCopy_safety(Safety/Copy.lean); required. Theorem:ZlibF.Spec.Public.InflateCopySafetyProof.inflateCopy_safety(public-inflate-copy-safety.lean). The goal has four clauses: the refusal of a NULLdest; the refusal of a NULLsource; the copy from a reachable source (the main clause); the refusal of asourcethat is a refused stream.Goal.inflate_refusal(Safety/Refusals.lean), also required, states the refusal of a refused source too. - Applies when. The refusal of a NULL
desthas no condition. The refusal of a NULLsourceasks thatdestpoints to a readable stream record. The refusal of a refusedsourceasks thatdestpoints to a readable stream record, and thatsourceis not NULL and is a refused stream (RefusedInflate); it does not ask thatdestandsourcediffer. The main clause asks:sourceis a reachable stream (StreamReachable). The statement also takes its invariant and default allocator as hypotheses (Good,DefAlloc); every reachable stream has them (Goal.inflate_sequence_safety, first clause);destpoints to a readable stream record that is not thesourcerecord (source ≠ dest). The platform size bound is not asked.
- Covered without condition. Every content of the
destrecord; every allocation outcome. In the refusals: every content of thedestrecord, every refusedsource, and, whendestis NULL, everysourcepointer. The goal is wider than Pre:destmay be a live stream; its old state then stays allocated and the record no longer points to it. - Guarantees.
- Returns. With a NULL
dest, a NULLsourceor a refusedsource, the call returnsZ_STREAM_ERROR. From a reachable source the call returns, withZ_OKorZ_MEM_ERROR.Z_MEM_ERRORis returned only after an allocation failed (AllocationFailed). - State. From a reachable source: the
sourcerecord and its state are unchanged. WithZ_OK,destis a reachable stream. WithZ_MEM_ERROR,dest->stateis NULL and the other fields ofdestare unchanged. - Writes. With a NULL
dest, nothing: the heap is unchanged. With a NULL or refusedsource, onlydest->state, which is set to NULL; the other fields ofdestand the rest of the heap are unchanged. From a reachable source, only thedestrecord and blocks the call itself allocates. - Allocations. In the three refusals nothing is allocated and nothing is freed. From a reachable source: with
Z_OK, the new blocks are exactly the blocks of the new state record: the record itself and its window, when it has one. Nothing is freed. The safety goal does not say thatdest->statepoints to this record; the functional goalGoal.inflateCopydoes. WithZ_MEM_ERRORthe allocated blocks are the same as before the call.
- Returns. With a NULL
- Not in this goal. A
sourcerecord withzallocandzfreeset whosestateis a garbage pointer, points to a freed state, or points to a deflate state: no goal covers a copy from such a source (deviations).dest == sourcewith a reachable source: no goal covers this call (deviations, row "Copy destination"). What the copy contains: functional goalGoal.inflateCopy(not planned; a theorem proves it).
Complete return conditions and boundaries
Post Z_OK copies decoding position, history and stream fields. Both streams
own their state/window independently and must be ended. Source is unchanged.
Caller buffer pointers, message and any registered header pointer are shared,
not deep-copied. No caller data is consumed or produced.
Errors NULL dest returns Z_STREAM_ERROR. For other refusals, non-NULL
dest has state cleared and is otherwise unchanged. Allocation failure returns
Z_MEM_ERROR and frees all allocations made by this attempt. Source is unchanged.
Edges dest == source with a live source is outside this contract. The C then copies the
record onto itself with zmemcpy(dest, source, sizeof(z_stream)), which is undefined behaviour,
and afterwards sets dest->state to the new state. To confirm: nothing then points to the
original state.
With a refused source the C returns Z_STREAM_ERROR before the copy, as in any other refusal.
The unpatched C compares unrelated pointers in this function; patch 0001 replaces
the comparison (patches).
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.inflateCopy_safety
State: done · Status of the results
/-- `int inflateCopy(z_streamp dest, z_streamp source)`.
**Safety of `inflateCopy`** (the safety content of `Goal.inflateCopy`). Null arguments are
refused. From every reachable source into a distinct, readable destination record, the call
returns without a fault, with `Z_OK` or `Z_MEM_ERROR`. It leaves the source record and its state
unchanged and writes only the destination record and new blocks. On `Z_MEM_ERROR` an allocation
really failed, the destination state is cleared and the live blocks are unchanged (no leak). On
`Z_OK` the destination is a reachable stream (`StreamReachable.inflateCopy`) and the live blocks
grow by exactly the fresh blocks its new state owns. The copied contents are left to
`Goal.inflateCopy`. The last clause is zlib.h's refusal of an inconsistent source: a source the state
check refuses (`RefusedInflate`) is refused with `Z_STREAM_ERROR`, and the destination state is
cleared (as in `Goal.inflate_refusal`). -/
def Goal.inflateCopy_safety : Prop :=
(∀ h source, C.run (Zlib.Inflate.inflateCopy none source) h = .ok (Z_STREAM_ERROR, h)) ∧
(∀ h dest z, dest.get h = some z →
C.run (Zlib.Inflate.inflateCopy (some dest) none) h =
.ok (Z_STREAM_ERROR, dest.put h { z with state := none })) ∧
(∀ h source i z s dest oldDest,
StreamReachable .inflate h source → Zlib.Inflate.Spec.Good h source i z s →
Zlib.Inflate.Spec.DefAlloc z → source ≠ dest → dest.get h = some oldDest →
∃ rc after,
C.run (Zlib.Inflate.inflateCopy (some dest) (some source)) h = .ok (rc, after) ∧
source.get after = some z ∧ after.istates i = some s ∧ Frame h after (StreamRoot dest) ∧
((rc = Z_MEM_ERROR ∧ AllocationFailed h after ∧
dest.get after = some { oldDest with state := none } ∧
LiveChange h after (fun _ => False) (fun _ => False)) ∨
(rc = Z_OK ∧ StreamReachable .inflate after dest ∧
∃ copied, after.istates h.nextBlk = some copied ∧
(∀ b, InflateOwned h.nextBlk copied b → h.nextBlk ≤ b) ∧
LiveChange h after (InflateOwned h.nextBlk copied) (fun _ => False)))) ∧
(∀ h source dest oldDest, dest.get h = some oldDest → RefusedInflate h (some source) →
C.run (Zlib.Inflate.inflateCopy (some dest) (some source)) h =
.ok (Z_STREAM_ERROR, dest.put h { oldDest with state := none }))Related definitions and source ↗Functional contract (beyond safety)
ZlibF.Spec.Public.Goal.inflateCopy
State: done · Status of the results
/-- `int inflateCopy(z_streamp dest, z_streamp source)`.
Copy every decoder field, relocate internal table pointers, share application header pointers,
and copy the initialized window bytes. All new storage is independent; failure releases it. -/
def Goal.inflateCopy : Prop :=
(∀ h source, C.run (Zlib.Inflate.inflateCopy none source) h = .ok (Z_STREAM_ERROR, h)) ∧
(∀ h dest z, dest.get h = some z →
C.run (Zlib.Inflate.inflateCopy (some dest) none) h =
.ok (Z_STREAM_ERROR, dest.put h { z with state := none })) ∧
(∀ h source i z s dest oldDest,
StreamReachable .inflate h source → Zlib.Inflate.Spec.Good h source i z s →
Zlib.Inflate.Spec.DefAlloc z → source ≠ dest → dest.get h = some oldDest →
∃ rc after,
C.run (Zlib.Inflate.inflateCopy (some dest) (some source)) h = .ok (rc, after) ∧
source.get after = some z ∧ after.istates i = some s ∧ Frame h after (StreamRoot dest) ∧
((rc = Z_MEM_ERROR ∧ AllocationFailed h after ∧
dest.get after = some { oldDest with state := none } ∧
LiveChange h after (fun _ => False) (fun _ => False)) ∨
(rc = Z_OK ∧ ∃ copied,
Zlib.Inflate.Spec.Good after dest h.nextBlk
{ z with state := some (.inflate h.nextBlk) } copied ∧
copied = { s with
strm := some dest, window := copied.window
lencode := relocateCode i h.nextBlk s.lencode
distcode := relocateCode i h.nextBlk s.distcode
next := relocateCode i h.nextBlk s.next } ∧
(s.window = .null ↔ copied.window = .null) ∧
(s.window ≠ .null → SameBytePrefix h after s.window copied.window s.whave.toNat) ∧
(∀ b, InflateOwned h.nextBlk copied b → h.nextBlk ≤ b) ∧
LiveChange h after (InflateOwned h.nextBlk copied) (fun _ => False))))Related definitions and source ↗