Calling C
Limen can call C functions directly, for the libraries that only exist in C: a database engine, a compression library, a system API. This chapter shows how, and why the permission to do it isn't like any other capability. C code runs outside all of Limen's checks, so the foreign grant is full trust.
A foreign block
A foreign block declares the C functions of one library, by their signatures:
foreign "c" {
// long strtol(const char *s, char **end, int base)
fn strtol(s: Str, end: Out[Handle], base: Int32) -> Int
// size_t strlen(const char *s)
fn strlen(s: Str) -> Int
}
fn main(root: Root) {
let c = root.foreign
let (n, _) = strtol(c, "42 apples", 10)
let (hex, _) = strtol(c, "ff", 16)
root.stdout.print("{n} {hex} {strlen(c, "hello")}")
}$ limen run main.lmn --grant foreign=c
limen: warning: --grant foreign=c is full access: C code can do anything this process can, past every other grant
42 255 5
$ limen run main.lmn
panic: foreign: library `c` is not granted (grant it with --grant foreign=c)
--> main.lmn:10:18
foreign "c" names the library: "c" is the C library itself, and foreign "sqlite3" would be libsqlite3. Each function inside is declared with Limen types that map to C types: Int is int64_t, Int32 is a C int (convert with n.to_int32() and r.to_int()), Float is double, Str is const char *, Handle is void *. The function name is the C symbol.
Calling a foreign function takes the Foreign capability first, before the other arguments: strtol(c, "42 apples", 10). That makes C reachable only from code that holds Foreign, and limen caps lists every function that does.
Out[Handle] is an out-parameter. C writes it, and Limen returns it after the result, so strtol returns a tuple (Int, Handle) and the caller doesn't pass end at all.
Without the grant, the program still compiles, and the first foreign call stops it:
$ limen run main.lmn
panic: foreign: library `c` is not granted (grant it with --grant foreign=c)
--> main.lmn:10:18
Why the foreign grant is different
Every other capability is checked: an Fs refuses paths outside its directory, a Net refuses other hosts. A C function, once called, can do anything the process can. It can open any file, connect anywhere, and read and change the program's memory, including every other capability the program holds. Limen checks the types you declared, but it can't check that they match the real C function, and a wrong declaration is undefined behaviour.
So the foreign grant is treated as what it is:
limen runprints a warning every time it's given, as you saw above.- Only the program can grant it, with
--grant foreign=LIBor in its own limen.toml. A dependency'scapscan't include it. A dependency may declare foreign blocks only if the program names it under[trust]:
[dependencies]
zstd = { git = "https://example.com/zstd.git", tag = "v1.0.0" }
[trust]
foreign = ["zstd"]
- limen.lock records which C libraries each trusted dependency calls. If an update makes it call a new one, the build stops until you've looked.
limen checklists every part of the program that calls C.- The operating-system sandbox (chapter 12) still applies, so C code is limited to roughly what the program was granted.
One library at a time
root.foreign.only("c") is a Foreign that reaches only the C library: narrow it before passing it on, as with any capability. A program that calls two C libraries grants both, with --grant foreign=c,m or --grant foreign=c --grant foreign=m, but parts of the program usually need only one. Where the compiler can see what a Foreign was narrowed to, a call into another library is an error before the program runs:
foreign "c" {
fn strlen(s: Str) -> Int
}
foreign "m" {
fn sqrt(x: Float) -> Float
}
fn main(root: Root) {
let c = root.foreign.only("c")
root.stdout.print("{strlen(c, "hello")}")
root.stdout.print("{sqrt(c, 2.0)}")
}$ limen check main.lmn
error[E0333]: `sqrt` calls C library `m`, but this Foreign grants only `c`
--> main.lmn:12:30
|
12 | root.stdout.print("{sqrt(c, 2.0)}")
| ^
= note: it was narrowed with `only`, so the call would panic; narrow it to the library the function belongs to
1 error
When the compiler can't tell, for example when the Foreign arrives as a parameter, the same check happens when the call is made, and the call panics instead. limen caps lists the libraries each function reaches, as you'll see below.
Dependencies narrow the same way. Give the trusted zstd dependency from above caps = ["foreign=zstd"] in its limen.toml entry, and it may call into the zstd library and no other; a foreign block for any other library is an error.
Narrowing limits which library's functions Limen code may call. It doesn't limit what those functions do once they run: a C function still has the whole process's authority.
Keeping C small
Put C behind a small module whose foreign functions are private, wrapped in a safe Limen API that takes ordinary capabilities. That's the shape of the standard library's sql module: programs using sql grant an Fs, not foreign, and the module keeps SQLite inside that directory.
Structs, variadic functions and callbacks
Three more things cross the boundary:
foreign "c" {
// a struct, passed and returned by value
struct Div { quot: Int32, rem: Int32 }
fn div(a: Int32, b: Int32) -> Div
// a variadic function, declared with the arguments this call passes
fn snprintf(buf: Handle, size: Int, format: Str, ..., n: Int, x: Float) -> Int32
// a callback: C calls a Limen function during the call
fn qsort(base: Handle, n: Int, size: Int, compare: fn(Handle, Handle) -> Int32)
fn malloc(size: Int) -> Handle
fn free(p: Handle)
fn memcpy(dst: Handle, src: Bytes, n: Int) -> Handle
}
// Compares two bytes in C memory; the Foreign capability lets it read them.
fn by_byte(f: Foreign, a: Handle, b: Handle) -> Int32 {
(f.copy(a, 1)[0] - f.copy(b, 1)[0]).to_int32()
}
fn main(root: Root) {
let f = root.foreign
let out = root.stdout
out.print("{div(f, 17, 5)}")
let buf = malloc(f, 64)
let len = snprintf(f, buf, 64, "%lld items at %.2f", 3, 9.5)
out.print(f.copy(buf, len.to_int()).to_str())
let data = "limen".to_bytes()
memcpy(f, buf, data, data.len())
qsort(f, buf, data.len(), 1, by_byte)
out.print(f.copy(buf, data.len()).to_str())
free(f, buf)
}$ limen run main.lmn --grant foreign=c
limen: warning: --grant foreign=c is full access: C code can do anything this process can, past every other grant
Div { quot: 3, rem: 2 }
3 items at 9.50
eilmn
Structs by value. A struct inside a foreign block is laid out as C lays it out, with fields of Int and the fixed-size integers, Float, Bool and Handle. In Limen it's an ordinary struct you can print and compare.
Variadic functions. C can't tell what a function like snprintf was passed, so the declaration fixes it: the parameters before ... are the function's own, and the ones after are the arguments this declaration passes. To call it with other argument types, declare it again under another name, with = "snprintf" after the signature to name the C symbol.
Callbacks. A parameter of a function type is a pointer to a function C can call. The argument must be a named top-level function. It may take a Foreign first, which gives it the same Foreign the call was given, here to read C memory with f.copy. A closure doesn't work: C calls the function with its arguments alone, and a closure would have nowhere to keep what it captured.
foreign "c" {
fn qsort(base: Handle, n: Int, size: Int, compare: fn(Handle, Handle) -> Int32)
}
fn main(root: Root) {
let reverse = true
let buf = Handle { addr: 0 }
qsort(root.foreign, buf, 0, 1, |a, b| if reverse { 1.to_int32() } else { (-1).to_int32() })
}$ limen check main.lmn
error[E0332]: a callback to C is a top-level function, passed by its name
--> main.lmn:8:36
|
8 | qsort(root.foreign, buf, 0, 1, |a, b| if reverse { 1.to_int32() } else { (-1).to_int32() })
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
= note: C calls it with its arguments alone, so it has nowhere to keep a closure's captured values; pass what it needs through C (most C functions that take a callback also take a pointer for it)
1 error
C may call a callback only during the call it was given to. A panic in a callback ends the program, since nothing can unwind through C's frames.
Callbacks C keeps
Some libraries call back on their own schedule: a timer fires, an event loop sees a socket, a thread they started begins. They keep the pointer and call it later, often from a thread of their own, where no Limen task is running. For those, declare the parameter Kept[fn(...)] and pass a channel. Every call from C sends its arguments on the channel, and a task receives them like any other message:
foreign "c" {
// C keeps `start` and calls it later, on a thread of its own
fn pthread_create(thread: Out[Handle], attr: Handle, start: Kept[fn(Handle)], arg: Handle) -> Int32
fn pthread_join(thread: Handle, result: Handle) -> Int32
}
fn main(root: Root) {
let f = root.foreign
let started: Chan[Handle] = channel(0)
let mut threads: List[Handle] = []
for i in 1..<4 {
let (_, t) = pthread_create(f, Handle { addr: 0 }, started, Handle { addr: i })
threads.push(t)
}
let mut seen: List[Int] = []
for _ in 0..<3 {
match started.recv() {
Some(h) => seen.push(h.addr),
None => {},
}
}
for t in threads {
pthread_join(f, t, Handle { addr: 0 })
}
root.stdout.print("threads {seen.sort()} started")
}$ limen run main.lmn --grant foreign=c
limen: warning: --grant foreign=c is full access: C code can do anything this process can, past every other grant
threads [1, 2, 3] started
The channel carries what C passes: one value, a tuple of several (Kept[fn(Handle, Int32)] takes a Chan[(Handle, Int32)]), or () for none. A kept callback returns nothing, since C gets no answer from a channel. A call from C never waits: when nobody is receiving and the channel is full, it grows. C may hold the pointer for the rest of the program, so the same channel always gives the same pointer, and a program can give C 32 channels at most.
No Limen code runs on C's thread. That's the point: everything that happens because of the call happens in a task, where it can wait, fail and be cancelled like the rest of the program.
Calls that take long
Mark a declaration blocking and its calls run on a separate pool of threads. Without it, a C call runs on the thread of the task that makes it. Most C functions return at once, and that's the fastest way to call them. Some take long, though, like a database query, a sleep or a read from a slow disk, and while such a call runs, its thread can't run any other task. With blocking, the task that made the call waits, as it would for a socket, and its own thread goes on running other tasks:
foreign "c" {
// int usleep(useconds_t microseconds): sleeps, holding its thread
blocking fn usleep(microseconds: Int32) -> Int32
}
fn nap(c: Foreign, name: Str) -> Str {
let _ = usleep(c, 200_000)
"{name} woke up"
}
fn main(root: Root) {
let c = root.foreign.only("c")
let clock = root.clock
let start = clock.now_ms()
let naps = group g {
for name in ["a", "b", "c", "d"] {
g.go(|| nap(c, name))
}
}
let ms = clock.now_ms() - start
root.stdout.print("{naps}")
root.stdout.print("four 200 ms naps took less than 400 ms: {ms < 400}")
}$ limen run main.lmn --grant foreign=c
limen: warning: --grant foreign=c is full access: C code can do anything this process can, past every other grant
["a woke up", "b woke up", "c woke up", "d woke up"]
four 200 ms naps took less than 400 ms: true
$ LIMEN_THREADS=1 limen run main.lmn --grant foreign=c
limen: warning: --grant foreign=c is full access: C code can do anything this process can, past every other grant
["a woke up", "b woke up", "c woke up", "d woke up"]
four 200 ms naps took less than 400 ms: true
Each usleep holds its thread for 200 ms. The four calls run at the same time on the pool, so the group is done in about 200 ms. That holds with a single worker thread too, LIMEN_THREADS=1:
$ LIMEN_THREADS=1 limen run main.lmn --grant foreign=c
limen: warning: --grant foreign=c is full access: C code can do anything this process can, past every other grant
["a woke up", "b woke up", "c woke up", "d woke up"]
four 200 ms naps took less than 400 ms: true
plain.lmn is the same program without the word blocking. With one worker thread, each sleep holds that thread, and the four come one after another:
$ LIMEN_THREADS=1 limen run plain.lmn --grant foreign=c
limen: warning: --grant foreign=c is full access: C code can do anything this process can, past every other grant
["a woke up", "b woke up", "c woke up", "d woke up"]
four 200 ms naps took less than 400 ms: false
limen caps shows which C libraries each function reaches, here only c, since main narrowed its Foreign with only("c"):
$ limen caps main.lmn
usleep Foreign (c)
nap Foreign (c)
main Root
Crossing to another thread and back costs a little on every call, so blocking is for calls that can take long, not for every C function. The pool starts threads as calls need them, up to 64, or LIMEN_BLOCKING_THREADS. A blocking function can't take a callback, since C may call a callback only on the task's own thread. If a task is cancelled while its blocking call is in C, the task stops waiting at once; the call finishes in the background, and its result is dropped.
The sql module declares SQLite's slow calls this way, so a long query holds up only its own task.
Memory
Arguments are lent to C for the duration of the call: a Str or Bytes pointer is valid only until the call returns, so C must copy what it keeps. A mut b: Bytes parameter is a buffer C may write into, b.len() bytes long, so size it first with bytes_of(0, n). Memory C allocates belongs to C, and you free it with the library's own function, as with free above. f.copy(p, n) copies n bytes of C memory into Limen Bytes: that's how results that are a pointer and a length come back.
Native builds link the libraries with -l. The playground can't call C, so it refuses a program that does.
Summary
Foreign blocks declare C functions, and calling one takes the Foreign capability, which only narrows to one library. A callback C keeps is a channel each call sends on. Calls that take long are declared blocking and run on a separate pool of threads. C runs outside every check, so granting it is full trust: only the program grants it, dependencies need [trust], limen run warns, and the sandbox still limits the process. Keep C behind a small, safe module, the way sql does.
You now know the whole language. In the last chapter we'll use it to build a small web service.