Contents Open

DocsLanguage Guide

Unsafe Code and C Interop

unsafe blocks and functions, raw memory, and calling C and being called from it.

Everything so far has been safe: the compiler, the runtime or both check that memory is used correctly, so a mistake is a compile error or a clean trap, never a corrupted heap. Sometimes you need to step outside that: to manage raw memory yourself, to view bytes as a different type, or to call a C library that knows nothing of Sable's rules. Sable lets you, but makes you say so, with the unsafe keyword, so that the places where the compiler is taking your word are easy to find.

This chapter covers unsafe code and the raw memory types first, then how Sable calls C and is called from it.

Unsafe Blocks#

An unsafe { } block marks code that does something the compiler can't check:

Sable
unsafe {    let p = RawPtr<Int>.allocate(count: 3)    defer { p.deallocate() }    p.initialize(to: 10, at: 0)    p.initialize(to: 20, at: 1)    p.initialize(to: 30, at: 2)    print(p.load(at: 1))    print(p.advanced(by: 2).load())}
2030

unsafe blocks are required for working through raw pointers, for unchecked reinterpretation of memory as another type, and for calling foreign functions that take pointers. Everything else inside the block is checked as usual: an unsafe block doesn't switch off type checking, move checking or inference of reference roots. It only permits the operations that need it.

Writing unsafe doesn't make code wrong, but it does move responsibility to you. The convention is to keep unsafe blocks small and wrap them in safe functions whose callers needn't care.

Unsafe Functions#

Some functions are safe only if the caller keeps a promise the compiler cannot check, like "these bytes are valid UTF-8" or "this pointer points at three initialised Ints". Such a function is declared unsafe fn, and its documentation states the promise:

Sable
extension String {    /// The bytes as a string, not checked: they must be well-formed UTF-8.    public unsafe static fn fromUtf8Unchecked(_ bytes: U8[:]) -> String}

The modifier can appear wherever the function's other modifiers go: unsafe fn, unsafe static fn, unsafe mutating fn, unsafe init, and so on. Before a brace, unsafe starts a block; before fn or another modifier, it modifies a function.

An unsafe fn may be called, or taken as a function value, only inside an unsafe block or in the body of another unsafe fn, including closures inside either (S3470):

Sable
fn decode(_ bytes: U8[:]) -> String {    return String.fromUtf8Unchecked(bytes)      // error: needs 'unsafe' (S3470)}fn decodeTrusted(_ bytes: U8[:]) -> String {    unsafe {        return String.fromUtf8Unchecked(bytes)  // the caller vouches    }}

The usual fix, of course, is the safe function beside the unsafe one: String.fromUtf8 validates the bytes and throws if they are not UTF-8.

Only a function or initialiser can be unsafe. A property or a type cannot (S3471): what the caller vouches for is a call. (The unsafe in unowned(unsafe), a reference that isn't checked, from Memory and Ownership, is a separate thing.)

This is closer to Rust's model than to Swift's, where "unsafe" is only a naming convention on types such as UnsafePointer. In Sable, the compiler tracks it.

Forbidding unsafe code#

sable build --deny-unsafe fails the build on any unsafe block or unsafe fn in the program's own code (S3472). The standard library and your dependencies may still use them behind safe APIs, as String.fromUtf8 does internally; what is counted is the code you wrote. This is a simple way to enforce, in CI, that an application is written entirely in safe Sable. (A finer allow-list, naming which packages may use unsafe, is not built yet.)

Raw Memory#

Sable.Core has a small set of types for working with memory directly.

Type What it is
RawPtr<T> an address and the type of what is there; may be null. RawPtr<Opaque> is C's void *
NonNull<T> a RawPtr<T> that is known not to be null
UnsafeBuffer<T> a run of count values at an address; once made, a checked random-access collection
NativeMemory allocation and copying of bytes at any alignment
MemoryLayout<T> size, stride and alignment of a type

Pointers#

Making a pointer, stepping it and comparing pointers are safe, just as integer arithmetic is. Using a pointer, which means allocating, reading, writing, moving and freeing through it, is done with unsafe fns:

Sable
let p = RawPtr<U32>(address: 0x1000)        // safe: just a numberlet q = p.advanced(by: 4)                   // safe: 0x1010print(p.distance(to: q))                    // prints 4print(p < q)                                // prints trueunsafe {    let buffer = RawPtr<U32>.allocate(count: 4)    buffer.initialize(repeating: 0, count: 4)    buffer.store(7, at: 2)    print(buffer.load(at: 2))               // prints 7    buffer.deinitialize(count: 4)    buffer.deallocate()}

RawPtr has allocate(count:) and deallocate(); initialize(to:at:) and initialize(repeating:count:) to put values into fresh memory; load(at:) and store(_:at:) to read and replace; move(at:) to take a value out; deinitialize(count:) to destroy values in place; cast(to:) to view the same address as another type; and load(as:byteOffset:) and storeBytes(of:byteOffset:) to read and write a value of another type at a byte offset.

Sable
unsafe {    let bytes = NativeMemory.allocate(byteCount: 16, zeroed: true)    defer { NativeMemory.deallocate(bytes) }    let mark: U16 = 0xCAFE    bytes.storeBytes(of: mark, byteOffset: 4)    print(bytes.load(as: U16.self, byteOffset: 4))     // prints 51966}

Two rules are worth stating plainly:

  • Nothing counts what a pointer points at. Reference counting doesn't see raw memory. A value you put there, a String say, is kept alive until you move it out or deinitialise it, and memory you allocate is freed only when you call deallocate().
  • Fresh memory holds no value. Memory from allocate has nothing in it until you initialise it, and reading it before then is undefined. That is why Sable needs no Uninitialized<T> type (Rust's MaybeUninit): raw memory already serves that purpose.

Buffers#

An UnsafeBuffer<T> is a start address and a count. Making one is unsafe, because you vouch that the memory holds count values; but once made, it is a RandomAccessCollection and its subscript is bounds-checked:

Sable
unsafe {    let numbers = UnsafeBuffer<F32>.allocate(count: 3)    numbers.initialize(repeating: 1.5)    for value in numbers {        print(value)    }    numbers.deinitialize()    numbers.deallocate()}

UnsafeBuffer<T>.viewing(start, count: n) views memory someone else owns, such as a buffer a C library returned, without copying or taking ownership of it.

Layout#

MemoryLayout<T> tells you how a type is laid out, which you need when allocating bytes for values or matching a C struct:

Sable
struct Sample {    var time: U64    var level: U8}print(MemoryLayout<Sample>.size)        // 9: the bytes the fields needprint(MemoryLayout<Sample>.stride)      // 16: the distance between two in an arrayprint(MemoryLayout<Sample>.alignment)   // 8

Safe memory helpers#

Three functions in Memory work on ordinary places and are entirely safe. They exist because moving values in and out of a place is a common need, and expressing it with inout is clearer than with temporary copies:

Sable
var current = "draft"var next = "final"Memory.swap(&current, &next)                     // current is "final", next "draft"let previous = Memory.replace(&current, with: "archived")   // gives back "final"var cached: String? = "result"let taken = Memory.take(&cached)                 // "result"; cached is now none

Memory.withPointer(to: &place) { pointer in ... } lends a pointer to a variable for the duration of a closure, which is how you hand C a pointer to a local.

Calling C#

A C function is declared with @extern("c", "name") on a function with no body. The Sable name may differ from the C one:

Sable
import Sable.Interop@extern("c", "abs")fn cAbs(_ n: CInt) -> CInt@extern("c", "toupper")fn cUpper(_ c: CInt) -> CInt@mainfn main() {    print(cAbs(-42))    print(cUpper(0x61))}
4265

@extern("c") alone takes the C name to be the function's own name:

Sable
@extern("c")fn labs(_ n: CLong) -> CLong

The function must be declared at module level, and may not be generic, async or throwing. An @extern one has no body (S3223). The program has to be linked with the library that provides the function; for a package, its build script names the library, or you can look the functions up at run time (see Loading libraries).

What can cross#

What crosses between Sable and C is passed by value and must be something C has in the same form (S3224):

  • an integer type, F32, F64 or Bool;
  • a RawPtr;
  • a struct of those, which is passed exactly as the platform's C passes a struct with the same fields. A struct marked @packed or @align(n) uses C's packed and aligned layouts, and a field of a packed struct passed inout is copied to an aligned place and back.

A struct whose only field is a pointer, such as NonNull, Sable.Interop's CStr or CFunction, is passed as that pointer.

Sable
struct Point {    var x: F64    var y: F64}@extern("c", "geo_distance")fn distance(_ a: Point, _ b: Point) -> F64

What cannot cross by value: C unions, structs with arrays or bit-fields in them, va_list, blocks and long double.

Pointers make an extern unsafe#

An @extern function that is given a pointer, a RawPtr or a struct containing one, must be declared unsafe fn (S3225). Making a pointer is safe, so nothing but the caller's word says it points at what C will read or write, for as long as C will. A function that only returns a pointer needn't be unsafe; using that pointer later is what's unsafe.

Sable
@extern("c", "strlen")unsafe fn cLength(_ text: CStr) -> CSizefn length(of text: String) -> Int {    return text.withCString { (c: CStr) -> Int in        unsafe {            return Int(cLength(c))        }    }}

withCString lends a C string for the length of a closure. The same pattern works for arrays (withPointer and withMutablePointer) and single variables (Memory.withPointer(to:)): the pointer is valid while the closure runs, and C must not keep it afterwards.

Sable
@extern("c", "qsort")unsafe fn cSort(_ base: RawPtr<Opaque>, _ count: CSize, _ size: CSize,                _ compare: CFunction<(RawPtr<Opaque>, RawPtr<Opaque>) -> CInt>)

C's Types#

Sable.Interop names C's types, each an alias for the Sable type of the same width on the target, so a declaration means the same thing on every platform:

Sable.Interop C
CChar, CSignedChar, CUnsignedChar char, signed char, unsigned char (CChar's sign is the platform's)
CShort, CUnsignedShort short, unsigned short
CInt, CUnsignedInt int, unsigned int
CLong, CUnsignedLong long, unsigned long (32 bits on Windows, 64 elsewhere)
CLongLong, CUnsignedLongLong long long, unsigned long long
CFloat, CDouble, CBool float, double, bool
CSize, CSignedSize size_t, ssize_t
CWChar wchar_t

C strings#

Two types carry C strings:

  • CStr is a view: a pointer to NUL-terminated CChars that someone else owns. Its string property decodes it (replacing invalid UTF-8), validated gives none if it isn't UTF-8, and bytes and count give the raw content. CStr.viewing(pointer) is unsafe, since you vouch the pointer is a C string.
  • CString is a class that owns a copy of a string in memory of its own, for when C will keep the pointer. CString("text") throws InteriorNul if the string contains a NUL byte. Its cStr is the view.
Sable
@extern("c", "zlibVersion")fn zlibVersion() -> CStrprint("zlib \(zlibVersion().string)")

Variadic functions#

A C function declared with ... takes CVarArg... after at least one fixed parameter. Only an @extern may do this. The integer types, the floating-point types, Bool and RawPtr are CVarArg:

Sable
@extern("c", "snprintf")unsafe fn cFormat(_ into: RawPtr<CChar>, _ size: CSize, _ format: CStr, _ rest: CVarArg...) -> CInt

Each call passes its values with C's default argument promotions, as a C compiler would: an integer narrower than 32 bits, and Bool, become an int, and F32 becomes a double. They go where the platform's C passes variable arguments; on arm64 macOS, for instance, that's the stack, whatever registers are free. Declaring the variadic part as anything but CVarArg..., or with no fixed parameter before it, is S3224.

Function Pointers and Callbacks#

A C function pointer is a CFunction<F>, where F is a function type C can express. The protocol for those types is CSignature; the compiler knows which function types meet it by what they take and return, using the same rules as for what can cross.

cFunction(f) makes one from a named function, or from a closure written right there, provided it captures nothing (S3226):

Sable
fn ascending(_ a: RawPtr<Opaque>, _ b: RawPtr<Opaque>) -> CInt {    unsafe {        return a.cast(to: CInt.self).load() - b.cast(to: CInt.self).load()    }}var numbers: CInt[>..] = [5, -2, 9, 0]numbers.withMutablePointer { start in    unsafe {        cSort(start.cast(to: Opaque.self), 4, 4, cFunction(ascending))    }}print(numbers)      // prints [-2, 0, 5, 9]

The other way round, someCFunction.function() (unsafe) gives a Sable closure that calls the C function through its address.

A closure that does capture can't be a plain C function pointer, since C has nowhere to keep the captures. C APIs usually solve this with a void * context argument, and Sable.Interop supports that pattern:

  • withCallback(closure) { function, context in ... } lends a capturing closure to C for one call, as a function and a context to pass alongside it. It may be called only on the current thread, which is checked.
  • CCallback(closure) holds a closure whose captures are Sendable, callable from any thread for as long as the CCallback lives.

The context is an index into a table the runtime keeps, never a raw address. So if C calls a callback after it has been let go of, the program stops with a message instead of running freed code. A thread that C created is taken up by the runtime the first time it calls into Sable.

Being Called from C#

@export("c", "name") makes a Sable function callable from C under that name. @export("name") alone takes the language to be C:

Sable
import Sable.Interop@export("c", "inventory_count")public fn inventoryCount(_ warehouse: CInt) -> CInt {    return warehouse * 100}@export("inventory_is_open")fn isOpen(_ hour: I8) -> Bool => hour >= 8 && hour < 18

The same restrictions apply as for @extern: a module-level function, not generic, not async, not throwing, with parameters and results that can cross.

A stored variable at module level can be exported too. C then reads and writes its storage directly by that name:

Sable
@export("inventory_counter")var counter: Int = 5@export("inventory_limit")let limit: I32 = 7
extern int64_t inventory_counter;extern const int32_t inventory_limit;

The variable holds its initial value once the program has started.

A package can be built as a library for C to link, with .library(path:, native: .staticLibrary) (or .dynamicLibrary) in its manifest. As it loads, it starts the runtime and gives its globals their initial values; C then calls its @export functions.

Loading Libraries at Run Time#

DynamicLibrary loads a shared library while the program runs and looks up its symbols, like dlopen and dlsym. Opening a library and looking up a function are unsafe, since you vouch that the symbol has the type you say:

Sable
import Sable.Interopfn loadZlib() -> DynamicLibrary? {    #if os(macos)    let name = "libz.1.dylib"    #elseif os(linux)    let name = "libz.so.1"    #else    let name = "zlib1.dll"    #endif    unsafe {        return try? DynamicLibrary.open(name)    }}@mainfn main() {    guard let zlib = loadZlib() else {        print("no zlib here")        return    }    unsafe {        let version: () -> CStr = try! zlib.function("zlibVersion")        print(version().string)    }}
  • DynamicLibrary.open(path, global:) opens a library, throwing a LibraryError if it can't.
  • DynamicLibrary.program is the running program itself, with everything it is linked against, such as the C library.
  • library.function("name") gives a function of the type you ask for, or throws if there is no such symbol; library.symbol("name") gives an optional instead.
  • library.variable("name", as: CInt.self) gives a LibraryVariable, whose load() and store(_:) read and write the library's variable.
  • library.contains("name") asks whether a symbol exists.

A library stays open as long as anything from it is held: the DynamicLibrary, a function value taken from it, or a LibraryVariable.

Generating Bindings#

Writing @extern declarations by hand is fine for a few functions. For anything larger, sable bindgen writes them from a C header, using clang to read it:

Shell
sable bindgen zlib.h

It writes a Sable module of @extern("c") functions, structs and integer constants. C's types become Sable.Interop's (CInt, CLong, CSize), so the module is the same on every platform. A pointer is a RawPtr (to an empty enum where C only names an opaque struct), a function pointer is a CFunction, ... is CVarArg..., and a function given a pointer is unsafe. Whatever can't cross, such as a union or a struct with an array in it passed by value, is listed in a comment.

The usual shape of a binding is then a thin safe layer on top: public functions that lend buffers with withPointer, call the unsafe externs inside small unsafe blocks, and turn C's error codes into thrown errors.

C++, Objective-C and WebAssembly#

C++ and Objective-C are out of scope beyond calling them through extern "C" shims. Sable's object header is deliberately compatible with neither, to avoid the coupling to Objective-C that constrained Swift's evolution for years.

On WebAssembly (wasm32), C's addresses are 32 bits wide. A pointer is passed as C's, and a struct that holds a pointer beside other fields does not cross by value.

Note

Code run at compile time (a const, a comptime block or a source generator) runs in the compiler's interpreter, which calls no C. Calling an extern there is an error at compile time.

Sable

A systems language with value semantics, automatic reference counting, move-checked resources and compile-time checks on how memory is used, compiled ahead of time to native code through LLVM.

Sable is pre-1.0: the language, the standard library and the toolchain work end to end, but expect changes between versions.