numbox.core.bindings

Overview

A binding lets jitted code call a C function. It is a numbox function with the C function’s name and arguments, and a jitted call of it runs the C function. numbox has bindings for the C standard library, the C math library and SQLite. They include functions that numba’s own support lacks: files through fopen and fwrite, raw memory through memcpy, formatted output to C streams and buffers through printf and snprintf, math functions such as remainder, and the SQLite API. A jitted function that calls bindings can be cached with cache=True, and it keeps working when a later process loads it from the cache. Its compiled code refers to each binding and each C function by name, never by address, and numbox loads the libraries in that process as well, so that LLVM finds the names again.

numbox loads the dynamic libraries that it binds, such as libc, libm and libsqlite3, through ctypes. On Linux and macOS, ctypes.util.find_library finds each library by its short name in the system’s library search, not in the Python installation. On Windows, numbox loads the C runtime msvcrt.dll for libc and libm, and the sqlite3.dll that comes with Python. On Linux and macOS, numbox opens the libraries in global symbol mode (RTLD_GLOBAL, see dlopen(3)). Global mode makes the symbols that the libraries export, their native C API, visible to LLVM, which finds a symbol by name when it links compiled code into the process. Jitted code can then call these C functions [1], which complement the functions that numba supports itself.

The same technique serves for a C library of your own. Load the library with load_lib() or load_lib_path(), declare each function with numba’s ExternalFunction, and call it from a function decorated with proxy(). The proxy decorator compiles the function once, when its module is imported, and every jitted caller then calls that one compiled copy by name. Use proxy_if_available() instead for a symbol that some versions of the library lack. The proxy page shows such a binding in its section on optional C symbols.

References

Calling a binding

Import a binding from its module and call it in jitted code:

from numba import njit

from numbox.core.bindings.libc import strlen
from numbox.core.bindings.libm import remainder
from numbox.utils.lowlevel import get_unicode_data_p


@njit(cache=True)
def demo(word):
    return remainder(7.0, 2.0), strlen(get_unicode_data_p(word))


print(demo("numbox"))   # (-1.0, 6)

C’s remainder rounds the quotient 3.5 to the nearest even integer, 4, and returns 7.0 - 4 * 2.0, which is -1.0. strlen takes a pointer, passed as an intp integer, and get_unicode_data_p() returns the address of a string’s characters. C reads those characters as text only for an ASCII string, as the section Pointers and memory explains. Python code can call the same bindings, and remainder(7.0, 2.0) returns -1.0 there too.

Bindings module conventions

numbox defines its bindings in these modules:

The remaining modules are internal, so you seldom call them directly:

The helper knows the calling conventions of x86-64 on Linux, macOS and Windows, and of 64-bit Arm on Linux and macOS. On another machine, the first import of libc, libm or a SQLite module fails with a RuntimeError that names the platform, because the import compiles the bindings through the helper.

A binding in libc, libm, fmtio or the SQLite subpackage has its C function’s name and takes the C function’s arguments in their C order. The C function’s manual page is therefore its reference: the Linux man pages, Apple’s Libc sources for macOS, and Microsoft’s C runtime reference for Windows. libm’s round and pow are C’s functions, not Python’s: C’s round(2.5) is 3.0, and Python’s is 2. Import the module, as in from numbox.core.bindings import libm, and call libm.round, so that the name round keeps its Python meaning.

Every binding outside fmtio is a proxied function, made with the proxy decorator that the Overview describes. numbox compiles it once, when its module is imported, and a jitted caller calls it by name instead of compiling a copy of its code into each caller. A caller’s own compiled code therefore stays small, and a cached caller works in a later process. The drawback is that each call remains a function call, because LLVM cannot inline it. Python code can call a proxied binding as well.

A binding’s .as_func is a first-class function value for the binding’s signature, and a jitted function can take it as an argument, as the proxy page’s section on passing the function as a value shows. Pass .as_func, not the binding itself. The binding is a numba dispatcher, the object that @njit returns, and its numba type names the address of the function it wraps, so a cached function that receives it compiles again on every run.

numba caches the bindings under numbox’s jit options, the numba options that the NUMBOX_JIT_OPTIONS environment variable sets (numbox.core.configurations). A later import loads the bindings from the cache unless those options disable caching. numbox also disables caching, with a warning, where numba can write no cache. The package numbox.core.bindings imports none of its modules, so a module you do not import is never compiled.

Cached callers of a binding keep working after a numbox upgrade from one release to another. The bindings compile again, because their cache key holds numbox’s version, as after you upgrade numbox explains. numbox repairs each cached caller of a binding whose code the new release changed, at the caller’s next run and with one warning, as the proxy page says under After you upgrade numbox. The one case that repair does not cover is a caller that holds a binding’s .as_func in a module-level variable. Delete that caller’s cache files, as holding the function as a module-level constant explains.

A few SQLite bindings name symbols that some builds of SQLite lack, such as sqlite3_changes64, which SQLite added in version 3.37. Where the symbol is missing, the binding is a stub, and a jitted caller fails to compile, as the proxy page’s section on optional C symbols explains. fmtio’s functions are not proxied: numba compiles each call of them into its caller, and the section Caching callers of the formatted I/O functions says how that changes a cached caller’s behavior after an upgrade.

The bindings in libc, libm and the SQLite subpackage take their signatures from one table, the dictionary signatures in numbox/core/bindings/signatures.py, keyed by C name. strchr, for example, is intp(intp, int32): it takes a pointer and an int32 and returns a pointer. The table writes C’s int as int32, long long as int64, double as float64, and size_t and every pointer as intp. It holds no C long, which has 64 bits on Linux and macOS and 32 bits on Windows; when you declare a C function that takes a long, use int64 on Linux and macOS and int32 on Windows. A jitted caller may pass another numeric type, and numba converts it to the table’s type without a warning. For example, C receives 65 when the caller passes 65.7 or 2**40 + 65 for an int32. The stdio, errno and strerror modules declare their signatures in their own code.

Pointers and memory

A pointer is an intp integer, and numbox does not check it. The caller keeps the memory alive while C uses it, and makes it large enough, and aligned, for what C reads or writes. numbox.utils.lowlevel converts between Python objects and pointers:

In jitted code, numba frees an array or a string as soon as the code no longer refers to it, and an address taken from the object does not count as a reference. A temporary, such as the result of a + b in strlen(get_unicode_data_p(a + b)), is therefore freed before strlen reads it. numba frees a named array in the same way when array_data_p(x) is the last place that names x. C then reads freed memory: a small object may still hold its old bytes, and a large one ends the process with a segmentation fault. Name the object and refer to it after the C call, for example by reading its length, or pass it in from the caller, as the examples on this page do. A string literal or a module-level string is safe: numba holds it as a constant and never frees it, so get_unicode_data_p("r") inside a call works.

Called from Python, get_unicode_data_p returns an address inside the str object itself, so keep the string alive while C uses it.

C reads a string’s characters as text only if the string is ASCII. numba and CPython store each string at one, two or four bytes per character, a width set by its widest character, and never as UTF-8. For other text, encode the string as UTF-8 in Python, add a NUL, and pass the address of the bytes as a uint8 array:

import numpy as np
from numba import njit

from numbox.core.bindings.libc import strlen
from numbox.utils.lowlevel import array_data_p


@njit(cache=True)
def byte_count(text):
    return strlen(array_data_p(text))


text = np.frombuffer("caf\u00e9".encode("utf-8") + b"\0", dtype=np.uint8)
print(byte_count(text))   # 5: four characters, five UTF-8 bytes

c_string() builds the same bytes from Python and keeps them alive for the length of a with block.

Passing a struct

numbox’s bindings pass only numbers and pointers. Store a struct in a one-element NumPy structured array, and pass array_data_p of the array to a C function that takes a pointer to the struct. Build the dtype with align=True, so that NumPy places the fields where a C compiler does: np.dtype([("x", np.int32), ("y", np.float64)], align=True) puts y at offset 8, as C does, and without align=True NumPy puts it at offset 4.

A C function that takes a struct by value is harder to call. numba’s ExternalFunction cannot pass a struct by value at all: a jitted call of a function declared with a tuple argument fails to compile with an AssertionError. Passing one through numbox’s internal helper and its table of signatures is a method specific to numbox. That method is fragile: a struct written as a numba tuple reaches C intact, on x86-64 Linux only, in these four cases:

  • it has a single field;

  • it is larger than 16 bytes;

  • it is exactly 16 bytes, with one field in each 8-byte half;

  • it is exactly 16 bytes, with two or more fields in a half, and neither half is made only of floating-point fields.

(int32, int32, int64) matches the last case and reaches C intact. (int32, int32, float64) matches no case, because its upper half holds only a float64. C reads a wrong value for its second int32. A struct smaller than 16 bytes with two or more fields, such as the 8-byte div_t that C’s div returns, is corrupted as well.

A numba record cannot be passed by value in either direction. Passed as an argument, it reaches C as the address of its data instead of its fields, and a record result of 16 bytes or less ends the process with a segmentation fault.

The helper also refuses some calls when numba compiles them, with a TypingError whose message contains the text below:

  • is unavailable in the LLVM context: no loaded library exports the symbol; load its library with load_lib first;

  • Undefined signature for: the table has no entry for the name;

  • Record returns >16 bytes are not yet supported: return a tuple of the same fields instead;

  • has no fixed bitwidth: a tuple field, such as a voidptr, has no fixed size; pass the pointer as an intp.

Loading a library

You need load_lib() only to bind a library of your own, because each numbox binding module calls it for its own library when imported. load_lib takes a short name, such as "c", "m" or "sqlite3", and returns the library’s handle, an ordinary ctypes.CDLL. The handle remains loaded for the lifetime of the process. A second call with the same name returns the same handle. On Linux and macOS, load_lib finds the file with ctypes.util.find_library. That function uses the system’s library search and does not look in the Python installation, as the ctypes documentation describes. It then opens the file in global symbol mode. A plain ctypes.CDLL opens a library in local mode instead, where its symbols are not visible to LLVM. A jitted call of one of its functions through ExternalFunction then ends the process with a segmentation fault.

When find_library finds no file, load_lib raises RuntimeError: Could not find shared library for <name>. Pass the file’s path to load_lib_path() instead, which opens the file in the same mode and returns a new handle on each call. On Windows, "c" and "m" load the C runtime msvcrt.dll. For any other name, load_lib prefers the DLL bundled with the Python installation to one found on the PATH, and for "sqlite3" it takes only the bundled one.

On Linux, every libm binding runs the system’s libm. On Windows, 26 of them, such as cos, pow, sqrt and fmod, run CPython’s C runtime instead of the msvcrt.dll that numbox loads for "m". numba registers those 26 names for its own math support, and LLVM looks up numba’s registration before any library.

When numba’s JIT is disabled

Under NUMBA_DISABLE_JIT=1, numba compiles nothing, and importing any module of proxied bindings fails with AttributeError: 'function' object has no attribute 'get_compile_result'. The message means that proxy needs numba’s compiler, which the setting disables; unset the variable to use these bindings. fmtio still imports, and printf runs under Python. fprintf fails with the same AttributeError, because it imports the stdio bindings. snprintf writes through a ctypes call that accepts only a Python int as the address. With numba’s JIT disabled, array_data_p returns a NumPy integer, so pass int(array_data_p(buf)).

Writing to stdout and stderr

C functions that work on a stream, such as fputs, fflush and fprintf, take the stream’s FILE *. stdout(), stderr() and stdin() return the current process’s three standard streams as intp values, in jitted code and under Python. They are functions, not constants, because a cached caller’s compiled code must not contain an address from the process that compiled it. A stream’s address changes from one process to the next, so each call reads the address in the running process. Here jitted code writes one line to each stream:

from numba import njit

from numbox.core.bindings.libc import fflush, fputs
from numbox.core.bindings.stdio import stderr, stdout
from numbox.utils.lowlevel import get_unicode_data_p


@njit(cache=True)
def report(line, warning):
    fputs(get_unicode_data_p(line), stdout())
    fflush(stdout())
    fputs(get_unicode_data_p(warning), stderr())


report("42 rows written\n", "2 rows skipped\n")

C keeps a buffer for its stdout, and Python keeps another for sys.stdout. When stdout is a file or a pipe, each writes its buffer only when the buffer fills, when the program flushes it, or when the process exits. Lines from jitted code and lines from Python can then appear out of order. If the process crashes, C never writes the text that remains in its buffer. To keep the order, flush Python’s buffer with sys.stdout.flush() before the jitted call. In jitted code, call fflush(stdout()) after the write, as report does; fflush(0) flushes every C stream. On Linux, C writes stderr without a buffer (setbuf(3)), so a warning appears immediately. On Windows, C flushes a stderr that goes to a file or a pipe only when its buffer fills (Microsoft’s stream I/O), so call fflush(stderr()) there as well.

Reading errno after a failed call

A C function that fails, such as fopen on a missing file, returns a failure value and leaves the reason in errno (errno(3)). errno_get() returns the current thread’s errno as an int32. errno_set() sets it, and narrows its argument to int32. Read errno in the jitted function that made the call, immediately after the call, because a later C call may change it:

from numba import njit

from numbox.core.bindings.errno import errno_get
from numbox.core.bindings.libc import fclose, fopen
from numbox.utils.lowlevel import get_unicode_data_p


@njit(cache=True)
def open_error(path):
    fp = fopen(get_unicode_data_p(path), get_unicode_data_p("r"))
    if fp == 0:
        return errno_get()
    fclose(fp)
    return 0


print(open_error("/no/such/file"))   # 2, which is errno.ENOENT

Each thread has its own errno, and both functions look up the current thread’s on every call. In a prange loop (parallel loops), an iteration therefore reads the errno of the thread that runs it. Read errno in the iteration that made the C call, because the caller’s errno after the loop depends on the threading layer. Under OpenMP, which numba selects when TBB is not installed (threading layers), the calling thread runs some iterations itself. After the loop, its errno holds the value set by those iterations. Under the workqueue layer, the calling thread runs no iterations, and its errno is unchanged.

Turning an error number into a message

strerror_safe() writes the message for an error number into a buffer that the caller provides, and ends the message with a NUL. It returns 0 on success and an error number on failure. libc’s strerror may return a buffer that a later call overwrites; strerror_safe keeps no buffer of its own, so threads can call it at the same time:

import numpy as np
from numba import njit

from numbox.core.bindings.strerror import strerror_safe
from numbox.utils.lowlevel import array_data_p, get_str_from_p_as_int


@njit(cache=True)
def describe(errnum, buf):
    rc = strerror_safe(errnum, array_data_p(buf), buf.size)
    return rc, get_str_from_p_as_int(array_data_p(buf))


print(describe(2, np.zeros(128, dtype=np.uint8)))   # (0, 'No such file or directory')

With glibc, strerror_safe returns EINVAL (22) for an unknown error number and writes Unknown error followed by the number. It returns ERANGE (34) for a buffer too short for the message and writes as much of the message as fits. On Linux, strerror_safe calls __xpg_strerror_r, the POSIX form of strerror_r that glibc exports, and falls back to strerror_r where the C library lacks it; on macOS it calls strerror_r, and on Windows strerror_s.

Formatted output and input

printf(), fprintf(), snprintf() and sscanf() take a format string and the values after it, as C’s functions do (printf(3), sscanf(3)). They are ordinary Python functions that numba also compiles, as it compiles print, so one function body can run under Python and in jitted code:

from numba import njit

from numbox.core.bindings.fmtio import printf
from numbox.core.bindings.libc import fflush
from numbox.core.bindings.stdio import stdout


def step(n, label):
    printf("step %d: %s\n", n, label)
    fflush(stdout())
    return 2 * n


step(7, "in Python")
njit(step)(7, "in jitted code")

Under Python, printf formats the values with Python’s % operator and writes the text to the current sys.stdout, so a redirection such as contextlib.redirect_stdout reaches it. fprintf maps the addresses that stdout(), stderr() and stdin() return to the sys.stdout, sys.stderr and sys.stdin objects that it finds at its first call. A redirection installed after that first call does not change where fprintf writes. fprintf raises RuntimeError for any other FILE *, such as one from fopen. snprintf writes the text into memory at the address it receives, such as array_data_p(buf). In jitted code, numba compiles each call into a call of C’s function, which writes to C’s streams and accepts any FILE *. sscanf runs only in jitted code, as the section Parsing with sscanf describes.

The format string and its arguments

In jitted code, the format must be a string that numba reads as a constant: a string literal, a module-level string or a closure variable. A format built at run time fails to compile with TypingError: printf: format string must be a literal str; pass the part that varies as an argument instead, such as a %s. numbox encodes the format as UTF-8, so non-ASCII text in the format prints as written. Each conversion takes one kind of argument:

Conversions

Argument

%d, %i, %o, %u, %x, %X, %c

an integer or a bool

%e, %f, %g, %a and their capitals

a float

%s

a str, or a pointer

%p

a pointer

When numba compiles the call, numbox checks the format against the arguments, as GCC’s -Wformat does. The compile fails with a TypingError that names the problem when:

  • the format has more or fewer conversions than there are arguments; a * width or precision counts as one more integer argument;

  • a conversion gets an argument of another kind than the one it takes, apart from the two cases described below;

  • an argument has a type that no conversion takes, such as an array, a complex number or a tuple; pass the element or the field you mean, such as a[0] or z.real;

  • the format holds %n, which would make C write the number of characters printed so far through a pointer;

  • the format holds the ' flag for digit grouping, which POSIX defines and C99 and Python’s % lack.

numba lists each of these errors next to a second message, format string must be a literal str, got unicode_type; read the message that names the mismatch. A literal percent sign followed by n, %%n, is allowed. Under Python, %n and the ' flag raise ValueError.

The check cannot distinguish a pointer from an integer, because numba represents a pointer as an intp, which is an int64. It also sees a str as the address of its characters, because numbox substitutes that address before the check runs. A %s given an int64 value compiles, and C then reads memory at that address, which usually ends the process with a segmentation fault. A %d given a str compiles as well, and C prints the address. Pass %s a str or the address of a NUL-terminated buffer, and pass an integer conversion an integer. %p only prints its argument as an address, so an int64 argument for %p is harmless.

For %s, numbox passes a str as the address of its characters, so the ASCII limit from the section Pointers and memory applies: "caf\xe9" prints its last character as the single byte 0xE9, not as UTF-8. Pass other text as a uint8 array of UTF-8 bytes, built as that section shows. A width, as in %-10s, counts bytes, not characters.

When Python and C print differently

If the format uses an ll conversion for every integer, %lld for a signed value and %llu for an unsigned one, the call prints the same under Python and in jitted code. Other conversions can print differently. Python’s % operator ignores a single h, l or L and rejects any other length modifier, as its documentation says: "%lld" % 5 raises ValueError: unsupported format character 'l'. Under Python, numbox therefore removes every length modifier from the format before it formats, and with the modifiers gone, Python prints each value at its full size. In jitted code, numbox passes every integer and bool as 64 bits and every float as a float64, and C converts each value to the type that its conversion names, such as int for %d or signed char for %hhd. A value that fits that type prints the same under Python and in jitted code, and a value that does not fit prints differently:

Format

Value

Python

jitted code

%lld

2**40 + 5

1099511627781

1099511627781

%d

2**40 + 5

1099511627781

5

%hhd

300

300

44

%x

-1

-1

ffffffff

The Python path has one known inconsistency: its stripping does not skip the %% escape, so it also removes a modifier that follows a literal %%, and printf("%%lld\n") prints %d under Python and %lld in jitted code. On Windows, C’s long has 32 bits (Microsoft’s data type ranges), so %ld reads only 32 bits of an int64 there. Python accepts some calls that jitted code refuses, such as %f with an integer and %d with a float. %p works only in jitted code, because Python’s % rejects it.

Checking snprintf for truncation

snprintf(buf, size, fmt, ...) writes at most size bytes into buf, the terminating NUL included, and returns the length of the whole text. A return value of size or more therefore means that snprintf truncated the text. In jitted code, buf and size must be intp values. a.size, np.intp(16) and an int64 argument of the jitted function, such as a Python int passed in, are intp, but a literal is not: snprintf(p, 16, ...) fails to compile with TypingError: snprintf: size must be intp (size_t-as-int), got Literal[int](16). The message means that numba typed the literal 16 as a literal integer; pass a.size or np.intp(16) instead.

On Windows, jitted code calls C’s _snprintf instead. It returns -1 when the text is longer than size, and when the text is exactly size bytes long it returns size and writes no terminating NUL. The test n < 0 or n >= size covers both cases on every platform:

import numpy as np
from numba import njit

from numbox.core.bindings.fmtio import snprintf
from numbox.utils.lowlevel import array_data_p


@njit(cache=True)
def format_range(buf, lo, hi):
    n = snprintf(array_data_p(buf), buf.size, "[%d:%d]", lo, hi)
    return -1 if n < 0 or n >= buf.size else n


buf = np.zeros(16, dtype=np.uint8)
n = format_range(buf, 7, 11)
print(n, bytes(buf[:n]).decode())   # 6 [7:11]

Under Python, snprintf follows the C99 rule on every platform.

Parsing with sscanf

sscanf(buf, fmt, ...) reads values from the NUL-terminated text at buf into storage that the caller provides. It returns the number of values that it stored, or -1 (EOF) when the text ends before the first conversion. Unlike the other three functions, it runs only in jitted code. Under Python it raises NotImplementedError, and int(), float() or re parse the text there instead. A jitted function calls sscanf as follows:

import numpy as np
from numba import njit

from numbox.core.bindings.fmtio import sscanf
from numbox.utils.lowlevel import array_data_p, get_unicode_data_p


@njit(cache=True)
def parse_pair(text):
    count = np.zeros(1, dtype=np.int32)
    ratio = np.zeros(1, dtype=np.float64)
    n = sscanf(get_unicode_data_p(text), "%d %lf", array_data_p(count), array_data_p(ratio))
    return n, count[0], ratio[0]


print(parse_pair("42 0.25"))   # (2, 42, 0.25)

buf must be an intp, so pass get_unicode_data_p(text), not the string; the ASCII limit from the section Pointers and memory applies to the text. Each argument after the format is the address of the storage for one conversion, also as an intp. numbox checks only that type, so an int64 value that is not an address compiles. C then treats the value as an address and writes to the memory that it points to. numbox does not compare the format with the arguments either, so the caller must make them match the format in number and in size. Each conversion writes storage of its own size:

Conversion

Storage

%hhd

int8

%hd

int16

%d, %u

int32, uint32

%lld, %llu

int64, uint64

%ld

int64 on Linux and macOS, int32 on Windows

%f

float32

%lf

float64

%s

a uint8 array

%n

int32

Give %s a width one less than the array’s size, such as %15s for 16 bytes, so that the characters and the NUL fit. Unlike the output functions, sscanf accepts %n: it stores the number of characters read so far, and the return value does not count it.

Caching callers of the formatted I/O functions

A jitted call of printf, fprintf, snprintf or sscanf compiles into its caller: the caller’s code names C’s function and holds the format as a constant. A caller cached with cache=True works in a later process, which finds C’s function by name. After you upgrade numbox, however, a cached caller still runs the fmtio code of the numbox version that compiled it. This happens because numba’s cache key covers the caller’s own file and not the code of the functions it calls (what the key leaves out). Delete the caller’s cache files after an upgrade; where numba writes the cache says where they are. Alternatively, decorate the caller with numbox_njit(), whose cache key holds numbox’s version, so that an upgrade from one release to another recompiles it. The cache_key page lists which functions numbox keys. It also explains what an upgrade changes, both between releases and in a source checkout, where the version stays empty.

Modules

numbox.core.bindings.libc

Bindings for C standard library functions on strings, memory, streams, random numbers and the environment.

Each binding has the C function’s name and takes its arguments in C’s order, with the types of the function’s entry in numbox.core.bindings.signatures: C’s int as int32, and size_t and every pointer as intp. A pointer is an address that the caller keeps alive while C uses it, and numba converts another numeric argument to the entry’s type without a warning. Each binding is a proxied function that jitted code and Python can call, and its docstring links the C function’s Linux manual page. The section “Bindings module conventions” on the bindings page describes the conventions that all binding modules share.

numbox.core.bindings.libc.clearerr(fp)[source]

Clear the end-of-file and error indicators of the stream fp.

C reference: clearerr(3).

numbox.core.bindings.libc.fclose(fp)[source]

Flush the buffered output of the stream fp, close the stream, and return 0, or EOF on error.

C reference: fclose(3).

fp is invalid after the call, whatever the result, and must not be used again.

numbox.core.bindings.libc.feof(fp)[source]

Return a nonzero value if the end-of-file indicator of the stream fp is set, and 0 if it is not.

C reference: feof(3).

clearerr clears the indicator, as do C’s fseek, fsetpos and rewind when they succeed; numbox binds none of those three.

numbox.core.bindings.libc.ferror(fp)[source]

Return a nonzero value if the error indicator of the stream fp is set, and 0 if it is not.

C reference: ferror(3).

clearerr clears the indicator, as does C’s rewind, which numbox does not bind.

numbox.core.bindings.libc.fflush(fp)[source]

Flush the buffered output of the stream fp, or of every output stream if fp is 0.

C reference: fflush(3).

The result is 0 on success and EOF on error. Because C buffers its stdout apart from Python’s sys.stdout, text from jitted code and text from Python can appear out of order when stdout is a file or a pipe, until both are flushed.

numbox.core.bindings.libc.fopen(path, mode)[source]

Open the file whose name is the string at path, in the mode given by the string at mode, as a stream.

C reference: fopen(3).

path and mode, such as "r", "wb" or "a+", are intp addresses of NUL-terminated strings. The result is a FILE * as an intp, or 0 on error, with the reason in errno. The caller closes the stream with fclose. On Windows, a mode without b opens the file in text mode, which translates line endings.

numbox.core.bindings.libc.fputc(c, fp)[source]

Write c, converted to unsigned char, to the stream fp, and return the byte written.

C reference: fputc(3).

The result is EOF on error. fp is a FILE * as an intp.

numbox.core.bindings.libc.fputs(s, fp)[source]

Write the NUL-terminated string at address s to the stream fp, without a newline.

C reference: fputs(3).

The result is non-negative on success and EOF on error. s is an intp address that the caller keeps alive during the call, and fp is a FILE * as an intp, from fopen or from numbox.core.bindings.stdio.

numbox.core.bindings.libc.fread(ptr, size, nmemb, fp)[source]

Read up to nmemb elements of size bytes each from the stream fp into memory at address ptr.

C reference: fread(3).

The result is the number of elements read, which is less than nmemb at the end of the file or on an error; feof and ferror distinguish the two cases. ptr is the intp address of at least size * nmemb bytes, which the caller keeps alive during the call.

numbox.core.bindings.libc.fwrite(ptr, size, nmemb, fp)[source]

Write nmemb elements of size bytes each from address ptr to the stream fp.

C reference: fwrite(3).

The result is the number of elements written, which is less than nmemb only on error. ptr is an intp address that the caller keeps alive during the call, and fp is a FILE * as an intp.

numbox.core.bindings.libc.getenv(name)[source]

Return the address of the value of the environment variable named by the string at name, or 0 if unset.

C reference: getenv(3).

The environment owns the value: the caller must not modify or free it, and a later setenv, putenv or unsetenv can invalidate it. To keep the value, copy it into a str with get_str_from_p_as_int() before the environment changes.

numbox.core.bindings.libc.memchr(s, c, n)[source]

Return the address of the first byte equal to c in the n bytes at address s, or 0 if none.

C reference: memchr(3).

C converts c to unsigned char, so it compares c & 0xff.

numbox.core.bindings.libc.memcmp(a, b, n)[source]

Compare the first n bytes at addresses a and b, as unsigned bytes.

C reference: memcmp(3).

The result follows the sign convention of strcmp, and the comparison does not stop at a NUL.

numbox.core.bindings.libc.memcpy(dst, src, n)[source]

Copy n bytes from address src to address dst, and return dst.

C reference: memcpy(3).

The two regions must not overlap; memmove copies between overlapping regions. The caller keeps both regions alive during the call.

numbox.core.bindings.libc.memmove(dst, src, n)[source]

Copy n bytes from address src to address dst, which may overlap, and return dst.

C reference: memmove(3).

The caller keeps both regions alive during the call.

numbox.core.bindings.libc.memset(dst, c, n)[source]

Fill the n bytes at address dst with c, converted to unsigned char, and return dst.

C reference: memset(3).

numbox.core.bindings.libc.putchar(c)[source]

Write c, converted to unsigned char, to C’s stdout, and return the byte written.

C reference: putchar(3).

The result is EOF on error.

numbox.core.bindings.libc.puts(s)[source]

Write the NUL-terminated string at address s and a newline to C’s stdout.

C reference: puts(3).

The result is non-negative on success and EOF on error. s is an intp address that the caller keeps alive during the call.

numbox.core.bindings.libc.rand()[source]

Return the next pseudo-random integer, from 0 to RAND_MAX, of the generator that srand seeds.

C reference: rand(3).

RAND_MAX is 2147483647 with glibc and on macOS, and 32767 on Windows. C does not require rand to be safe to call from several threads concurrently.

numbox.core.bindings.libc.srand(s)[source]

Seed the generator that rand uses with s.

C reference: srand(3).

C takes the seed as an unsigned int: numba converts an integer argument to int32 without a warning, and C reads its 32 bits as unsigned.

numbox.core.bindings.libc.strchr(s, c)[source]

Return the address of the first byte equal to c in the NUL-terminated string at s, or 0 if none.

C reference: strchr(3).

C converts c to char, and a c of 0 finds the terminating NUL. numba converts an integer argument to int32 without a warning.

numbox.core.bindings.libc.strcmp(a, b)[source]

Compare the NUL-terminated strings at addresses a and b byte by byte, as unsigned bytes.

C reference: strcmp(3).

The result is negative if a sorts first, 0 if the strings are equal, and positive if b sorts first.

numbox.core.bindings.libc.strerror(errnum)[source]

Return the address of the message string for the error number errnum.

C reference: strerror(3).

C does not require strerror to be thread-safe: the string may be in a buffer that a later call overwrites. strerror_safe() writes the message into the caller’s buffer instead.

numbox.core.bindings.libc.strlen(s)[source]

Return the number of bytes in the NUL-terminated string at address s, the NUL excluded.

C reference: strlen(3).

s is an intp address, such as one from get_unicode_data_p(), and the caller keeps the string alive during the call.

numbox.core.bindings.libc.strncmp(a, b, n)[source]

Compare at most the first n bytes of the NUL-terminated strings at addresses a and b.

C reference: strncmp(3).

The comparison stops at the first NUL in either string, and the result follows the sign convention of strcmp. An n of 0 gives 0.

numbox.core.bindings.libc.strncpy(dst, src, n)[source]

Copy at most n bytes of the NUL-terminated string at src to dst, and return dst.

C reference: strncpy(3).

If src is shorter than n bytes, C fills the rest of the n bytes with NULs. If it is n bytes or longer, dst receives n bytes and no terminating NUL. A caller that needs a NUL-terminated result reserves one more byte, and either zeroes the buffer first or writes a NUL at offset n of dst after the call.

numbox.core.bindings.libc.strrchr(s, c)[source]

Return the address of the last byte equal to c in the NUL-terminated string at s, or 0 if none.

C reference: strrchr(3).

C converts c to char, and a c of 0 finds the terminating NUL. numba converts an integer argument to int32 without a warning.

numbox.core.bindings.libc.strstr(haystack, needle)[source]

Return the address of the first occurrence of the string needle in the string haystack, or 0 if none.

C reference: strstr(3).

Both arguments are intp addresses of NUL-terminated strings. An empty needle gives haystack.

numbox.core.bindings.libm

Bindings for the functions of the C math library, on float64.

Each binding calls the double form of the C function of its name, so it takes and returns float64, and numba converts an integer or float32 argument without a warning. The bindings behave as C’s functions, not Python’s. C returns NaN or an infinity where Python’s math module raises ValueError or OverflowError, as for sqrt(-1.0), log(0.0) or exp(1000.0), and round and pow differ from Python’s built-ins. Import the module, as in from numbox.core.bindings import libm, and call libm.round, so that the name round still refers to Python’s built-in function. numba registers 26 of these names, among them cos, pow and sqrt, for its own math support, and LLVM finds a registered name before it searches any library. On Windows, those 26 bindings therefore call the functions of CPython’s C runtime instead of those of the msvcrt.dll that this module loads for "m".

numbox.core.bindings.libm.acos(x)[source]

Return the arc cosine of x in radians, from 0 to pi.

C reference: acos(3).

An x outside [-1, 1] gives NaN. The binding calls C’s double form, so it takes and returns float64, and numba converts an integer or float32 argument without a warning. On Windows, the binding calls the function in CPython’s C runtime, not the one in msvcrt.dll, because numba registers the name acos for its own math support.

numbox.core.bindings.libm.acosh(x)[source]

Return the inverse hyperbolic cosine of x, a value of 0 or more.

C reference: acosh(3).

An x below 1 gives NaN. The binding calls C’s double form, so it takes and returns float64, and numba converts an integer or float32 argument without a warning. On Windows, the binding calls the function in CPython’s C runtime, not the one in msvcrt.dll, because numba registers the name acosh for its own math support.

numbox.core.bindings.libm.asin(x)[source]

Return the arc sine of x in radians, from -pi/2 to pi/2.

C reference: asin(3).

An x outside [-1, 1] gives NaN. The binding calls C’s double form, so it takes and returns float64, and numba converts an integer or float32 argument without a warning. On Windows, the binding calls the function in CPython’s C runtime, not the one in msvcrt.dll, because numba registers the name asin for its own math support.

numbox.core.bindings.libm.asinh(x)[source]

Return the inverse hyperbolic sine of x.

C reference: asinh(3).

The binding calls C’s double form, so it takes and returns float64, and numba converts an integer or float32 argument without a warning. On Windows, the binding calls the function in CPython’s C runtime, not the one in msvcrt.dll, because numba registers the name asinh for its own math support.

numbox.core.bindings.libm.atan(x)[source]

Return the arc tangent of x in radians, from -pi/2 to pi/2.

C reference: atan(3).

The binding calls C’s double form, so it takes and returns float64, and numba converts an integer or float32 argument without a warning. On Windows, the binding calls the function in CPython’s C runtime, not the one in msvcrt.dll, because numba registers the name atan for its own math support.

numbox.core.bindings.libm.atan2(y, x)[source]

Return the arc tangent of y / x in radians, in the quadrant that the signs of x and y determine.

C reference: atan2(3).

The result is in the range from -pi to pi, and the first argument is y, as in C. The binding calls C’s double form, so it takes and returns float64, and numba converts an integer or float32 argument without a warning. On Windows, the binding calls the function in CPython’s C runtime, not the one in msvcrt.dll, because numba registers the name atan2 for its own math support.

numbox.core.bindings.libm.atanh(x)[source]

Return the inverse hyperbolic tangent of x.

C reference: atanh(3).

An x of 1 or -1 gives an infinity of the same sign, and an x outside [-1, 1] gives NaN. The binding calls C’s double form, so it takes and returns float64, and numba converts an integer or float32 argument without a warning. On Windows, the binding calls the function in CPython’s C runtime, not the one in msvcrt.dll, because numba registers the name atanh for its own math support.

numbox.core.bindings.libm.cbrt(x)[source]

Return the cube root of x, which is negative for a negative x.

C reference: cbrt(3).

The binding calls C’s double form, so it takes and returns float64, and numba converts an integer or float32 argument without a warning.

numbox.core.bindings.libm.ceil(x)[source]

Return the smallest integral value that is not less than x, as a float.

C reference: ceil(3).

The binding calls C’s double form, so it takes and returns float64, and numba converts an integer or float32 argument without a warning. On Windows, the binding calls the function in CPython’s C runtime, not the one in msvcrt.dll, because numba registers the name ceil for its own math support.

numbox.core.bindings.libm.copysign(x, y)[source]

Return a value with the magnitude of x and the sign of y.

C reference: copysign(3).

The binding calls C’s double form, so it takes and returns float64, and numba converts an integer or float32 argument without a warning.

numbox.core.bindings.libm.cos(x)[source]

Return the cosine of x, an angle in radians.

C reference: cos(3).

The binding calls C’s double form, so it takes and returns float64, and numba converts an integer or float32 argument without a warning. On Windows, the binding calls the function in CPython’s C runtime, not the one in msvcrt.dll, because numba registers the name cos for its own math support.

numbox.core.bindings.libm.cosh(x)[source]

Return the hyperbolic cosine of x.

C reference: cosh(3).

The binding calls C’s double form, so it takes and returns float64, and numba converts an integer or float32 argument without a warning. On Windows, the binding calls the function in CPython’s C runtime, not the one in msvcrt.dll, because numba registers the name cosh for its own math support.

numbox.core.bindings.libm.erf(x)[source]

Return the error function of x.

C reference: erf(3).

The binding calls C’s double form, so it takes and returns float64, and numba converts an integer or float32 argument without a warning.

numbox.core.bindings.libm.erfc(x)[source]

Return the complementary error function of x, 1 - erf(x), computed accurately for large x.

C reference: erfc(3).

The binding calls C’s double form, so it takes and returns float64, and numba converts an integer or float32 argument without a warning.

numbox.core.bindings.libm.exp(x)[source]

Return e raised to the power x.

C reference: exp(3).

The binding calls C’s double form, so it takes and returns float64, and numba converts an integer or float32 argument without a warning. On Windows, the binding calls the function in CPython’s C runtime, not the one in msvcrt.dll, because numba registers the name exp for its own math support.

numbox.core.bindings.libm.exp2(x)[source]

Return 2 raised to the power x.

C reference: exp2(3).

The binding calls C’s double form, so it takes and returns float64, and numba converts an integer or float32 argument without a warning.

numbox.core.bindings.libm.expm1(x)[source]

Return e raised to the power x, minus 1, computed accurately when x is near 0.

C reference: expm1(3).

The binding calls C’s double form, so it takes and returns float64, and numba converts an integer or float32 argument without a warning. On Windows, the binding calls the function in CPython’s C runtime, not the one in msvcrt.dll, because numba registers the name expm1 for its own math support.

numbox.core.bindings.libm.fabs(x)[source]

Return the absolute value of x.

C reference: fabs(3).

The binding calls C’s double form, so it takes and returns float64, and numba converts an integer or float32 argument without a warning. On Windows, the binding calls the function in CPython’s C runtime, not the one in msvcrt.dll, because numba registers the name fabs for its own math support.

numbox.core.bindings.libm.fdim(x, y)[source]

Return x - y if x is greater than y, and 0 otherwise.

C reference: fdim(3).

The binding calls C’s double form, so it takes and returns float64, and numba converts an integer or float32 argument without a warning.

numbox.core.bindings.libm.floor(x)[source]

Return the largest integral value that is not greater than x, as a float.

C reference: floor(3).

The binding calls C’s double form, so it takes and returns float64, and numba converts an integer or float32 argument without a warning. On Windows, the binding calls the function in CPython’s C runtime, not the one in msvcrt.dll, because numba registers the name floor for its own math support.

numbox.core.bindings.libm.fmax(x, y)[source]

Return the larger of x and y; if one of them is NaN, return the other.

C reference: fmax(3).

The binding calls C’s double form, so it takes and returns float64, and numba converts an integer or float32 argument without a warning.

numbox.core.bindings.libm.fmin(x, y)[source]

Return the smaller of x and y; if one of them is NaN, return the other.

C reference: fmin(3).

The binding calls C’s double form, so it takes and returns float64, and numba converts an integer or float32 argument without a warning.

numbox.core.bindings.libm.fmod(x, y)[source]

Return x - n * y, where n is x / y rounded toward zero, so the result has the sign of x.

C reference: fmod(3).

Python’s % gives the result the sign of y instead. A y of 0 gives NaN. The binding calls C’s double form, so it takes and returns float64, and numba converts an integer or float32 argument without a warning. On Windows, the binding calls the function in CPython’s C runtime, not the one in msvcrt.dll, because numba registers the name fmod for its own math support.

numbox.core.bindings.libm.hypot(x, y)[source]

Return the square root of x * x + y * y, without overflow or underflow in the intermediate steps.

C reference: hypot(3).

The binding calls C’s double form, so it takes and returns float64, and numba converts an integer or float32 argument without a warning.

numbox.core.bindings.libm.lgamma(x)[source]

Return the natural logarithm of the absolute value of the gamma function at x.

C reference: lgamma(3).

The sign of the gamma function is not returned: C stores it in the global variable signgam, which numbox does not read. Because of that global variable, C does not require lgamma to be thread-safe. The binding calls C’s double form, so it takes and returns float64, and numba converts an integer or float32 argument without a warning.

numbox.core.bindings.libm.log(x)[source]

Return the natural logarithm of x.

C reference: log(3).

An x of 0 gives negative infinity, and a negative x gives NaN. The binding calls C’s double form, so it takes and returns float64, and numba converts an integer or float32 argument without a warning. On Windows, the binding calls the function in CPython’s C runtime, not the one in msvcrt.dll, because numba registers the name log for its own math support.

numbox.core.bindings.libm.log10(x)[source]

Return the base-10 logarithm of x.

C reference: log10(3).

An x of 0 gives negative infinity, and a negative x gives NaN. The binding calls C’s double form, so it takes and returns float64, and numba converts an integer or float32 argument without a warning. On Windows, the binding calls the function in CPython’s C runtime, not the one in msvcrt.dll, because numba registers the name log10 for its own math support.

numbox.core.bindings.libm.log1p(x)[source]

Return the natural logarithm of 1 + x, computed accurately when x is near 0.

C reference: log1p(3).

An x of -1 gives negative infinity, and an x below -1 gives NaN. The binding calls C’s double form, so it takes and returns float64, and numba converts an integer or float32 argument without a warning. On Windows, the binding calls the function in CPython’s C runtime, not the one in msvcrt.dll, because numba registers the name log1p for its own math support.

numbox.core.bindings.libm.log2(x)[source]

Return the base-2 logarithm of x.

C reference: log2(3).

An x of 0 gives negative infinity, and a negative x gives NaN. The binding calls C’s double form, so it takes and returns float64, and numba converts an integer or float32 argument without a warning.

numbox.core.bindings.libm.logb(x)[source]

Return the base-2 exponent of x as a float: floor(log2(abs(x))) for a finite x other than 0.

C reference: logb(3).

An x of 0 gives negative infinity. The binding calls C’s double form, so it takes and returns float64, and numba converts an integer or float32 argument without a warning.

numbox.core.bindings.libm.nearbyint(x)[source]

Return x rounded to an integral value in the current rounding mode, as a float.

C reference: nearbyint(3).

It differs from rint only in that it does not set C’s inexact floating-point exception flag. In the default mode, a halfway case goes to the even value. The binding calls C’s double form, so it takes and returns float64, and numba converts an integer or float32 argument without a warning.

numbox.core.bindings.libm.pow(x, y)[source]

Return x raised to the power y.

C reference: pow(3).

This is C’s pow, not Python’s: a negative x with a non-integral y gives NaN, and 0 with a negative y gives infinity, where Python’s ** gives a complex number or raises ZeroDivisionError. The binding calls C’s double form, so it takes and returns float64, and numba converts an integer or float32 argument without a warning. On Windows, the binding calls the function in CPython’s C runtime, not the one in msvcrt.dll, because numba registers the name pow for its own math support.

numbox.core.bindings.libm.remainder(x, y)[source]

Return x - n * y, where n is x / y rounded to the nearest integer, halfway cases to even.

C reference: remainder(3).

This is the IEEE 754 remainder: remainder(7.0, 2.0) is -1.0. A y of 0 gives NaN. The binding calls C’s double form, so it takes and returns float64, and numba converts an integer or float32 argument without a warning.

numbox.core.bindings.libm.rint(x)[source]

Return x rounded to an integral value in the current rounding mode, as a float.

C reference: rint(3).

In the default mode, which rounds to nearest, a halfway case goes to the even value: rint(2.5) is 2.0. The binding calls C’s double form, so it takes and returns float64, and numba converts an integer or float32 argument without a warning.

numbox.core.bindings.libm.round(x)[source]

Return x rounded to the nearest integral value, with halfway cases away from zero, as a float.

C reference: round(3).

This is C’s round, not Python’s: round(2.5) is 3.0 here and 2 in Python. The binding calls C’s double form, so it takes and returns float64, and numba converts an integer or float32 argument without a warning. On Windows, the binding calls the function in CPython’s C runtime, not the one in msvcrt.dll, because numba registers the name round for its own math support.

numbox.core.bindings.libm.sin(x)[source]

Return the sine of x, an angle in radians.

C reference: sin(3).

The binding calls C’s double form, so it takes and returns float64, and numba converts an integer or float32 argument without a warning. On Windows, the binding calls the function in CPython’s C runtime, not the one in msvcrt.dll, because numba registers the name sin for its own math support.

numbox.core.bindings.libm.sinh(x)[source]

Return the hyperbolic sine of x.

C reference: sinh(3).

The binding calls C’s double form, so it takes and returns float64, and numba converts an integer or float32 argument without a warning. On Windows, the binding calls the function in CPython’s C runtime, not the one in msvcrt.dll, because numba registers the name sinh for its own math support.

numbox.core.bindings.libm.sqrt(x)[source]

Return the square root of x.

C reference: sqrt(3).

A negative x gives NaN. The binding calls C’s double form, so it takes and returns float64, and numba converts an integer or float32 argument without a warning. On Windows, the binding calls the function in CPython’s C runtime, not the one in msvcrt.dll, because numba registers the name sqrt for its own math support.

numbox.core.bindings.libm.tan(x)[source]

Return the tangent of x, an angle in radians.

C reference: tan(3).

The binding calls C’s double form, so it takes and returns float64, and numba converts an integer or float32 argument without a warning. On Windows, the binding calls the function in CPython’s C runtime, not the one in msvcrt.dll, because numba registers the name tan for its own math support.

numbox.core.bindings.libm.tanh(x)[source]

Return the hyperbolic tangent of x.

C reference: tanh(3).

The binding calls C’s double form, so it takes and returns float64, and numba converts an integer or float32 argument without a warning. On Windows, the binding calls the function in CPython’s C runtime, not the one in msvcrt.dll, because numba registers the name tanh for its own math support.

numbox.core.bindings.libm.tgamma(x)[source]

Return the gamma function at x.

C reference: tgamma(3).

The binding calls C’s double form, so it takes and returns float64, and numba converts an integer or float32 argument without a warning.

numbox.core.bindings.libm.trunc(x)[source]

Return x rounded toward zero to an integral value, as a float.

C reference: trunc(3).

The binding calls C’s double form, so it takes and returns float64, and numba converts an integer or float32 argument without a warning. On Windows, the binding calls the function in CPython’s C runtime, not the one in msvcrt.dll, because numba registers the name trunc for its own math support.

numbox.core.bindings.stdio

The C standard streams, stdout, stderr and stdin, as FILE * values for jitted code and Python.

stdout(), stderr() and stdin() return the running process’s three streams as intp addresses, which C functions such as fputs, fflush and fprintf take. Each call reads the address in the running process, so a cached caller never uses an address from the process that compiled it. On Windows, the functions need the Universal C Runtime (UCRT) of Windows 10 and later. Older Windows versions name the streams _iob or __iob_func, differently in each Visual C++ runtime, and numbox does not support them.

numbox.core.bindings.stdio.stderr()[source]

Return the running process’s C stream stderr, a FILE *, as an intp.

C reference: stderr(3).

Each call reads the address in the running process. C writes stderr without a buffer on Linux. On Windows, C buffers a stderr that goes to a file or a pipe, so call fflush(stderr()) there.

numbox.core.bindings.stdio.stdin()[source]

Return the running process’s C stream stdin, a FILE *, as an intp.

C reference: stdin(3).

Each call reads the address in the running process.

numbox.core.bindings.stdio.stdout()[source]

Return the running process’s C stream stdout, a FILE *, as an intp.

C reference: stdout(3).

Each call reads the address in the running process. C buffers this stream separately from Python’s sys.stdout, so flush both, with fflush(stdout()) and sys.stdout.flush(), to make jitted output and Python output appear in the order in which they were written.

numbox.core.bindings.errno

Reading and setting the calling thread’s errno, from jitted code and from Python.

errno_get() returns the current thread’s errno and errno_set() sets it. Both call the C library’s accessor on every use, so each reads or writes the errno of the thread that runs it.

numbox.core.bindings.errno.errno_get()[source]

Return the calling thread’s errno as an int32.

C reference: errno(3).

Each call looks up the errno of the thread that runs it, so an iteration of a prange loop reads the errno of its own thread. A Python caller reads the errno that a jitted function set on the same thread. After a parallel loop, the calling thread’s errno depends on numba’s threading layer. Under OpenMP, the calling thread runs some iterations itself, and its errno holds the value that those iterations set. Under the workqueue layer, the calling thread runs no iterations, and its errno is unchanged.

numbox.core.bindings.errno.errno_set(v)[source]

Set the calling thread’s errno to v, narrowed to int32.

C reference: errno(3).

v is an int64, Python’s integer width, and the binding stores its low 32 bits, the width of C’s int errno: 2**32 + 5 is stored as 5.

numbox.core.bindings.strerror

A thread-safe message for an error number, for jitted code and Python.

strerror_safe() writes the message for an error number into a buffer that the caller provides. It calls the thread-safe form of strerror that the platform’s C library exports, chosen when numba compiles the call:

  • glibc: __xpg_strerror_r, the POSIX (XSI) form, which glibc exports from version 2.3.4, released in 2004;

  • musl: also __xpg_strerror_r, which musl exports as a weak alias of its strerror_r, itself the POSIX form;

  • macOS: strerror_r, the POSIX form;

  • Windows: strerror_s, which takes its arguments in the order buffer, size, error number.

numbox supports no other C library on Linux. glibc’s plain strerror_r is the GNU form, which returns a char * and does not match the POSIX-shaped call that this module emits. The module therefore calls __xpg_strerror_r on Linux whenever LLVM finds it, as it does with glibc and musl, and falls back to strerror_r only for a C library that lacks the symbol.

numbox.core.bindings.strerror.strerror_safe(errnum, buf, buflen)[source]

Write the message for the error number errnum into the buffer at buf, and return 0 or an error number.

C reference: strerror_r(3).

buf is the intp address of buflen bytes that the caller keeps alive during the call, and the message ends with a NUL. The binding narrows errnum to int32, the width of C’s int. With glibc, the function returns EINVAL (22) for an unknown number and writes Unknown error followed by the number. It returns ERANGE (34) for a buffer too short for the message and writes as much of the message as fits. The function uses no buffer of its own, so threads can call it at the same time. On Linux it calls __xpg_strerror_r, which glibc and musl export, on macOS strerror_r, and on Windows strerror_s, with the arguments in that function’s order.

numbox.core.bindings.fmtio

C’s printf, fprintf, snprintf and sscanf, for Python and for jitted code.

The four public functions are ordinary Python functions that take C’s arguments in C’s order, with the values after the format as separate arguments, not in a tuple. In jitted code, numba compiles each call, through an @overload, into a call of the C function of the same name, with the format embedded as a constant. printf(), fprintf() and snprintf() run from the same source under Python and in jitted code: Python’s % operator formats the text under Python, and C formats it in jitted code. sscanf() runs in jitted code only. numba compiles a jitted call into its caller’s code. A caller cached with cache=True therefore runs the fmtio code of the numbox version that compiled it, as the section “Caching callers of the formatted I/O functions” of the bindings page explains. The section “Formatted output and input” there describes the conversions, where Python’s output and C’s differ, snprintf’s truncation and sscanf’s storage. The rest of the module is private: the intrinsics that emit the C calls, and the checks that numbox runs on a format when numba compiles a call.

numbox.core.bindings.fmtio.fprintf(fp, fmt, *args)[source]

Format args by fmt, write the text to the stream fp, and return the number of bytes written.

C reference: fprintf(3).

fp is a FILE * as an intp, such as one that stdout() or fopen returns. The format and the arguments follow the rules of printf(), in both modes. In jitted code, numba compiles the call into a call of C’s fprintf, which accepts any FILE *.

Under Python, the function writes to sys.stdout, sys.stderr or sys.stdin for the address of the matching C stream, and flushes it. It raises RuntimeError for any other FILE *, such as one from fopen; use Python’s open and write for a file there. The function maps the three addresses to the sys objects that are current at its first call, so a redirection installed after that call does not change where it writes. With NUMBA_DISABLE_JIT=1, the first call raises AttributeError, because it imports the stdio bindings.

numbox.core.bindings.fmtio.printf(fmt, *args)[source]

Format args by the C format string fmt, write the text to stdout, and return the number of bytes written.

C reference: printf(3).

Under Python, fmt can be any str. The function formats with Python’s % operator, writes the text to the current sys.stdout and flushes it, and returns the length in bytes of the text in UTF-8. Python’s % ignores the length modifiers h, l and L and rejects the others, such as the ll of %lld, so the function removes every length modifier before it formats. It also removes one that follows a literal %%, so "%%lld" prints %d under Python. %p works only in jitted code, because Python’s % rejects it. %s given an address prints the number under Python, where C prints the string at that address.

In jitted code, numba compiles the call into a call of C’s printf, which writes to C’s stdout and returns an int32. fmt must be a string that numba reads as a constant, such as a literal, and C receives it in UTF-8. numbox checks the conversions against the arguments when numba compiles the call, as GCC’s -Wformat does, and raises TypingError for a mismatch. numbox passes a str argument to C as the address of its characters, which C reads as text only for an ASCII string. The check is applied to that address, so a str given to %d compiles and prints the address. numbox passes every integer and bool to C as 64 bits and every float as a float64, and C converts each value to the type that its conversion names, such as int for %d. On Windows, C’s long has 32 bits, so use %lld rather than %ld for an int64. A width such as %-10s counts bytes, not characters; to pad by characters, pad the string first, for example with str.ljust.

In both modes, %n and the ' flag raise an error: TypingError in jitted code and ValueError under Python.

numbox.core.bindings.fmtio.snprintf(buf_p, size, fmt, *args)[source]

Format args by fmt into the size bytes at address buf_p, and return the length of the whole text.

C reference: snprintf(3).

buf_p is the intp address of at least size bytes, such as array_data_p(buf), which the caller keeps alive during the call. The function writes at most size bytes, the terminating NUL included, and returns the length in bytes of the text without the NUL, so a result of size or more means that it truncated the text. The format and the arguments follow the rules of printf().

In jitted code, buf_p and size must be intp values: a.size, np.intp(16) and an int64 argument of the jitted function work, but a literal such as 16 and an np.int32 fail to compile with TypingError. On Windows, jitted code calls C’s _snprintf instead. It returns -1 when the text is longer than size, and when the text is exactly size bytes long, it returns size and writes no NUL. The test n < 0 or n >= size covers both cases on every platform.

Under Python, the function follows the C99 rule on every platform. ctypes.memmove writes the text, and it rejects a NumPy integer as buf_p. array_data_p returns one under NUMBA_DISABLE_JIT=1, so pass int(array_data_p(buf)) there.

numbox.core.bindings.fmtio.sscanf(buf, fmt, *args)[source]

Read values by fmt from the NUL-terminated text at address buf into storage, in jitted code only.

C reference: sscanf(3).

The result is the number of values stored, or -1, C’s EOF, if the text ends before the first conversion. buf is the intp address of the text, such as get_unicode_data_p(text) for an ASCII str. Each argument after fmt is the intp address of the storage for one conversion, such as array_data_p of a one-element array of the matching dtype. numbox checks only that each of them is an intp. It does not compare the format with the arguments, so the caller must make them match in number and in size. fmt must be a string that numba reads as a constant, as for printf(). Under Python, the function raises NotImplementedError; use int(), float() or re to parse the text there.

numbox.core.bindings.abi

The C calling-convention rules that the bindings’ internal helper applies to each call.

numbox.core.bindings.call._call_lib_func uses this module to determine the calling convention that the host follows and the class of each value in a call: a number or a pointer, a struct of 16 bytes or less, or a larger struct. The module computes the size of a struct written as a numba tuple or record, and the offset of each field, as a C compiler lays them out. For a 16-byte struct, the module computes the class of each 8-byte half, and those classes determine whether the helper repacks the struct before the call. Every name in the module is private to the bindings.

numbox.core.bindings.call

The internal helper through which the libc, libm and SQLite bindings call C functions.

_call_lib_func is a numba intrinsic that compiles a call of a C function by its name. It takes the result type from numbox.core.bindings.signatures, checks that LLVM can find the name, and passes each value by the host’s calling convention, which numbox.core.bindings.abi classifies. numbox’s bindings call it from functions decorated with proxy(), so that numba has converted the arguments to the table’s types first. _call_lib_func_byval passes a struct through a pointer to a copy, for a C function that takes a pointer to a struct. The section “Passing a struct” of the bindings page says which structs reach C intact.

numbox.core.bindings.signatures

The table of C signatures that the libc, libm and SQLite bindings use, keyed by the C function’s name.

signatures merges signatures_c for the C standard library, signatures_m for the C math library and signatures_sqlite for SQLite. Each value is the numba signature of the C function. C’s int is int32, a 64-bit integer such as long long or sqlite3_int64 is int64, and double is float64. An unsigned type is the unsigned numba type of the same width, and size_t and every pointer are intp. Each binding is compiled for its entry, and _call_lib_func takes the result type from it. The table holds no C long, whose width is 64 bits on Linux and macOS and 32 bits on Windows. lldiv_t is the tuple type of the result of C’s lldiv.

numbox.core.bindings.utils

Library loading and small helpers for the binding modules.

load_lib() and load_lib_path() load a C library so that LLVM finds its symbols when it links jitted code into the process. extract_literal_str() reads the value of a numba string literal, such as a format string or a C function’s name, and intp_ll_type() returns the LLVM type that numbox uses for size_t and pointers. platform_ holds the name of the operating system, as platform.system() returns it.

numbox.core.bindings.utils.extract_literal_str(binding_name, ty, *, field='argument')[source]

Return the str value of a numba string literal type.

Intrinsics and overloads use it for an argument that numba must know when it compiles the call, such as a format string, a C function’s name or a standard stream’s name. It raises TypingError if ty is not a literal or if its value is not a str, and the message names binding_name and the argument, field.

numbox.core.bindings.utils.intp_ll_type(context=None)[source]

Return the LLVM integer type of numba’s intp, which numbox uses for size_t and pointers.

With a codegen context, the type is context.get_value_type(intp), which is how an intrinsic derives a width that depends on the platform, such as that of size_t, ssize_t or ptrdiff_t. Without one, as in a test or an IR probe, it is llir.IntType(intp.bitwidth). numba lowers intp to an integer of that same width, so both calls give the same type.

numbox.core.bindings.utils.load_lib(name)[source]

Return the ctypes.CDLL handle of the library whose short name is name, loading it at the first call.

The first call loads the library so that LLVM finds its symbols, and later calls with the same name return the same handle from the module’s cache, _loaded_libs. Each binding module calls it for its own library, and the modules share the handle without importing one another. A caller can test for a symbol with hasattr(handle, name), as proxy_if_available() does. ctypes never unloads a library, so the library stays loaded for the life of the process.

On Linux and macOS, ctypes.util.find_library finds the file by the short name, such as "m" for the C math library, in the system’s library search and not in the Python installation. The file is then opened in global symbol mode, RTLD_GLOBAL. On Windows, the function loads the C runtime msvcrt.dll for "c" and "m", and only the sqlite3.dll bundled with Python for "sqlite3". For any other name, it prefers a DLL bundled with Python to one on the PATH.

If no file is found, the function raises RuntimeError: Could not find shared library for <name>; pass the file’s path to load_lib_path() instead. On Linux, find_library also searches the directories in LD_LIBRARY_PATH, but it finds a library there only if the library was built with a SONAME, and the system’s loader reads the variable only when the process starts. On macOS, find_library searches the directories in DYLD_LIBRARY_PATH as os.environ holds the variable at the call.

numbox.core.bindings.utils.load_lib_path(path)[source]

Load the library at path so that LLVM finds its symbols, and return a new ctypes.CDLL handle.

path is any string that ctypes.CDLL accepts: an absolute path, a soname such as libm.so.6, which ctypes.util.find_library returns, or a file name that the system’s loader resolves. The function opens the library with RTLD_GLOBAL on Linux and macOS and with winmode=0 on Windows, and it raises RuntimeError on any other platform. Each call returns a new handle; use load_lib() for a library that several modules load by its short name.