Skip to content
REFERENCE / ZLIB × LEAN

inflateInit2_

Create a decoder with a selected wrapper and window.

Full chapter and shared rules ↗
int ZEXPORT inflateInit2_(z_streamp strm, int windowBits, const char *version, int stream_size);

Create a decoder with a selected wrapper and window.

The window holds the most recent decoded bytes; length and distance references copy old content from it. "Window bits" in the table below is an exponent b that means at most 2^b bytes: 15 means 32768 bytes. windowBits also selects raw, zlib, gzip or automatic detection, by its sign or by an added constant, so the argument is not a byte count. The requests 0, 16 and 32 leave the size to the header or to the default; the table gives each meaning.

Return values and next calls

Return type. int — zlib status code

The result says whether a decoder with the requested format was created. Only successful initialization requires a later end call.

inflateInit2_()
Returned value Meaning and conditions Caller’s next step
Z_OK
Decoder created
The version and stream size match, state allocation succeeded, and windowBits was accepted. Supply input and output ranges, call inflate, then call inflateEnd when finished or abandoning decoding.
Z_VERSION_ERROR
Version or structure size mismatch
version is NULL, its first byte mismatches, or stream_size is wrong; this returns before inspecting strm and changes nothing. Correct the version and structure size before initializing again; this failed attempt needs no inflateEnd.
Z_STREAM_ERROR
Stream or window request refused
After the version check, strm is NULL; or state allocation succeeds but windowBits is invalid, so that state is freed and state becomes NULL. Provide a writable non-live stream and accepted windowBits before initializing again; this failed attempt needs no end call.
Z_MEM_ERROR
State allocation failed
State allocation failed and the old state field is retained; msg is cleared and required default allocator fields may have been installed. Initialization may be tried again when resources are available; this failure retained no new allocation and needs no inflateEnd.

Calling conditions and effects

Domain Restricted domain: fresh writable stream storage, default allocator, and NULL or readable version pointer; all signed scalar arguments.

Effects Allocates state.

Pre The stream is not live. Allocator fields follow the common convention. Only the first version byte must be readable; a whole string is not inspected.

Proof goals.

  • Goal. Goal.inflateInit2__safety (Safety/Initialisation.lean); required. Theorem: ZlibF.Spec.Public.InitSafetyProof.inflateInit2__safety (public-init-safety.lean).
  • Applies when (InitArguments):
    1. the heap is a library heap (Fresh, Uniq, LibraryGlobals);
    2. version is NULL or its first byte is readable (VersionValue);
    3. strm is NULL, or points to a readable stream record whose zalloc and zfree are each NULL or the default function (DefaultOrNull).
  • Covered without condition. Every windowBits; every stream_size; every value of the first byte of version; every value of the other fields of the record, state included; every allocation outcome. The goal is wider than Pre: it also covers a NULL strm, a wrong version or stream_size, and a record whose state is not NULL. If that record was a live stream, the call still returns, but the old state stays allocated and the record no longer points to it: the account records that leak, it does not exclude it.
  • Guarantees (InitResultSafe).
    • Returns. The call returns. With a NULL strm the code is Z_VERSION_ERROR or Z_STREAM_ERROR.
    • State. With Z_OK, strm is a reachable stream.
    • Writes. With a NULL strm, nothing: the heap is unchanged. Otherwise only the stream record and blocks the call itself allocates.
    • Allocations. With Z_OK, every block the call allocated is one of the stream's own blocks, and nothing is freed (LiveChange). With any other code the allocated blocks are the same as before the call.
  • Not in this goal. A stream whose zalloc or zfree is a custom function: outside every goal (deviations). Which code each refusal and each allocation failure returns, and the field values after the call: functional goal Goal.inflateInit2_ (not planned; a theorem proves it). That some call does return Z_OK: Goal.inflate_initialisation_domain (Safety/Domains.lean), required.
Complete return conditions and boundaries

Post On Z_OK, the stream is live with zero totals, NULL message, zero data_type, no window, history, buffered bits or header registration. Wrapper adler starts at 1 for zlib/automatic detection and 0 for gzip-only; raw preserves it. Buffer pointers and available counts are unchanged.

Accepted windowBits values are:

Values Decoder request
-15 through -8 Raw DEFLATE, window bits equal to the magnitude
0; 8 through 15 Zlib; header-selected size for 0, otherwise that maximum
16; 24 through 31 Gzip only; default size for 16, otherwise value minus 16
32; 40 through 47 Zlib/gzip detection; header/default size for 32, otherwise value minus 32

Errors NULL/wrong version first byte or wrong stream_size returns Z_VERSION_ERROR without changes, before inspecting strm. Otherwise NULL strm returns Z_STREAM_ERROR. State allocation is attempted before the window argument is checked. Failure returns Z_MEM_ERROR, retaining the old state field, with message cleared and default callbacks installed as needed. An invalid window argument after successful allocation returns Z_STREAM_ERROR, frees that state and sets state to NULL. No failing init retains a new allocation. Only successful init needs a later inflateEnd; its window may be allocated by later calls.

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

State: done · Status of the results

/-- `int inflateInit2_(z_streamp strm, int windowBits, const char *version, int stream_size)`.
**Safety of `inflateInit2_`** (macro `inflateInit2`): for every `windowBits`, every
`stream_size` and every allocation outcome, on `InitArguments` the call is safe
(`InitResultSafe`). -/
def Goal.inflateInit2__safety : Prop :=
  ∀ h strm version size wb, InitArguments h strm version →
    ∃ rc after, C.run (Zlib.Inflate.inflateInit2_ strm wb version size) h = .ok (rc, after) ∧
      InitResultSafe .inflate h after strm rc
Related definitions and source ↗

Functional contract (beyond safety)

ZlibF.Spec.Public.Goal.inflateInit2_

State: done · Status of the results

/-- `int inflateInit2_(z_streamp strm, int windowBits, const char *version, int stream_size)`.
All signed window arguments and every allocation oracle are included, in source error order. -/
def Goal.inflateInit2_ : Prop :=
  ∀ wb, InflateInitContract (fun p v size => Zlib.Inflate.inflateInit2_ p wb v size) wb
Related definitions and source ↗
ZLIB × LEAN

Contents

READING NOWinflateInit2_