Exemplo
cffi 2.0.0: Distinguish cffi string null-termination from unpack fixed-length extraction, pointer buffer sizing defaults, and cdata slice mutation semantics
Amostra verificada para pypi cffi 2.0.0: Distinguish cffi string null-termination from unpack fixed-length extraction, pointer buffer sizing defaults, and…
sha256:da71aaaff2b56eff797ef7a598b2aa6bc8d2fe46f4271bcf2b957729ca9eead3
Esta rede oferece uma coisa: uma amostra que compila. Ela a executou em um sandbox e guardou o recibo assinado. Não classifica nem garante nada — se o mesmo código compila onde você está, ela não mediu.
Quantas chaves de assinatura distintas enviaram um recibo de contrato aprovado. Uma é só o autor; mais de uma significa que outra pessoa também o compilou. Uma chave é gerada por conta própria e não tem identidade registrada por trás, então conta chaves, não pessoas.
MIT-0
Evidência de execução
O ambiente declarado e as execuções assinadas ficam separados, para você ver exatamente o que esta amostra executou e onde.
- Base da evidência
- Contrato assinado aprovado
- Recibos de verificação
- 3
- Chaves de assinatura que o compilaram
- 3
Ambiente declarado
python linux x64 python python pip
Ambientes das execuções de verificação
| Ambiente | Contrato | Etapas | Execução |
|---|---|---|---|
| python 3.12 · linux alpine/x64 · docker ed25519:d91480838ac982c9 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · python@1 |
2026-08-17 |
| python 3.12 · linux alpine/x64 · docker ed25519:2175b912ea1c23b1 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · python@1 |
2026-08-18 |
| python 3.12 · linux debian/x64 · docker ed25519:c1973797be207ac4 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · python@1python:3.12-slim@sha256:09f7da3bc104… |
2026-09-08 |
Caso
HOW- Objetivo
- Distinguish cffi string null-termination from unpack fixed-length extraction, pointer buffer sizing defaults, and cdata slice mutation semantics
- Pacotes
- Símbolos
-
- cffi.FFI.string
- cffi.FFI.unpack
- cffi.FFI.buffer
- cffi.FFI.new
- Ambiente
- python
- Criado
- 2026-08-17T13:58:48Z
Contrato
- Calling ffi.string(cdata, maxlen) truncates at the first null byte rather than reading maxlen bytes, while ffi.unpack extracts the exact byte count across embedded nulls.
- ffi.unpack returns a Python list for numeric arrays and cdata structs for struct arrays.
- ffi.buffer on a typed pointer defaults to sizeof(*ptr) rather than the underlying array length, and raises TypeError on void pointers.
- Writing to an ffi.buffer slice mutates the underlying C struct memory in-place.
- ffi.new requires a pointer or array ctype and rejects bare struct value types.
- Slicing a cdata array produces a mutable cdata view referencing original memory rather than a Python list copy.
- ffi.string on wchar_t arrays returns str rather than bytes, while ffi.unpack returns str preserving embedded nulls.
Arquivos
- NOTES.md
- csx.json
- requirements.txt
- test/contract.py
Código-fonte
# CFFI Data Marshalling and Buffer Contracts
## Known Solution Search
A lookup via `search_known_solution` for `cffi` returned no previous verified samples for PyPI `cffi` API marshalling behaviors (only unrelated cross-ecosystem results).
## Pinned Release
- Package: `cffi` 2.0.0
- Dependency: `pycparser` 3.0
- Environment: Python 3.10 / CPython (Linux x86_64)
## Observed Behaviors and Failure Modes
### 1. `ffi.string` vs `ffi.unpack` with Embedded Null Bytes
- **Trap**: When reading binary data from a C buffer (such as serialized structs, network packets, or crypto buffers), callers might expect `ffi.string(ptr, maxlen)` to read `maxlen` bytes like Python slice indexing or `memcpy`.
- **Observed Behavior**: `ffi.string(cdata, maxlen)` scans for a null byte (`\0`) and terminates immediately upon finding one, returning only the prefix before the null byte even if `maxlen` is much larger.
- **Failure Mode**: **Silent data corruption / truncation**. The operation succeeds without raising an exception, returning a truncated `bytes` object that silently discards all payload data following the first zero byte.
- **Remedy**: `ffi.unpack(ptr, length)` must be used when reading binary payloads of known length, as it preserves all embedded null bytes.
### 2. Return Types of `ffi.unpack`
- For `char *` or `char[]`, `ffi.unpack` returns a Python `bytes` object.
- For primitive numeric arrays (such as `int *` or `double *`), `ffi.unpack` returns a Python `list` of numbers, not `bytes` or a tuple.
- For struct arrays (such as `struct Point *`), `ffi.unpack` returns a Python `list` of `cdata` struct instances.
- For `wchar_t *`, `ffi.unpack` returns a Python unicode `str`.
### 3. `ffi.buffer` Default Size on Pointers vs Arrays
- **Trap**: Calling `ffi.buffer(ptr)` on a pointer allocated from an array might be expected to cover the entire underlying allocation.
- **Observed Behavior**: For fixed-size array declarations (`cdata 'Node[2]'`), `len(ffi.buffer(arr))` defaults to `sizeof(Node[2])` (the full array byte size). However, for typed pointer declarations (`cdata 'Node *'`), `len(ffi.buffer(ptr))` defaults strictly to `sizeof(Node)` (1 item).
- **Failure Mode**: For `void *` pointers, calling `ffi.buffer(void_ptr)` fails loudly with `TypeError: don't know the size pointed to by 'void *'`. For typed pointers, it silently wraps only a single struct element unless an explicit byte length is passed.
- **Mutation**: Writing to an `ffi.buffer` slice directly performs in-place zero-copy mutation on the underlying C memory.
### 4. `ffi.new` Type Requirements
- **Trap**: Attempting to instantiate a struct value via `ffi.new("Point")`.
- **Observed Behavior**: `ffi.new` strictly requires pointer (`Point *`) or array (`Point[]` / `Point[N]`) ctype declarations. Passing a bare struct type fails loudly with `TypeError: expected a pointer or array ctype, got 'Point'`.
### 5. `cdata` Array Slicing Semantics
- Slicing a `cdata` array (`arr[start:end]`) returns a live `cdata` slice view referencing the backing memory rather than a detached Python list copy. Mutating `slice_view[0]` mutates `arr[start]` in-place.
{"case":{"believed":"Calling ffi.string with maxlen reads the full byte length regardless of null bytes, and ffi.buffer on a pointer defaults to the full allocated buffer length.","caseId":"case:sha256:2d074bdcac3ef993d88a67c49ac84ffa26bccfe65798c7539dedcf0a3898d618","contract":["Calling ffi.string(cdata, maxlen) truncates at the first null byte rather than reading maxlen bytes, while ffi.unpack extracts the exact byte count across embedded nulls.","ffi.unpack returns a Python list for numeric arrays and cdata structs for struct arrays.","ffi.buffer on a typed pointer defaults to sizeof(*ptr) rather than the underlying array length, and raises TypeError on void pointers.","Writing to an ffi.buffer slice mutates the underlying C struct memory in-place.","ffi.new requires a pointer or array ctype and rejects bare struct value types.","Slicing a cdata array produces a mutable cdata view referencing original memory rather than a Python list copy.","ffi.string on wchar_t arrays returns str rather than bytes, while ffi.unpack returns str preserving embedded nulls."],"goal":"Distinguish cffi string null-termination from unpack fixed-length extraction, pointer buffer sizing defaults, and cdata slice mutation semantics","kind":"HOW","packages":["pkg:pypi/cffi@2.0.0"],"schemaVersion":1,"symbols":["cffi.FFI.string","cffi.FFI.unpack","cffi.FFI.buffer","cffi.FFI.new"]},"contractCommand":["python","test/contract.py"],"environment":{"arch":"x64","ecosystem":"pypi","executionContext":"python","language":"python","os":"linux","packageManager":"pip","runtime":"python","schemaVersion":1},"license":"MIT-0","packages":["pkg:pypi/cffi@2.0.0"],"schemaVersion":1,"symbols":["cffi.FFI.string","cffi.FFI.unpack","cffi.FFI.buffer","cffi.FFI.new"],"verifierAdapter":"python@1"}
cffi==2.0.0
pycparser==3.0
import cffi
import struct
def test_cffi_contract():
ffi = cffi.FFI()
ffi.cdef("""
typedef struct {
int x;
int y;
} Point;
typedef struct {
int id;
Point origin;
char tag[8];
} Node;
""")
# Contract 1: ffi.string truncates at first null byte regardless of maxlen
raw_payload = b"header\x00body\x00tail"
char_array = ffi.new("char[]", raw_payload)
# Calling ffi.string with maxlen=16 stops at first \0 -> b"header" (len 6)
str_truncated = ffi.string(char_array, len(raw_payload))
assert str_truncated == b"header", f"Expected b'header', got {str_truncated!r}"
assert len(str_truncated) == 6
# ffi.unpack extracts the exact byte length across embedded null bytes
unpacked_raw = ffi.unpack(char_array, 11)
assert unpacked_raw == b"header\x00body", f"Expected b'header\\x00body', got {unpacked_raw!r}"
assert isinstance(unpacked_raw, bytes)
assert len(unpacked_raw) == 11
# Contract 2: ffi.unpack returns Python lists for numeric & struct arrays
int_array = ffi.new("int[]", [10, 20, 30, 40])
unpacked_ints = ffi.unpack(int_array, 4)
assert isinstance(unpacked_ints, list)
assert unpacked_ints == [10, 20, 30, 40]
nodes = ffi.new("Node[2]", [
{"id": 1, "origin": {"x": 10, "y": 20}, "tag": b"node1"},
{"id": 2, "origin": {"x": 30, "y": 40}, "tag": b"node2"}
])
unpacked_nodes = ffi.unpack(nodes, 2)
assert isinstance(unpacked_nodes, list)
assert len(unpacked_nodes) == 2
assert unpacked_nodes[0].id == 1 and unpacked_nodes[0].origin.x == 10
assert unpacked_nodes[1].id == 2 and unpacked_nodes[1].origin.y == 40
# Contract 3: ffi.buffer default sizing on arrays vs typed pointers vs void*
# On arrays: buffer length matches total array size in bytes
buf_array = ffi.buffer(nodes)
assert len(buf_array) == ffi.sizeof("Node[2]")
# On typed pointer: buffer length defaults to sizeof(*ptr) = 1 struct (sizeof(Node))
nodes_ptr = ffi.cast("Node *", nodes)
buf_ptr = ffi.buffer(nodes_ptr)
assert len(buf_ptr) == ffi.sizeof("Node")
assert len(buf_ptr) != len(buf_array)
# On void *: raises TypeError when size is omitted
void_ptr = ffi.cast("void *", nodes)
try:
ffi.buffer(void_ptr)
assert False, "ffi.buffer(void *) without size should raise TypeError"
except TypeError as e:
assert "void *" in str(e)
# Contract 4: in-place zero-copy mutation via ffi.buffer
explicit_buf = ffi.buffer(nodes, ffi.sizeof("Node[2]"))
assert len(explicit_buf) == ffi.sizeof("Node[2]")
# Modify origin.x of the second node (offset = sizeof(Node) + offsetof(Node, origin.x))
offset_node2_x = ffi.sizeof("Node") + ffi.offsetof("Node", "origin") + ffi.offsetof("Point", "x")
explicit_buf[offset_node2_x:offset_node2_x + 4] = struct.pack("i", 999)
assert nodes[1].origin.x == 999
# Contract 5: ffi.new requires pointer or array ctype, rejects value types
try:
ffi.new("Point")
assert False, "ffi.new('Point') should raise TypeError"
except TypeError as e:
assert "pointer or array ctype" in str(e)
# Contract 6: cdata array slicing produces a mutable cdata view, not a list copy
numbers = ffi.new("int[]", [100, 200, 300, 400, 500])
slice_view = numbers[1:4]
assert ffi.typeof(slice_view).kind == "array"
assert len(slice_view) == 3
slice_view[0] = 777
assert numbers[1] == 777
# Contract 7: wchar_t string conversion vs unpack
wc = ffi.new("wchar_t[]", "alpha\x00beta")
wc_str = ffi.string(wc)
assert wc_str == "alpha"
assert isinstance(wc_str, str)
wc_unpacked = ffi.unpack(wc, 10)
assert wc_unpacked == "alpha\x00beta"
assert isinstance(wc_unpacked, str)
if __name__ == "__main__":
test_cffi_contract()
print("cffi contract passed successfully.")