# Binary I/O and incremental SHA-256 — ABI 1.12

This additive API accepts every octet, including zero. It uses the existing
`ARRAY` representation; every member must be an `INTEGER` in `0..255`.
`NUMBER` values, strings and out-of-range integers are rejected before file
writes or digest updates. Array indices remain one-based in Kokum. No text
encoding, normalization, terminator or implicit conversion is applied.

The existing `OPEN`, `READ`, `WRITE`, `CLOSEFILE`, `FILE` values and `SHA256`
text builtin retain their ABI 1.11 behavior. In particular, old text APIs
still reject binary modes and invalid UTF-8 or embedded NUL when reading.
A new binary handle is an opaque native value assigned to an untyped local;
it is not a legacy `FILE`. `TLValue` layout is unchanged.

## Public operations

| Builtin | ID | Arguments | Result |
|---|---:|---|---|
| `BINOPEN` | 125 | UTF-8 path, mode | opaque binary file |
| `BINREAD` | 126 | file, integer count | `{"Bytes": ARRAY, "Eof": LOGICAL}` |
| `BINWRITE` | 127 | file, octet array | integer byte count |
| `BINSEEK` | 128 | file, integer offset, optional origin | integer position |
| `BINTELL` | 129 | file | integer position |
| `BINSIZE` | 130 | file | integer length |
| `BINFLUSH` | 131 | file, optional logical durable | `.T.` |
| `BINCLOSE` | 132 | file | `.T.` |
| `BINREPLACE` | 133 | temporary path, target path, optional durable | `.T.` |
| `SHA256BEGIN` | 134 | none | opaque digest state |
| `SHA256UPDATE` | 135 | digest state, octet array | `.T.` |
| `SHA256FINAL` | 136 | digest state | 64 lowercase hex characters |
| `SHA256CLOSE` | 137 | digest state | `.T.` |

New builtin use requires bytecode ABI 1.12. The compiler and official loader
must enforce that floor. Existing builtin identifiers 1..124 are unchanged.

## Open modes and path behavior

| Mode | Read | Write | Creation |
|---|---|---|---|
| `r` | yes | no | must exist |
| `w` | no | yes | create or truncate existing regular file |
| `rw` | yes | yes | must exist; no truncation |
| `x` | no | yes | exclusive create; existing name fails |
| `x+` | yes | yes | exclusive create; existing name fails |

Modes and seek origins use the exact lowercase spellings in this document.
Paths must be nonempty, valid UTF-8, have no embedded NUL, and contain at
most 32,768 UTF-8 bytes. OS path limits can be shorter. Relative paths resolve
against the host process working directory. Only regular files are accepted;
leaf symbolic links, Windows reparse points, directories, devices and FIFOs
are rejected. Intermediate directory symlinks are not a sandbox boundary.
Applications must keep their storage directory private and coordinate its use.

On POSIX, new files are created with permission bits `0600`, further restricted
by the process umask. Existing permissions are unchanged. On Windows, the
file inherits the directory access control; this API does not impose a new
owner-only Windows ACL. Use a suitably protected application directory.

## Counts, memory and EOF

A read count must be an `INTEGER` from 1 to 1,048,576 bytes. A write or hash
update may contain zero to 1,048,576 octets. Oversized calls fail before a raw
copy or I/O; streaming requires repeated bounded calls.

An octet array is not a compact native byte buffer. Each `TLValue` array entry
uses 16 bytes on the supported 64-bit targets, so a maximum-size result uses
about 16 MiB for its entries, plus collection allocation overhead and up to
1 MiB of temporary native bytes. The runtime allocator can fail sooner under
its configured memory limit. Holding multiple chunks multiplies this cost.
A 64 KiB application chunk is a useful initial choice. This API bounds each
operation, not the total arrays an application chooses to retain.

Recoverable native-buffer and collection-growth failures return `KBY1900`.
Existing generic runtime object/string constructors still terminate on fatal
allocation failure. This additive module does not change that behavior or
promise that every process-wide out-of-memory condition can be caught.

`BINREAD` retries interrupted and short system reads until the requested
count, end of file, or an error. A short final result has `Eof=.T.`. When the
last bytes exactly fill the requested count, `Eof` remains `.F.` until the
next read returns `Bytes=[]` and `Eof=.T.`. Zero bytes are ordinary data.

`BINWRITE` validates the complete array, retries interrupted and short writes,
and returns the complete input length on success. An I/O error can leave a
prefix on disk. It throws a typed error rather than returning an apparently
successful short length. Inspect `BINTELL` if recovery needs the actual
position; callers must verify data before recording a committed transfer.
Read or result-allocation failure may also leave the position advanced.

Offsets and lengths are exact signed 64-bit integers. `BINSEEK` defaults to
`"start"`; other origins are `"current"` and `"end"`. Negative results,
addition overflow, and positions beyond the host's supported range fail.
Seeking beyond end does not immediately extend the file. A later write may
create a sparse region. There is no conversion through floating point.

## Flush, close and atomic commit

Descriptor writes have no hidden C stdio buffer. `BINFLUSH(file)` therefore
returns success without a storage barrier. `BINFLUSH(file,.T.)` requires a
writable handle and asks the OS to sync the file (`fsync` or Windows `_commit`).
This reports OS success, not a guarantee that hardware or a remote filesystem
will survive every failure. `BINCLOSE` does not imply a durable flush.

`BINCLOSE` is idempotent and accepts `NULL`. Explicit close affects all aliases
of the handle. A reported close error still leaves the resource closed; do
not retry a native descriptor number. Runtime finalization closes abandoned
handles, but applications needing reliable error handling must close explicitly.

Use `x` or `x+` with a cryptographically random temporary filename in the
intended target directory. After writing and verifying bytes, close the
writer and call `BINREPLACE(temporary,target,.T.)` before acknowledging a
completed object. An application database transaction and a filesystem rename
are separate operations; store enough local recovery state to reconcile a
crash between them.

`BINREPLACE` requires distinct leaf names in the same lexically spelled parent
directory. Equivalent paths with different spelling are deliberately rejected.
The source must be a regular file. A present target must be regular, may not
be a leaf symlink/reparse point, and may not name the same file identity as
the source. There is no cross-volume copy fallback. POSIX uses an anchored
parent descriptor, verifies the source identity, and calls `renameat`.
Windows uses UTF-16 file APIs and `MoveFileExW` with replacement enabled.
Other processes sharing a directory must coordinate; the API is not a defense
against a malicious concurrent directory owner.

Without `durable`, success means the OS completed replacement. With `durable`,
POSIX syncs the source before rename and the directory afterward. Windows
syncs the source and requests `MOVEFILE_WRITE_THROUGH`; it does not promise a
POSIX directory-fsync equivalent. A sync error before replacement is `KBY1006`.
`KBY1007` specifically means replacement **already happened**, but subsequent
directory durability could not be confirmed. Do not blindly retry expecting
the temporary name to remain. Inspect and verify the target during recovery.

## Incremental SHA-256

The implementation uses the linked OpenSSL EVP provider. It does not invoke
an executable or implement SHA-256 in Kokum. No provider downgrade is attempted.
Input is bounded per update; the total supported input is at most
2,305,843,009,213,693,951 bytes, preserving SHA-256's 64-bit bit-length field.
A malformed or oversized update leaves previous valid state untouched.
A provider update failure closes the state. Finalization consumes and closes
the state even when the provider or result allocation fails.
`SHA256CLOSE` is idempotent and accepts `NULL`.

```kokum
LOCAL file
LOCAL digest
LOCAL part AS MAP
LOCAL finished AS LOGICAL
LOCAL hash AS STRING
file=BINOPEN("complete.bin","r")
digest=SHA256BEGIN()
finished=.F.
DO WHILE NOT finished
 part=BINREAD(file,65536)
 SHA256UPDATE(digest,part["Bytes"])
 finished=part["Eof"]
ENDDO
hash=SHA256FINAL(digest)
BINCLOSE(file)
```

Wrap production file operations in the application's `TRY`/`CATCH` cleanup
flow. On failure, close any still-open file and digest handles. A hash proves
byte equality only when the expected digest is independently trusted or
included in authenticated metadata; it is not a signature or encryption.

## Ownership and diagnostics

Handles belong to their creating runtime, runtime owner thread, and current
Kokum task. Operations from another runtime/thread/task fail. Passing native
resources between workers is not a supported sharing mechanism. Each worker
must open its own files and own its own digest state. Closed handles remain
closed across aliases; idempotent close checks runtime ownership even when
already closed.

The native dispatcher borrows input values. Its successful output owns one
reference and its failure output is `NULL`. The caller supplies an empty,
distinct result slot and an entered owner execution context. The C error
structure contains static input-independent code/message pointers and a
native numeric status. It never echoes paths or binary data.

Temporary native byte copies are cleared before release. Ordinary Kokum
arrays remain managed application values; this API does not promise secure
erasure of application arrays, allocator copies, OS caches, swap or dumps.

| Code | Meaning |
|---|---|
| `KBY1000` | argument, type, mode or size violation |
| `KBY1001` | regular-file open failed |
| `KBY1002` | resource already closed |
| `KBY1003` | read failure; position may have advanced |
| `KBY1004` | write/close failure; a write prefix may exist |
| `KBY1005` | seek, size, position or signed-offset overflow |
| `KBY1006` | durability/atomic replace failed before completion |
| `KBY1007` | replacement completed; directory durability unconfirmed |
| `KBY1008` | runtime, thread or task ownership violation |
| `KBY1009` | SHA-256 provider failure |
| `KBY1900` | bounded allocation failed |

## Reproducible checks and their limits

`tests/abi112_binary/native_api.c` exercises the native entry point with real
files, all octets, a maximum-size transfer, sparse 64-bit offsets, invalid
values, resource ownership, same-file/symlink rejection and independent hash
vectors. Compile-time-only seams simulate short writes, ENOSPC after a prefix,
and post-rename directory-sync failure. Its task-ID stub tests affinity checks;
it is not a real task scheduler test. The overflow test adjusts the digest
counter directly; it does not claim to hash exabytes of input. Neither seam
nor stub is compiled into distributable runtime modules.

Build that test with `-Iinclude -Isrc`, `tests/abi112_binary/native_api.c`,
`libkokum_runtime.a` and the platform runtime/OpenSSL libraries; do not also
link the core module because the test supplies the task-ID function. Execute
it in a fresh empty directory. It creates synthetic test files only.

`python3 tests/abi112_binary/test_language.py --kokumc ./kokumc --kokumvm ./kokumvm`
exercises the same public functions through AST, IR, compiler bytecode,
standalone KBC and KAPP execution. Python independently checks output bytes.
The runner also uses a child OpenSSL null-provider configuration to verify a
real catchable provider failure. Existing text-file semantics are included.

The release reports record actual execution platforms. Linux execution or
source parity does not establish Windows/macOS execution. Filesystem durability
beyond the OS result and physical disk-full behavior remain deployment concerns.
