This page describes the detailed semantics underlying the FFI library and its interaction with both Lua and C code.
Given that the FFI library is designed to interface with C code and that declarations can be written in plain C syntax, it closely follows the C language semantics wherever possible. Some concessions are needed for smoother interoperation with Lua language semantics. But it should be straightforward to write applications using the LuaJIT FFI for developers with a C or C++ background.
C Language Support
The FFI library has a built-in C parser with a minimal memory footprint. It's used by the ffi.* library functions to declare C types or external symbols.
It's only purpose is to parse C declarations, as found e.g. in C header files. Although it does evaluate constant expressions, it's not a C compiler. The body of inline C function definitions is simply ignored.
Also, this is not a validating C parser. It expects and accepts correctly formed C declarations, but it may choose to ignore bad declarations or show rather generic error messages. If in doubt, please check the input against your favorite C compiler.
The C parser complies to the C99 language standard plus the following extensions:
- C++-style comments (//).
- The '\e' escape in character and string literals.
- The long long 64 bit integer type.
- The C99/C++ boolean type, declared with the keywords bool or _Bool.
- Complex numbers, declared with the keywords complex or _Complex.
- Two complex number types: complex (aka complex double) and complex float.
- Vector types, declared with the GCC mode or vector_size attribute.
- Unnamed ('transparent') struct/union fields inside a struct/union.
- Incomplete enum declarations, handled like incomplete struct declarations.
- Unnamed enum fields inside a struct/union. This is similar to a scoped C++ enum, except that declared constants are visible in the global namespace, too.
- C++-style scoped static const declarations inside a struct/union.
- Zero-length arrays ([0]), empty struct/union, variable-length arrays (VLA, [?]) and variable-length structs (VLS, with a trailing VLA).
- Alternate GCC keywords with '__', e.g. __const__.
- GCC __attribute__ with the following attributes: aligned, packed, mode, vector_size, cdecl, fastcall, stdcall.
- The GCC __extension__ keyword and the GCC __alignof__ operator.
- GCC __asm__("symname") symbol name redirection for function declarations.
- MSVC keywords for fixed-length types: __int8, __int16, __int32 and __int64.
- MSVC __cdecl, __fastcall, __stdcall, __ptr32, __ptr64, __declspec(align(n)) and #pragma pack.
- All other GCC/MSVC-specific attributes are ignored.
The following C types are pre-defined by the C parser (like a typedef, except re-declarations will be ignored):
- Vararg handling: va_list, __builtin_va_list, __gnuc_va_list.
- From <stddef.h>: ptrdiff_t, size_t, wchar_t.
- From <stdint.h>: int8_t, int16_t, int32_t, int64_t, uint8_t, uint16_t, uint32_t, uint64_t, intptr_t, uintptr_t.
You're encouraged to use these types in preference to the compiler-specific extensions or the target-dependent standard types. E.g. char differs in signedness and long differs in size, depending on the target architecture and platform ABI.
The following C features are not supported:
- A declaration must always have a type specifier; it doesn't default to an int type.
- Old-style empty function declarations (K&R) are not allowed. All C functions must have a proper protype declaration. A function declared without parameters (int foo();) is treated as a function taking zero arguments, like in C++.
- The long double C type is parsed correctly, but there's no support for the related conversions, accesses or arithmetic operations.
- Wide character strings and character literals are not supported.
- See below for features that are currently not implemented.
C Type Conversion Rules
TODO
Conversions from C types to Lua objects
Conversions from Lua objects to C types
Conversions between C types
Initializers
Conversions between C types
Initializers
Creating a cdata object with ffi.new() or the equivalent constructor syntax always initializes its contents, too. Different rules apply, depending on the number of optional initializers and the C types involved:
- If no initializers are given, the object is filled with zero bytes.
- Scalar types (numbers and pointers) accept a single initializer. The Lua object is converted to the scalar C type.
- Valarrays (complex numbers and vectors) are treated like scalars when a single initializer is given. Otherwise they are treated like regular arrays.
- Aggregate types (arrays and structs) accept either a single compound initializer (Lua table or string) or a flat list of initializers.
- The elements of an array are initialized, starting at index zero. If a single initializer is given for an array, it's repeated for all remaining elements. This doesn't happen if two or more initializers are given: all remaining uninitialized elements are filled with zero bytes.
- The fields of a struct are initialized in the order of their declaration. Uninitialized fields are filled with zero bytes.
- Only the first field of a union can be initialized with a flat initializer.
- Elements or fields which are aggregates themselves are initialized with a single initializer, but this may be a compound initializer or a compatible aggregate, of course.
Operations on cdata Objects
TODO
Garbage Collection of cdata Objects
All explicitly (ffi.new(), ffi.cast() etc.) or implicitly (accessors) created cdata objects are garbage collected. You need to ensure to retain valid references to cdata objects somewhere on a Lua stack, an upvalue or in a Lua table while they are still in use. Once the last reference to a cdata object is gone, the garbage collector will automatically free the memory used by it (at the end of the next GC cycle).
Please note that pointers themselves are cdata objects, however they are not followed by the garbage collector. So e.g. if you assign a cdata array to a pointer, you must keep the cdata object holding the array alive as long as the pointer is still in use:
ffi.cdef[[ typedef struct { int *a; } foo_t; ]] local s = ffi.new("foo_t", ffi.new("int[10]")) -- WRONG! local a = ffi.new("int[10]") -- OK local s = ffi.new("foo_t", a) -- Now do something with 's', but keep 'a' alive until you're done.
Similar rules apply for Lua strings which are implicitly converted to "const char *": the string object itself must be referenced somewhere or it'll be garbage collected eventually. The pointer will then point to stale data, which may have already beeen overwritten. Note that string literals are automatically kept alive as long as the function containing it (actually its prototype) is not garbage collected.
Objects which are passed as an argument to an external C function are kept alive until the call returns. So it's generally safe to create temporary cdata objects in argument lists. This is a common idiom for passing specific C types to vararg functions:
ffi.cdef[[
int printf(const char *fmt, ...);
]]
ffi.C.printf("integer value: %d\n", ffi.new("int", x)) -- OK
Memory areas returned by C functions (e.g. from malloc()) must be manually managed, of course. Pointers to cdata objects are indistinguishable from pointers returned by C functions (which is one of the reasons why the GC cannot follow them).
C Library Namespaces
A C library namespace is a special kind of object which allows access to the symbols contained in shared libraries or the default symbol namespace. The default ffi.C namespace is automatically created when the FFI library is loaded. C library namespaces for specific shared libraries may be created with the ffi.load() API function.
Indexing a C library namespace object with a symbol name (a Lua string) automatically binds it to the library. First the symbol type is resolved — it must have been declared with ffi.cdef. Then the symbol address is resolved by searching for the symbol name in the associated shared libraries or the default symbol namespace. Finally, the resulting binding between the symbol name, the symbol type and its address is cached. Missing symbol declarations or nonexistent symbol names cause an error.
This is what happens on a read access for the different kinds of symbols:
- External functions: a cdata object with the type of the function and its address is returned.
- External variables: the symbol address is dereferenced and the loaded value is converted to a Lua object and returned.
- Constant values (static const or enum constants): the constant is converted to a Lua object and returned.
This is what happens on a write access:
- External variables: the value to be written is converted to the C type of the variable and then stored at the symbol address.
- Writing to constant variables or to any other symbol type causes an error, like any other attempted write to a constant location.
C library namespaces themselves are garbage collected objects. If the last reference to the namespace object is gone, the garbage collector will eventually release the shared library reference and remove all memory associated with the namespace. Since this may trigger the removal of the shared library from the memory of the running process, it's generally not safe to use function cdata objects obtained from a library if the namespace object may be unreferenced.
Performance notice: the JIT compiler specializes to the identity of namespace objects and to the strings used to index it. This effectively turns function cdata objects into constants. It's not useful and actually counter-productive to explicitly cache these function objects, e.g. local strlen = ffi.C.strlen. OTOH it is useful to cache the namespace itself, e.g. local C = ffi.C.
No Hand-holding!
The FFI library has been designed as a low-level library. The goal is to interface with C code and C data types with a minimum of overhead. This means you can do anything you can do from C: access all memory, overwrite anything in memory, call machine code at any memory address and so on.
The FFI library provides no memory safety, unlike regular Lua code. It will happily allow you to dereference a NULL pointer, to access arrays out of bounds or to misdeclare C functions. If you make a mistake, your application might crash, just like equivalent C code would.
This behavior is inevitable, since the goal is to provide full interoperability with C code. Adding extra safety measures, like bounds checks, would be futile. There's no way to detect misdeclarations of C functions, since shared libraries only provide symbol names, but no type information. Likewise there's no way to infer the valid range of indexes for a returned pointer.
Again: the FFI library is a low-level library. This implies it needs to be used with care, but it's flexibility and performance often outweigh this concern. If you're a C or C++ developer, it'll be easy to apply your existing knowledge. OTOH writing code for the FFI library is not for the faint of heart and probably shouldn't be the first exercise for someone with little experience in Lua, C or C++.
As a corollary of the above, the FFI library is not safe for use by untrusted Lua code. If you're sandboxing untrusted Lua code, you definitely don't want to give this code access to the FFI library or to any cdata object (except 64 bit integers or complex numbers). Any properly engineered Lua sandbox needs to provide safety wrappers for many of the standard Lua library functions — similar wrappers need to be written for high-level operations on FFI data types, too.
Current Status
The initial release of the FFI library has some limitations and is missing some features. Most of these will be fixed in future releases.
C language support is currently incomplete:
- C declarations are not passed through a C pre-processor, yet.
- The C parser is able to evaluate most constant expressions commonly found in C header files. However it doesn't handle the full range of C expression semantics and may fail for some obscure constructs.
- static const declarations only work for integer types up to 32 bits. Neither declaring string constants nor floating-point constants is supported.
- Packed struct bitfields that cross container boundaries are not implemented.
- Native vector types may be defined with the GCC mode or vector_size attribute. But no operations other than loading, storing and initializing them are supported, yet.
- The volatile type qualifier is currently ignored by compiled code.
- ffi.cdef silently ignores all redeclarations.
The JIT compiler already handles a large subset of all FFI operations. It automatically falls back to the interpreter for unimplemented operations (you can check for this with the -jv command line option). The following operations are currently not compiled and may exhibit suboptimal performance, especially when used in inner loops:
- Array/struct copies and bulk initializations.
- Bitfield accesses and initializations.
- Vector operations.
- Lua tables as compound initializers.
- Initialization of nested struct/union types.
- Allocations of variable-length arrays or structs.
- Allocations of C types with a size > 64 bytes or an alignment > 8 bytes.
- Conversions from lightuserdata to void *.
- Pointer differences for element sizes that are not a power of two.
- Calls to non-cdecl or vararg C functions.
- Calls to C functions with aggregates passed or returned by value.
- Calls to C functions with 64 bit arguments or return values on 32 bit CPUs.
- Accesses to external variables in C library namespaces.
- tostring() for cdata types.
- The following ffi.* API functions: ffi.sizeof(), ffi.alignof(), ffi.offsetof().
Other missing features:
- Bit operations for 64 bit types.
- Arithmetic for complex numbers.
- User-defined metamethods for C types.
- Callbacks from C code to Lua functions.
- Atomic handling of errno.
- Passing structs by value to vararg C functions.
- C++ exception interoperability does not extend to C functions called via the FFI.