gzoffset64
Query the underlying physical file offset.
Full chapter and shared rules ↗z_off64_t ZEXPORT gzoffset64(gzFile file);
Query the underlying physical file offset.
Return values and next calls
Return type. z_off64_t — Physical file offset, or failure sentinel
The result is the descriptor's current position, less unused compressed input when reading. This physical quantity is not the count of uncompressed bytes delivered.
gzoffset64()| Returned value | Meaning and conditions | Caller’s next step |
|---|---|---|
offset != -1Physical file offset value |
The valid handle's system position query succeeds and offset arithmetic is representable; held unused compressed input is subtracted for a reader. | Use it as a physical offset; the query does not move the descriptor, flush writer buffers or execute a pending logical seek. |
-1Physical offset unavailable |
NULL, wrong mode, a failed system position query, including a nonseekable descriptor, or a negative result of that query. | Check the handle and descriptor seekability; inspect the associated errno for a system failure, without assuming gzerror records this query failure. |
Calling conditions and effects
Domain Restricted domain: live reader/writer and descriptor environment.
Effect: read-only handle query and system position query; errno may change.
Pre The shared requirements hold. Successful offset arithmetic is representable.
Proof goals.
- Goal.
Goal.gzoffset64_safety(Safety/GzCalls.lean); required. Theorem:ZlibF.Spec.Public.GzCallSafetyProof.gzoffset64_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 (this call has no argument condition):
fileis a handle with a history (GzHistory, described under the safety goal).
- Covered without condition. Every state a history can leave the handle in, reader or writer, with or without a pending error; every file-system world.
- Guarantees.
- Returns. On a NULL handle the call returns
-1. 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).
- Returns. On a NULL handle the call returns
- 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.gzoffset64(not planned; a theorem proves it).
Complete return conditions and boundaries
Post Returns the descriptor's current position, subtracting unused compressed input held by a reader. Does not flush buffered writer data or execute a pending logical seek. It does not change the descriptor position.
Errors and edges: Returns -1 for NULL, wrong mode or failed system query,
including a nonseekable descriptor, and for every negative result of that query
(patch 0005; the unpatched C overflowed on some of them, see
caveats). It differs from uncompressed position.
A transparent reader's unread output buffer is not subtracted, so the result
can be ahead of bytes already delivered. It includes any existing prefix
before a gzdopen handle's initial offset.
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.gzoffset64_safety
State: done · Status of the results
/-- `z_off64_t gzoffset64(gzFile)`.
**Safety of `gzoffset64`**: 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.gzoffset64_safety : Prop :=
(∀ (fs : Fs) (h : Heap), Zlib.Gzlib.gzoffset64 none fs h = .ok ((-1, fs), h)) ∧
GzCallSafety (fun | .gzoffset64 .. => True | _ => False)Related definitions and source ↗Functional contract (beyond safety)
ZlibF.Spec.Public.Goal.gzoffset64
State: done · Status of the results
/-- `z_off64_t gzoffset64(gzFile file)`.
The physical descriptor position excludes compressed input already buffered by a reader. -/
def Goal.gzoffset64 : Prop := OffsetContract Zlib.Gzlib.gzoffset64Related definitions and source ↗