]> git.lizzy.rs Git - rust.git/blob - src/doc/guide-ffi.md
auto merge of #13967 : richo/rust/features/ICE-fails, r=alexcrichton
[rust.git] / src / doc / guide-ffi.md
1 % The Rust Foreign Function Interface Guide
2
3 # Introduction
4
5 This guide will use the [snappy](https://code.google.com/p/snappy/)
6 compression/decompression library as an introduction to writing bindings for
7 foreign code. Rust is currently unable to call directly into a C++ library, but
8 snappy includes a C interface (documented in
9 [`snappy-c.h`](https://code.google.com/p/snappy/source/browse/trunk/snappy-c.h)).
10
11 The following is a minimal example of calling a foreign function which will
12 compile if snappy is installed:
13
14 ~~~~no_run
15 extern crate libc;
16 use libc::size_t;
17
18 #[link(name = "snappy")]
19 extern {
20     fn snappy_max_compressed_length(source_length: size_t) -> size_t;
21 }
22
23 fn main() {
24     let x = unsafe { snappy_max_compressed_length(100) };
25     println!("max compressed length of a 100 byte buffer: {}", x);
26 }
27 ~~~~
28
29 The `extern` block is a list of function signatures in a foreign library, in
30 this case with the platform's C ABI. The `#[link(...)]` attribute is used to
31 instruct the linker to link against the snappy library so the symbols are
32 resolved.
33
34 Foreign functions are assumed to be unsafe so calls to them need to be wrapped
35 with `unsafe {}` as a promise to the compiler that everything contained within
36 truly is safe. C libraries often expose interfaces that aren't thread-safe, and
37 almost any function that takes a pointer argument isn't valid for all possible
38 inputs since the pointer could be dangling, and raw pointers fall outside of
39 Rust's safe memory model.
40
41 When declaring the argument types to a foreign function, the Rust compiler can
42 not check if the declaration is correct, so specifying it correctly is part of
43 keeping the binding correct at runtime.
44
45 The `extern` block can be extended to cover the entire snappy API:
46
47 ~~~~no_run
48 extern crate libc;
49 use libc::{c_int, size_t};
50
51 #[link(name = "snappy")]
52 extern {
53     fn snappy_compress(input: *u8,
54                        input_length: size_t,
55                        compressed: *mut u8,
56                        compressed_length: *mut size_t) -> c_int;
57     fn snappy_uncompress(compressed: *u8,
58                          compressed_length: size_t,
59                          uncompressed: *mut u8,
60                          uncompressed_length: *mut size_t) -> c_int;
61     fn snappy_max_compressed_length(source_length: size_t) -> size_t;
62     fn snappy_uncompressed_length(compressed: *u8,
63                                   compressed_length: size_t,
64                                   result: *mut size_t) -> c_int;
65     fn snappy_validate_compressed_buffer(compressed: *u8,
66                                          compressed_length: size_t) -> c_int;
67 }
68 # fn main() {}
69 ~~~~
70
71 # Creating a safe interface
72
73 The raw C API needs to be wrapped to provide memory safety and make use of higher-level concepts
74 like vectors. A library can choose to expose only the safe, high-level interface and hide the unsafe
75 internal details.
76
77 Wrapping the functions which expect buffers involves using the `slice::raw` module to manipulate Rust
78 vectors as pointers to memory. Rust's vectors are guaranteed to be a contiguous block of memory. The
79 length is number of elements currently contained, and the capacity is the total size in elements of
80 the allocated memory. The length is less than or equal to the capacity.
81
82 ~~~~
83 # extern crate libc;
84 # use libc::{c_int, size_t};
85 # unsafe fn snappy_validate_compressed_buffer(_: *u8, _: size_t) -> c_int { 0 }
86 # fn main() {}
87 pub fn validate_compressed_buffer(src: &[u8]) -> bool {
88     unsafe {
89         snappy_validate_compressed_buffer(src.as_ptr(), src.len() as size_t) == 0
90     }
91 }
92 ~~~~
93
94 The `validate_compressed_buffer` wrapper above makes use of an `unsafe` block, but it makes the
95 guarantee that calling it is safe for all inputs by leaving off `unsafe` from the function
96 signature.
97
98 The `snappy_compress` and `snappy_uncompress` functions are more complex, since a buffer has to be
99 allocated to hold the output too.
100
101 The `snappy_max_compressed_length` function can be used to allocate a vector with the maximum
102 required capacity to hold the compressed output. The vector can then be passed to the
103 `snappy_compress` function as an output parameter. An output parameter is also passed to retrieve
104 the true length after compression for setting the length.
105
106 ~~~~
107 # extern crate libc;
108 # use libc::{size_t, c_int};
109 # unsafe fn snappy_compress(a: *u8, b: size_t, c: *mut u8,
110 #                           d: *mut size_t) -> c_int { 0 }
111 # unsafe fn snappy_max_compressed_length(a: size_t) -> size_t { a }
112 # fn main() {}
113 pub fn compress(src: &[u8]) -> Vec<u8> {
114     unsafe {
115         let srclen = src.len() as size_t;
116         let psrc = src.as_ptr();
117
118         let mut dstlen = snappy_max_compressed_length(srclen);
119         let mut dst = Vec::with_capacity(dstlen as uint);
120         let pdst = dst.as_mut_ptr();
121
122         snappy_compress(psrc, srclen, pdst, &mut dstlen);
123         dst.set_len(dstlen as uint);
124         dst
125     }
126 }
127 ~~~~
128
129 Decompression is similar, because snappy stores the uncompressed size as part of the compression
130 format and `snappy_uncompressed_length` will retrieve the exact buffer size required.
131
132 ~~~~
133 # extern crate libc;
134 # use libc::{size_t, c_int};
135 # unsafe fn snappy_uncompress(compressed: *u8,
136 #                             compressed_length: size_t,
137 #                             uncompressed: *mut u8,
138 #                             uncompressed_length: *mut size_t) -> c_int { 0 }
139 # unsafe fn snappy_uncompressed_length(compressed: *u8,
140 #                                      compressed_length: size_t,
141 #                                      result: *mut size_t) -> c_int { 0 }
142 # fn main() {}
143 pub fn uncompress(src: &[u8]) -> Option<Vec<u8>> {
144     unsafe {
145         let srclen = src.len() as size_t;
146         let psrc = src.as_ptr();
147
148         let mut dstlen: size_t = 0;
149         snappy_uncompressed_length(psrc, srclen, &mut dstlen);
150
151         let mut dst = Vec::with_capacity(dstlen as uint);
152         let pdst = dst.as_mut_ptr();
153
154         if snappy_uncompress(psrc, srclen, pdst, &mut dstlen) == 0 {
155             dst.set_len(dstlen as uint);
156             Some(dst)
157         } else {
158             None // SNAPPY_INVALID_INPUT
159         }
160     }
161 }
162 ~~~~
163
164 For reference, the examples used here are also available as an [library on
165 GitHub](https://github.com/thestinger/rust-snappy).
166
167 # Stack management
168
169 Rust tasks by default run on a "large stack". This is actually implemented as a
170 reserving a large segment of the address space and then lazily mapping in pages
171 as they are needed. When calling an external C function, the code is invoked on
172 the same stack as the rust stack. This means that there is no extra
173 stack-switching mechanism in place because it is assumed that the large stack
174 for the rust task is plenty for the C function to have.
175
176 A planned future improvement (net yet implemented at the time of this writing)
177 is to have a guard page at the end of every rust stack. No rust function will
178 hit this guard page (due to Rust's usage of LLVM's `__morestack`). The intention
179 for this unmapped page is to prevent infinite recursion in C from overflowing
180 onto other rust stacks. If the guard page is hit, then the process will be
181 terminated with a message saying that the guard page was hit.
182
183 For normal external function usage, this all means that there shouldn't be any
184 need for any extra effort on a user's perspective. The C stack naturally
185 interleaves with the rust stack, and it's "large enough" for both to
186 interoperate. If, however, it is determined that a larger stack is necessary,
187 there are appropriate functions in the task spawning API to control the size of
188 the stack of the task which is spawned.
189
190 # Destructors
191
192 Foreign libraries often hand off ownership of resources to the calling code.
193 When this occurs, we must use Rust's destructors to provide safety and guarantee
194 the release of these resources (especially in the case of failure).
195
196 # Callbacks from C code to Rust functions
197
198 Some external libraries require the usage of callbacks to report back their
199 current state or intermediate data to the caller.
200 It is possible to pass functions defined in Rust to an external library.
201 The requirement for this is that the callback function is marked as `extern`
202 with the correct calling convention to make it callable from C code.
203
204 The callback function that can then be sent to through a registration call
205 to the C library and afterwards be invoked from there.
206
207 A basic example is:
208
209 Rust code:
210
211 ~~~~no_run
212 extern fn callback(a:i32) {
213     println!("I'm called from C with value {0}", a);
214 }
215
216 #[link(name = "extlib")]
217 extern {
218    fn register_callback(cb: extern fn(i32)) -> i32;
219    fn trigger_callback();
220 }
221
222 fn main() {
223     unsafe {
224         register_callback(callback);
225         trigger_callback(); // Triggers the callback
226     }
227 }
228 ~~~~
229
230 C code:
231
232 ~~~~ {.notrust}
233 typedef void (*rust_callback)(int32_t);
234 rust_callback cb;
235
236 int32_t register_callback(rust_callback callback) {
237     cb = callback;
238     return 1;
239 }
240
241 void trigger_callback() {
242   cb(7); // Will call callback(7) in Rust
243 }
244 ~~~~
245
246 In this example will Rust's `main()` will call `do_callback()` in C,
247 which would call back to `callback()` in Rust.
248
249
250 ## Targetting callbacks to Rust objects
251
252 The former example showed how a global function can be called from C code.
253 However it is often desired that the callback is targetted to a special
254 Rust object. This could be the object that represents the wrapper for the
255 respective C object.
256
257 This can be achieved by passing an unsafe pointer to the object down to the
258 C library. The C library can then include the pointer to the Rust object in
259 the notification. This will allow the callback to unsafely access the
260 referenced Rust object.
261
262 Rust code:
263
264 ~~~~no_run
265
266 struct RustObject {
267     a: i32,
268     // other members
269 }
270
271 extern fn callback(target: *mut RustObject, a:i32) {
272     println!("I'm called from C with value {0}", a);
273     unsafe {
274         // Update the value in RustObject with the value received from the callback
275         (*target).a = a;
276     }
277 }
278
279 #[link(name = "extlib")]
280 extern {
281    fn register_callback(target: *mut RustObject,
282                         cb: extern fn(*mut RustObject, i32)) -> i32;
283    fn trigger_callback();
284 }
285
286 fn main() {
287     // Create the object that will be referenced in the callback
288     let mut rust_object = box RustObject { a: 5 };
289
290     unsafe {
291         register_callback(&mut *rust_object, callback);
292         trigger_callback();
293     }
294 }
295 ~~~~
296
297 C code:
298
299 ~~~~ {.notrust}
300 typedef void (*rust_callback)(int32_t);
301 void* cb_target;
302 rust_callback cb;
303
304 int32_t register_callback(void* callback_target, rust_callback callback) {
305     cb_target = callback_target;
306     cb = callback;
307     return 1;
308 }
309
310 void trigger_callback() {
311   cb(cb_target, 7); // Will call callback(&rustObject, 7) in Rust
312 }
313 ~~~~
314
315 ## Asynchronous callbacks
316
317 In the previously given examples the callbacks are invoked as a direct reaction
318 to a function call to the external C library.
319 The control over the current thread is switched from Rust to C to Rust for the
320 execution of the callback, but in the end the callback is executed on the
321 same thread (and Rust task) that lead called the function which triggered
322 the callback.
323
324 Things get more complicated when the external library spawns its own threads
325 and invokes callbacks from there.
326 In these cases access to Rust data structures inside the callbacks is
327 especially unsafe and proper synchronization mechanisms must be used.
328 Besides classical synchronization mechanisms like mutexes, one possibility in
329 Rust is to use channels (in `std::comm`) to forward data from the C thread
330 that invoked the callback into a Rust task.
331
332 If an asynchronous callback targets a special object in the Rust address space
333 it is also absolutely necessary that no more callbacks are performed by the
334 C library after the respective Rust object gets destroyed.
335 This can be achieved by unregistering the callback in the object's
336 destructor and designing the library in a way that guarantees that no
337 callback will be performed after unregistration.
338
339 # Linking
340
341 The `link` attribute on `extern` blocks provides the basic building block for
342 instructing rustc how it will link to native libraries. There are two accepted
343 forms of the link attribute today:
344
345 * `#[link(name = "foo")]`
346 * `#[link(name = "foo", kind = "bar")]`
347
348 In both of these cases, `foo` is the name of the native library that we're
349 linking to, and in the second case `bar` is the type of native library that the
350 compiler is linking to. There are currently three known types of native
351 libraries:
352
353 * Dynamic - `#[link(name = "readline")]
354 * Static - `#[link(name = "my_build_dependency", kind = "static")]
355 * Frameworks - `#[link(name = "CoreFoundation", kind = "framework")]
356
357 Note that frameworks are only available on OSX targets.
358
359 The different `kind` values are meant to differentiate how the native library
360 participates in linkage. From a linkage perspective, the rust compiler creates
361 two flavors of artifacts: partial (rlib/staticlib) and final (dylib/binary).
362 Native dynamic libraries and frameworks are propagated to the final artifact
363 boundary, while static libraries are not propagated at all.
364
365 A few examples of how this model can be used are:
366
367 * A native build dependency. Sometimes some C/C++ glue is needed when writing
368   some rust code, but distribution of the C/C++ code in a library format is just
369   a burden. In this case, the code will be archived into `libfoo.a` and then the
370   rust crate would declare a dependency via `#[link(name = "foo", kind =
371   "static")]`.
372
373   Regardless of the flavor of output for the crate, the native static library
374   will be included in the output, meaning that distribution of the native static
375   library is not necessary.
376
377 * A normal dynamic dependency. Common system libraries (like `readline`) are
378   available on a large number of systems, and often a static copy of these
379   libraries cannot be found. When this dependency is included in a rust crate,
380   partial targets (like rlibs) will not link to the library, but when the rlib
381   is included in a final target (like a binary), the native library will be
382   linked in.
383
384 On OSX, frameworks behave with the same semantics as a dynamic library.
385
386 ## The `link_args` attribute
387
388 There is one other way to tell rustc how to customize linking, and that is via
389 the `link_args` attribute. This attribute is applied to `extern` blocks and
390 specifies raw flags which need to get passed to the linker when producing an
391 artifact. An example usage would be:
392
393 ~~~ no_run
394 #![feature(link_args)]
395
396 #[link_args = "-foo -bar -baz"]
397 extern {}
398 # fn main() {}
399 ~~~
400
401 Note that this feature is currently hidden behind the `feature(link_args)` gate
402 because this is not a sanctioned way of performing linking. Right now rustc
403 shells out to the system linker, so it makes sense to provide extra command line
404 arguments, but this will not always be the case. In the future rustc may use
405 LLVM directly to link native libraries in which case `link_args` will have no
406 meaning.
407
408 It is highly recommended to *not* use this attribute, and rather use the more
409 formal `#[link(...)]` attribute on `extern` blocks instead.
410
411 # Unsafe blocks
412
413 Some operations, like dereferencing unsafe pointers or calling functions that have been marked
414 unsafe are only allowed inside unsafe blocks. Unsafe blocks isolate unsafety and are a promise to
415 the compiler that the unsafety does not leak out of the block.
416
417 Unsafe functions, on the other hand, advertise it to the world. An unsafe function is written like
418 this:
419
420 ~~~~
421 unsafe fn kaboom(ptr: *int) -> int { *ptr }
422 ~~~~
423
424 This function can only be called from an `unsafe` block or another `unsafe` function.
425
426 # Accessing foreign globals
427
428 Foreign APIs often export a global variable which could do something like track
429 global state. In order to access these variables, you declare them in `extern`
430 blocks with the `static` keyword:
431
432 ~~~no_run
433 extern crate libc;
434
435 #[link(name = "readline")]
436 extern {
437     static rl_readline_version: libc::c_int;
438 }
439
440 fn main() {
441     println!("You have readline version {} installed.",
442              rl_readline_version as int);
443 }
444 ~~~
445
446 Alternatively, you may need to alter global state provided by a foreign
447 interface. To do this, statics can be declared with `mut` so rust can mutate
448 them.
449
450 ~~~no_run
451 extern crate libc;
452 use std::ptr;
453
454 #[link(name = "readline")]
455 extern {
456     static mut rl_prompt: *libc::c_char;
457 }
458
459 fn main() {
460     "[my-awesome-shell] $".with_c_str(|buf| {
461         unsafe { rl_prompt = buf; }
462         // get a line, process it
463         unsafe { rl_prompt = ptr::null(); }
464     });
465 }
466 ~~~
467
468 # Foreign calling conventions
469
470 Most foreign code exposes a C ABI, and Rust uses the platform's C calling convention by default when
471 calling foreign functions. Some foreign functions, most notably the Windows API, use other calling
472 conventions. Rust provides a way to tell the compiler which convention to use:
473
474 ~~~~
475 extern crate libc;
476
477 #[cfg(target_os = "win32", target_arch = "x86")]
478 #[link(name = "kernel32")]
479 extern "stdcall" {
480     fn SetEnvironmentVariableA(n: *u8, v: *u8) -> libc::c_int;
481 }
482 # fn main() { }
483 ~~~~
484
485 This applies to the entire `extern` block. The list of supported ABI constraints
486 are:
487
488 * `stdcall`
489 * `aapcs`
490 * `cdecl`
491 * `fastcall`
492 * `Rust`
493 * `rust-intrinsic`
494 * `system`
495 * `C`
496
497 Most of the abis in this list are self-explanatory, but the `system` abi may
498 seem a little odd. This constraint selects whatever the appropriate ABI is for
499 interoperating with the target's libraries. For example, on win32 with a x86
500 architecture, this means that the abi used would be `stdcall`. On x86_64,
501 however, windows uses the `C` calling convention, so `C` would be used. This
502 means that in our previous example, we could have used `extern "system" { ... }`
503 to define a block for all windows systems, not just x86 ones.
504
505 # Interoperability with foreign code
506
507 Rust guarantees that the layout of a `struct` is compatible with the platform's representation in C.
508 A `#[packed]` attribute is available, which will lay out the struct members without padding.
509 However, there are currently no guarantees about the layout of an `enum`.
510
511 Rust's owned and managed boxes use non-nullable pointers as handles which point to the contained
512 object. However, they should not be manually created because they are managed by internal
513 allocators. References can safely be assumed to be non-nullable pointers directly to the
514 type. However, breaking the borrow checking or mutability rules is not guaranteed to be safe, so
515 prefer using raw pointers (`*`) if that's needed because the compiler can't make as many assumptions
516 about them.
517
518 Vectors and strings share the same basic memory layout, and utilities are available in the `vec` and
519 `str` modules for working with C APIs. However, strings are not terminated with `\0`. If you need a
520 NUL-terminated string for interoperability with C, you should use the `c_str::to_c_str` function.
521
522 The standard library includes type aliases and function definitions for the C standard library in
523 the `libc` module, and Rust links against `libc` and `libm` by default.
524
525 # The "nullable pointer optimization"
526
527 Certain types are defined to not be `null`. This includes references (`&T`,
528 `&mut T`), owning pointers (`~T`), and function pointers (`extern "abi"
529 fn()`). When interfacing with C, pointers that might be null are often used.
530 As a special case, a generic `enum` that contains exactly two variants, one of
531 which contains no data and the other containing a single field, is eligible
532 for the "nullable pointer optimization". When such an enum is instantiated
533 with one of the non-nullable types, it is represented as a single pointer,
534 and the non-data variant is represented as the null pointer. So
535 `Option<extern "C" fn(c_int) -> c_int>` is how one represents a nullable
536 function pointer using the C ABI.