Skip to content
REFERENCE / ZLIB × LEAN

inflateSync

Search for a possible full-flush boundary after damaged input.

Full chapter and shared rules ↗
int ZEXPORT inflateSync(z_streamp strm);

Search for a possible full-flush boundary after damaged input.

Return values and next calls

Return type. int — zlib status code

The result says whether recovery search found a candidate boundary; finding the pattern does not establish correct recovered data.

inflateSync()
Returned value Meaning and conditions Caller’s next step
Z_OK
Candidate boundary found
The pattern 00 00 ff ff was found in buffered whole bytes or input; history and header registration reset while totals are preserved. Resume inflate at the following block; do not infer a valid suffix or restored validation.
Z_DATA_ERROR
Not found; search continues
The available searchable bytes did not yield the complete pattern; partial matches persist across calls. Provide more input and continue inflateSync; ordinary inflate returns Z_STREAM_ERROR while this search is unfinished.
Z_BUF_ERROR
No searchable byte available
There is no input and fewer than eight buffered bits; nothing changes. Provide more input and continue inflateSync, or abandon with inflateEnd.
Z_STREAM_ERROR
Stream check failed
The common stream check failed; nothing changes. Establish a valid stream and its ownership before further operations.

Calling conditions and effects

Domain Restricted domain: live streams after a data error or during a recovery search, with readable input.

Effects Consumes input, mutates state, may free a window.

Pre next_in and avail_in describe a readable range. Output is not used.

Proof goals.

  • Goal. Goal.inflateSync_safety (Safety/Streams.lean); required. Theorem: ZlibF.Spec.Public.StreamCallSafetyProof.inflateSync_safety (public-stream-call-safety.lean). The goal has two clauses: the refusal of a refused stream, and one call on a reachable stream.
  • Applies when. The refusal asks that strm is 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):
    1. strm is a reachable stream (StreamReachable);
    2. the platform size bound holds (ByteObjectsFit);
    3. next_in points to avail_in readable bytes outside the stream's own blocks, or is NULL with avail_in == 0 (StreamArguments).
  • Covered without condition. Every input byte sequence. Every reachable stream, in every mode: before decoding, mid-block, at stream end, and after a data or memory error. In the refusal: every refused stream.
  • Guarantees (StreamCallSafe for 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 and the stream's own blocks.
    • 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).
  • Not in this goal. A stream record with zalloc and zfree set whose state is 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 how much input is consumed: functional goal Goal.inflateSync (not planned; not done).
Complete return conditions and boundaries

Post Searches buffered whole bytes and then input for 00 00 ff ff, retaining partial matches across calls. Input pointers/counts and total_in advance by the input searched. No output is produced and total_out is preserved.

Results Z_OK means a pattern was found: history and header registration are reset, totals are preserved, decoding can resume at the following block. If no header had been read, recovery uses raw mode; otherwise it disables trailer validation. A still unknown window size becomes 15. Z_DATA_ERROR means continue searching; ordinary inflate returns Z_STREAM_ERROR during that search.

Edges No input and fewer than eight buffered bits returns Z_BUF_ERROR unchanged. A failed stream check changes nothing. A found pattern need not be a real flush point; even a sync-flush boundary can need earlier history. Recovery does not promise a valid suffix or restored checksum checking. No allocation.

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_ERROR without 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. inflateEnd ends the history.
  • Result cells as values. inflateGetDictionary reports a length through uInt *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.inflateSync_safety

State: done · Status of the results

/-- `int inflateSync(z_streamp strm)`.
**Safety of `inflateSync`**: 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.inflateSync_safety : Prop :=
  (∀ h p, Fresh h → RefusedInflate h p →
    ∃ after, C.run (Zlib.Inflate.inflateSync p) h = .ok (Z_STREAM_ERROR, after) ∧
      Frame h after (fun _ => False) ∧ LiveChange h after (fun _ => False) (fun _ => False)) ∧
  (∀ h r,
     StreamCallDomain .inflate h r (.inflateSync (some r)) →
     StreamCallSafe .inflate h r (.inflateSync (some r)))
Related definitions and source ↗

Functional contract (beyond safety)

ZlibF.Spec.Public.Goal.inflateSync

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

/-- `int inflateSync(z_streamp strm)`.
Search byte-aligned held bits before new input, retaining the partial marker match.
On success retain totals and restart at TYPE with validation disabled. -/
def Goal.inflateSync : Prop :=
  ∀ h r i z s input,
    StreamReachable .inflate h r → Zlib.Inflate.Spec.Good h r i z s →
    Zlib.Inflate.Spec.DefAlloc z → Bytes h z.next_in z.avail_in.toNat input →
    ∃ rc after z' s' used,
      C.run (Zlib.Inflate.inflateSync (some r)) h = .ok (rc, after) ∧
      Zlib.Inflate.Spec.Good after r i z' s' ∧ used ≤ input.length ∧
      z'.next_in = advance z.next_in used ∧ z'.avail_in.toNat + used = z.avail_in.toNat ∧
      z'.total_in = z.total_in + UInt64.ofNat used ∧ z'.total_out = z.total_out ∧
      (if z.avail_in = 0 ∧ s.bits.toNat < 8 then rc = Z_BUF_ERROR ∧ z' = z ∧ s' = s
       else let start := if s.mode = SYNC then s.have.toNat else
              (Api.syncSearch 0 (heldSyncBytes s)).1
            let found := Api.syncSearch start input
            used = found.2 ∧
            if found.1 = 4 then rc = Z_OK ∧ s'.mode = TYPE ∧ (s'.wrap &&& 4) = 0
            else rc = Z_DATA_ERROR ∧ s'.mode = SYNC ∧ s'.have.toNat = found.1) ∧
      Frame h after (fun b => StreamRoot r b ∨ InflateOwned i s b) ∧
      LiveChange h after (fun _ => False)
        (fun b => InflateOwned i s b ∧ ¬ InflateOwned i s' b)
Related definitions and source ↗
ZLIB × LEAN

Contents

READING NOWinflateSync