text
stringlengths
10
16.2k
##### Evaluation order Beware that the tail-modulo-cons transformation has an effect on evaluation order: the constructor argument that is transformed into tail-position will always be evaluated last. Consider the following example: type 'a two_headed_list = \| Nil \| Consnoc of 'a \* 'a two_headed_list \* 'a let\[@tail_mod_cons\] rec map f = function \| Nil -> Nil \| Consnoc (front, body, rear) -> Consnoc (f front, map f body, f rear) Due to the \[@tail_mod_cons\] transformation, the calls to f front and f rear will be evaluated before map f body. In particular, this is likely to be different from the evaluation order of the unannotated version. (The evaluation order of constructor arguments is unspecified in OCaml, but many implementations typically use left-to-right or right-to-left.) This effect on evaluation order is one of the reasons why the tail-modulo-cons transformation has to be explicitly requested by the user, instead of being applied as an automatic optimization.
##### Why tail-modulo-cons? Other program transformations, in particular a transformation to continuation-passing style (CPS), can make all functions tail-recursive, instead of targeting only a small fragment. Some reasons to provide builtin support for the less-general tail-mod-cons are as follows: - The tail-mod-cons transformation preserves the performance of the original, non-tail-recursive version, while a continuation-passing-style transformation incurs a measurable constant-factor overhead. - The tail-mod-cons transformation cannot be expressed as a source-to-source transformation of OCaml programs, as it relies on mutable state in type-unsafe ways. In contrast, continuation-passing-style versions can be written by hand, possibly using a convenient monadic notation.
##### Note: OCaml call stack size In OCaml 4.x and earlier, bytecode programs respect the stack_limit runtime parameter configuration (as set using Gc.set in the example above), or the l setting of the OCAMLRUNPARAM variable. Native programs ignore these settings and only respect the operating system native stack limit, as set by ulimit on Unix systems. Most operating systems run with a relatively low stack size limit by default, so stack overflow on non-tail-recursive functions are a common programming bug. Starting from OCaml 5.0, native code does not use the native system stack for OCaml function calls anymore, so it is not affected by the operating system native stack size; both native and bytecode programs respect the OCaml runtime’s own limit. The runtime limit is set to a much higher default than most operating system native stacks, with a limit of at least 512MiB, so stack overflow should be much less common in practice. There is still a stack limit by default, as it remains useful to quickly catch bugs with looping non-tail-recursive functions. Without a stack limit, one has to wait for the whole memory to be consumed by the stack for the program to crash, which can take a long time and make the system unresponsive. This means that the tail modulo constructor transformation is less important on OCaml 5: it does improve performance noticeably in some cases, but it is not necessary for basic correctness for most use-cases.
## 1 Disambiguation It may happen that several arguments of a constructor are recursive calls to a tail-modulo-cons function. The transformation can only turn one of these calls into a tail call. The compiler will not make an implicit choice, but ask the user to provide an explicit disambiguation. Consider this type of syntactic expressions (assuming some pre-existing type var of expression variables): type var (\* some pre-existing type of variables \*) type exp = \| Var of var \| Let of binding \* exp and binding = var \* exp Consider a map function on variables. The direct definition has two recursive calls inside arguments of the Let constructor, so it gets rejected as ambiguous. let\[@tail_mod_cons\] rec map_vars f exp = match exp with \| Var v -> Var (f v) \| Let ((v, def), body) -> Let ((f v, map_vars f def), map_vars f body) Error: \[@tail_mod_cons\]: this constructor application may be TMC-transformed in several different ways. Please disambiguate by adding an explicit \[@tailcall\] attribute to the call that should be made tail-recursive, or a \[@tailcall false\] attribute on calls that should not be transformed. This call could be annotated. This call could be annotated. To disambiguate, the user should add a \[@tailcall\] attribute to the recursive call that should be transformed to tail position: let\[@tail_mod_cons\] rec map_vars f exp = match exp with \| Var v -> Var (f v) \| Let ((v, def), body) -> Let ((f v, map_vars f def), (map_vars\[@tailcall\]) f body)
## 1 Disambiguation Be aware that the resulting function is *not* tail-recursive, the recursive call on def will consume stack space. However, expression trees tend to be right-leaning (lots of Let in sequence, rather than nested inside each other), so putting the call on body in tail position is an interesting improvement over the naive definition: it gives bounded stack space consumption if we assume a bound on the nesting depth of Let constructs. One would also get an error when using conflicting annotations, asking for two of the constructor arguments to be put in tail position: let\[@tail_mod_cons\] rec map_vars f exp = match exp with \| Var v -> Var (f v) \| Let ((v, def), body) -> Let ((f v, (map_vars\[@tailcall\]) f def), (map_vars\[@tailcall\]) f body) Error: \[@tail_mod_cons\]: this constructor application may be TMC-transformed in several different ways. Only one of the arguments may become a TMC call, but several arguments contain calls that are explicitly marked as tail-recursive. Please fix the conflict by reviewing and fixing the conflicting annotations. This call is explicitly annotated. This call is explicitly annotated.
## 2 Danger: getting out of tail-mod-cons Due to the nature of the tail-mod-cons transformation (see Section ‍[26.3](#sec%3Adetails) for a presentation of transformation): - Calls from a tail-mod-cons function to another tail-mod-cons function declared in the same recursive-binding group are transformed into tail calls, as soon as they occur in tail position or tail-modulo-cons position in the source function. - Calls from a function *not* annotated tail-mod-cons to a tail-mod-cons function or, conversely, from a tail-mod-cons function to a non-tail-mod-cons function are transformed into *non*-tail calls, even if they syntactically appear in tail position in the source program. The fact that calls in tail position in the source program may become non-tail calls if they go from a tail-mod-cons to a non-tail-mod-cons function is surprising, and the transformation will warn about them. For example: let\[@tail_mod_cons\] rec flatten = function \| \[\] -> \[\] \| xs :: xss -> let rec append_flatten xs xss = match xs with \| \[\] -> flatten xss \| x :: xs -> x :: append_flatten xs xss in append_flatten xs xss
## 2 Danger: getting out of tail-mod-cons Warning 71 \[unused-tmc-attribute\]: This function is marked @tail_mod_cons but is never applied in TMC position. Warning 72 \[tmc-breaks-tailcall\]: This call is in tail-modulo-cons position in a TMC function, but the function called is not itself specialized for TMC, so the call will not be transformed into a tail call. Please either mark the called function with the \[@tail_mod_cons\] attribute, or mark this call with the \[@tailcall false\] attribute to make its non-tailness explicit. Here the append_flatten helper is not annotated with \[@tail_mod_cons\], so the calls append_flatten xs xss and flatten xss will *not* be tail calls. The correct fix here is to annotate append_flatten to be tail-mod-cons. let\[@tail_mod_cons\] rec flatten = function \| \[\] -> \[\] \| xs :: xss -> let\[@tail_mod_cons\] rec append_flatten xs xss = match xs with \| \[\] -> flatten xss \| x :: xs -> x :: append_flatten xs xss in append_flatten xs xss The same warning occurs when append_flatten is a non-tail-mod-cons function of the same recursive group; using the tail-mod-cons transformation is a property of individual functions, not whole recursive groups. let\[@tail_mod_cons\] rec flatten = function \| \[\] -> \[\] \| xs :: xss -> append_flatten xs xss and append_flatten xs xss = match xs with \| \[\] -> flatten xss \| x :: xs -> x :: append_flatten xs xss
## 2 Danger: getting out of tail-mod-cons Warning 71 \[unused-tmc-attribute\]: This function is marked @tail_mod_cons but is never applied in TMC position. Warning 72 \[tmc-breaks-tailcall\]: This call is in tail-modulo-cons position in a TMC function, but the function called is not itself specialized for TMC, so the call will not be transformed into a tail call. Please either mark the called function with the \[@tail_mod_cons\] attribute, or mark this call with the \[@tailcall false\] attribute to make its non-tailness explicit. Again, the fix is to specialize append_flatten as well: let\[@tail_mod_cons\] rec flatten = function \| \[\] -> \[\] \| xs :: xss -> append_flatten xs xss and\[@tail_mod_cons\] append_flatten xs xss = match xs with \| \[\] -> flatten xss \| x :: xs -> x :: append_flatten xs xss Non-recursive functions can also be annotated \[@tail_mod_cons\]; this is typically useful for local bindings to recursive functions. Incorrect version: let\[@tail_mod_cons\] rec map_vars f exp = let self exp = map_vars f exp in match exp with \| Var v -> Var (f v) \| Let ((v, def), body) -> Let ((f v, self def), (self\[@tailcall\]) body) Warning 51 \[wrong-tailcall-expectation\]: expected tailcall Warning 51 \[wrong-tailcall-expectation\]: expected tailcall Warning 71 \[unused-tmc-attribute\]: This function is marked @tail_mod_cons but is never applied in TMC position. Recommended fix:
## 2 Danger: getting out of tail-mod-cons let\[@tail_mod_cons\] rec map_vars f exp = let\[@tail_mod_cons\] self exp = map_vars f exp in match exp with \| Var v -> Var (f v) \| Let ((v, def), body) -> Let ((f v, self def), (self\[@tailcall\]) body) In other cases, there is either no benefit in making the called function tail-mod-cons, or it is not possible: for example, it is a function parameter (the transformation only works with direct calls to known functions). For example, consider a substitution function on binary trees: type 'a tree = Leaf of 'a \| Node of 'a tree \* 'a tree let\[@tail_mod_cons\] rec bind (f : 'a -> 'a tree) (t : 'a tree) : 'a tree = match t with \| Leaf v -> f v \| Node (left, right) -> Node (bind f left, (bind\[@tailcall\]) f right) Warning 72 \[tmc-breaks-tailcall\]: This call is in tail-modulo-cons position in a TMC function, but the function called is not itself specialized for TMC, so the call will not be transformed into a tail call. Please either mark the called function with the \[@tail_mod_cons\] attribute, or mark this call with the \[@tailcall false\] attribute to make its non-tailness explicit. Here f is a function parameter, not a direct call, and the current implementation is strictly first-order, it does not support tail-mod-cons arguments. In this case, the user should indicate that they realize this call to f v is not, in fact, in tail position, by using (f\[@tailcall false\]) v.
## 2 Danger: getting out of tail-mod-cons type 'a tree = Leaf of 'a \| Node of 'a tree \* 'a tree let\[@tail_mod_cons\] rec bind (f : 'a -> 'a tree) (t : 'a tree) : 'a tree = match t with \| Leaf v -> (f\[@tailcall false\]) v \| Node (left, right) -> Node (bind f left, (bind\[@tailcall\]) f right)
## 3 Details on the transformation To use this advanced feature, it helps to be aware that the function transformation produces a specialized function in destination-passing-style. Recall our map example: let rec map f l = match l with \| \[\] -> \[\] \| x :: xs -> let y = f x in y :: map f xs Below is a description of the transformed program in pseudo-OCaml notation: some operations are not expressible in OCaml source code. (The transformation in fact happens on the Lambda intermediate representation of the OCaml compiler.) let rec map f l = match l with | [] -> [] | x :: xs -> let y = f x in let dst = y ::{mutable} Hole in map_dps f xs dst 1; dst and map_dps f l dst idx = match l with | [] -> dst.idx <- [] | x :: xs -> let y = f x in let dst' = y ::{mutable} Hole in dst.idx <- dst'; map_dps f xs dst' 1 The source version of map gets transformed into two functions, a *direct-style* version that is also called map, and a *destination-passing-style* version (DPS) called map_dps. The destination-passing-style version does not return a result directly, instead it writes it into a memory location specified by two additional function parameters, dst (a memory block) and i (a position within the memory block). The source call y :: map f xs gets transformed into the creation of a mutable block y ::{mutable} Hole, whose second parameter is an un-initialized *hole*. The block is then passed to map_dps as a destination parameter (with offset 1).
## 3 Details on the transformation Notice that map does not call itself recursively, it calls map_dps. Then, map_dps calls itself recursively, in a tail-recursive way. The call from map to map_dps is *not* a tail call (this is something that we could improve in the future); but this call happens only once when invoking map f l, with all list elements after the first one processed in constant stack by map_dps. This explains the “getting out of tail-mod-cons” subtleties. Consider our previous example involving mutual recursion between flatten and append_flatten. let[@tail_mod_cons] rec flatten l = match l with | [] -> [] | xs :: xss -> append_flatten xs xss The call to append_flatten, which syntactically appears in tail position, gets transformed differently depending on whether the function has a destination-passing-style version available, that is, whether it is itself annotated \[@tail_mod_cons\]: (* if append_flatten_dps exists *) and flatten_dps l dst i = match l with | [] -> dst.i <- [] | xs :: xss -> append_flatten_dps xs xss dst i (* if append_flatten_dps does not exist *) and rec flatten_dps l dst i = match l with | [] -> dst.i <- [] | xs :: xss -> dst.i <- append_flatten xs xss If append_flatten does not have a destination-passing-style version, the call gets transformed to a non-tail call.
## 4 Current limitations
##### Purely syntactic criterion Just like tail calls in general, the notion of tail-modulo-constructor position is purely syntactic; some simple refactoring will move calls out of tail-modulo-constructor position. (\* works as expected \*) let\[@tail_mod_cons\] rec map f li = match li with \| \[\] -> \[\] \| x :: xs -> let y = f x in y :: (\* this call is in TMC position \*) map f xs (\* not optimizable anymore \*) let\[@tail_mod_cons\] rec map f li = match li with \| \[\] -> \[\] \| x :: xs -> let y = f x in let ys = (\* this call is not in TMC position anymore \*) map f xs in y :: ys Warning 71 \[unused-tmc-attribute\]: This function is marked @tail_mod_cons but is never applied in TMC position.
##### Local, first-order transformation When a function gets transformed with tail-mod-cons, two definitions are generated, one providing a direct-style interface and one providing the destination-passing-style version. However, not all calls to this function in tail-modulo-cons position will use the destination-passing-style version and become tail calls: - The transformation is local: only tail-mod-cons calls to foo within the same compilation unit as foo become tail calls. - The transformation is first-order: only direct calls to known tail-mod-cons functions become tail calls when in tail-mod-cons position, never calls to function parameters. Consider the call Option.map foo x for example: even if foo is called in tail-mod-cons position within the definition of Option.map, that call will never become a tail call. (This would be the case even if the call to Option.map was inside the Option module.) In general this limitation is not a problem for recursive functions: the first call from an outside module or a higher-order function will consume stack space, but further recursive calls in tail-mod-cons position will get optimized. For example, if List.map is defined as a tail-mod-cons function, calls from outside the List module will not become tail calls when in tail positions, but the recursive calls within the definition of List.map are in tail-modulo-cons positions and do become tail calls: processing the first element of the list will consume stack space, but all further elements are handled in constant space.
## 4 Current limitations These limitations may be an issue in more complex situations where mutual recursion happens between functions, with some functions not annotated tail-mod-cons, or defined across different modules, or called indirectly, for example through function parameters.
##### Non-exact calls to tupled functions OCaml performs an implicit optimization for “tupled” functions, which take a single parameter that is a tuple: let f (x, y, z) = .... Direct calls to these functions with a tuple literal argument (like f (a, b, c)) will call the “tupled” function by passing the parameters directly, instead of building a tuple of them. Other calls, either indirect calls or calls passing a more complex tuple value (like let t = (a, b, c) in f t) are compiled as “inexact” calls that go through a wrapper. The \[@tail_mod_cons\] transformation supports tupled functions, but will only optimize “exact” calls in tail position; direct calls to something other than a tuple literal will not become tail calls. The user can manually unpack a tuple to force a call to be “exact”: let (x, y, z) = t in f (x, y, z). If there is any doubt as to whether a call can be tail-mod-cons-optimized or not, one can use the \[@tailcall\] attribute on the called function, which will warn if the transformation is not possible. let rec map (f, l) = match l with \| \[\] -> \[\] \| x :: xs -> let y = f x in let args = (f, xs) in (\* this inexact call cannot be tail-optimized, so a warning will be raised \*) y :: (map\[@tailcall\]) args Warning 51 \[wrong-tailcall-expectation\]: expected tailcall ------------------------------------------------------------------------ [« Runtime tracing with runtime events](runtime-tracing.html)[Runtime detection of data races with ThreadSanitizer »](tsan.html) Copyright © 2024 Institut National de Recherche en Informatique et en Automatique
## 4 Current limitations ------------------------------------------------------------------------
# OCaml - Runtime detection of data races with ThreadSanitizer Source: https://ocaml.org/manual/5.2/tsan.html ☰ - [Batch compilation (ocamlc)](comp.html) - [The toplevel system or REPL (ocaml)](toplevel.html) - [The runtime system (ocamlrun)](runtime.html) - [Native-code compilation (ocamlopt)](native.html) - [Lexer and parser generators (ocamllex, ocamlyacc)](lexyacc.html) - [Dependency generator (ocamldep)](depend.html) - [The documentation generator (ocamldoc)](ocamldoc.html) - [The debugger (ocamldebug)](debugger.html) - [Profiling (ocamlprof)](profil.html) - [Interfacing C with OCaml](intfc.html) - [Optimisation with Flambda](flambda.html) - [Fuzzing with afl-fuzz](afl-fuzz.html) - [Runtime tracing with runtime events](runtime-tracing.html) - [The “Tail Modulo Constructor” program transformation](tail_mod_cons.html) - [Runtime detection of data races with ThreadSanitizer](tsan.html)
# Chapter 27 Runtime detection of data races with ThreadSanitizer
## 1 Overview and usage OCaml, since version 5.0, allows shared-memory parallelism and thus mutation of data shared between multiple threads. This creates the possibility of data races, i.e., unordered accesses to the same memory location with at least one of them being a write. In OCaml, data races are easy to introduce, and the behaviour of programs with data races can be unintuitive — the observed behaviours cannot be explained by simply interleaving operations from different concurrent threads. More information about data races and their consequences can be found in section ‍[9.4](parallelism.html#s%3Apar_mm_easy) and Chapter ‍[10](memorymodel.html#c%3Amemorymodel). To help detect data races, OCaml supports ThreadSantizer (TSan), a dynamic data race detector that has been successfully used in languages such as C/C++, Swift, etc. TSan support for OCaml is available since OCaml 5.2. To use TSan, you must configure the compiler with --enable-tsan. You can also install an opam switch with the TSan feature enabled as follows: opam switch create <YOUR-SWITCH-NAME-HERE> ocaml-option-tsan TSan support for OCaml is currently available for the x86_64 architecture, on FreeBSD, Linux and macOS, and for the arm64 architecture on Linux and macOS. Building OCaml with TSan support requires GCC or Clang. Minimal supported versions are GCC 11 and Clang 14. Note that TSan data race reports with GCC 11 are known to result in poor stack trace reporting (no line numbers), which is fixed in GCC 12.
## 1 Overview and usage A TSan-enabled compiler differs from a regular compiler in the following way: all programs compiled by ocamlopt are instrumented with calls to the TSan runtime, and TSan will detect data races encountered during execution. For instance, consider the following program: let a = ref 0 and b = ref 0 let d1 () = a := 1; !b let d2 () = b := 1; !a let () = let h = Domain.spawn d2 in let r1 = d1 () in let r2 = Domain.join h in assert (not (r1 = 0 && r2 = 0)) This program has data races. The memory locations a and b are read and written concurrently by multiple domains d1 and d2. a and b are “non-atomic” locations according to the memory model (see Chapter ‍[10](memorymodel.html#c%3Amemorymodel)), and there is no synchronization between accesses to them. Hence, there are two data races here corresponding to the two memory locations a and b. When you compile and run this program with ocamlopt, you may observe data race reports on the standard error, such as: ================== WARNING: ThreadSanitizer: data race (pid=3808831) Write of size 8 at 0x8febe0 by thread T1 (mutexes: write M90): #0 camlSimple_race.d2_274 simple_race.ml:8 (simple_race.exe+0x420a72) #1 camlDomain.body_706 stdlib/domain.ml:211 (simple_race.exe+0x440f2f) #2 caml_start_program <null> (simple_race.exe+0x47cf37) #3 caml_callback_exn runtime/callback.c:197 (simple_race.exe+0x445f7b) #4 domain_thread_func runtime/domain.c:1167 (simple_race.exe+0x44a113)
## 1 Overview and usage Previous read of size 8 at 0x8febe0 by main thread (mutexes: write M86): #0 camlSimple_race.d1_271 simple_race.ml:5 (simple_race.exe+0x420a22) #1 camlSimple_race.entry simple_race.ml:13 (simple_race.exe+0x420d16) #2 caml_program <null> (simple_race.exe+0x41ffb9) #3 caml_start_program <null> (simple_race.exe+0x47cf37) [...] WARNING: ThreadSanitizer: data race (pid=3808831) Read of size 8 at 0x8febf0 by thread T1 (mutexes: write M90): #0 camlSimple_race.d2_274 simple_race.ml:9 (simple_race.exe+0x420a92) #1 camlDomain.body_706 stdlib/domain.ml:211 (simple_race.exe+0x440f2f) #2 caml_start_program <null> (simple_race.exe+0x47cf37) #3 caml_callback_exn runtime/callback.c:197 (simple_race.exe+0x445f7b) #4 domain_thread_func runtime/domain.c:1167 (simple_race.exe+0x44a113) Previous write of size 8 at 0x8febf0 by main thread (mutexes: write M86): #0 camlSimple_race.d1_271 simple_race.ml:4 (simple_race.exe+0x420a01) #1 camlSimple_race.entry simple_race.ml:13 (simple_race.exe+0x420d16) #2 caml_program <null> (simple_race.exe+0x41ffb9) #3 caml_start_program <null> (simple_race.exe+0x47cf37) [...] ================== ThreadSanitizer: reported 2 warnings For each detected data race, TSan reports the location of the conflicting accesses, their nature (read, write, atomic read, etc.), and the associated stack trace.
## 1 Overview and usage If you run the above program several times, the output may vary: sometimes TSan will report two data races, sometimes one, and sometimes none. This is due to the combination of two factors: - First, TSan reports only the data races encountered during execution, i.e., conflicting, unordered memory accesses that are effectively performed. - In addition, in this program, depending on executions, there may be no such memory accesses: if d1 returns before d2 has finished spawning, then all memory accesses originating from d1 may happen-before the ones originating from d2, since spawning a domain involves inter-thread synchronization. In that case, the accesses are considered to be ordered and no data race is reported. This example illustrates the fact that data races can sometimes be hidden by unrelated synchronizing operations.
## 2 Performance implications TSan instrumentation imposes a non-negligible cost at runtime. Empirically, this cost has been observed to cause a slowdown which can range from 2x to 7x. One of the main factors of high slowdowns is frequent access to mutable data. In contrast, the initialising writes to and reads from immutable memory locations are not instrumented. TSan also allocates very large amounts of virtual memory, although it uses only a fraction of it. The memory consumption is increased by a factor between 4 and 7.
## 3 False negatives and false positives As illustrated by the previous example, TSan will only report the data races encountered during execution. Another important caveat is that TSan remembers only a finite number of memory accesses per memory location. At the time of writing, this number is 4. Data races involving a forgotten access will not be detected. Lastly, the [documentation of TSan](https://github.com/google/sanitizers/wiki/ThreadSanitizerAlgorithm) states that there is a tiny probability to miss a race if two threads access the same location at the same time. TSan may overlook data races only in these three specific cases. For data races between two memory accesses made from OCaml code, TSan does not produce false positives; that is, TSan will not emit spurious reports. When mixing OCaml and C code, through the use of C primitives, the very notion of false positive becomes less clear, as it involves two memory models – OCaml and C11. However, TSan should behave mostly as one would expect: non-atomic reads and writes in C will race with non-atomic reads and writes in OCaml, and C atomics will not race with OCaml atomics. There is one theoretical possibility of false positive: if a value is initialized from C without using caml_initialize (which is allowed under the condition that the GC does not run between the allocation and the write, see Chapter ‍[22](intfc.html#c%3Aintf-c)) and a conflicting access is made later by another thread. This does not constitute a data race, but TSan may report it as such.
## 4 Runtime options TSan supports a number of configuration options at runtime using the TSAN_OPTIONS environment variable. TSAN_OPTIONS should contain one or more options separated by spaces. See the [documentation of TSan flags](https://github.com/google/sanitizers/wiki/ThreadSanitizerFlags) and the [documentation of flags common to all sanitizers](https://github.com/google/sanitizers/wiki/SanitizerCommonFlags) for more information. Notably, TSAN_OPTIONS allows suppressing some data races from TSan reports. Suppressing data race reports is useful for intentional races or libraries that cannot be fixed. For example, to suppress reports originating from functions in the OCaml module My_module, one can run TSAN_OPTIONS="suppressions=suppr.txt" ./my_instrumented_program with suppr.txt a file containing: race_top:^camlMy_module (Note that this depends on the format of OCaml symbols in the executable. Some builders, like Dune, might result in different formats. You should adapt this example to the symbols effectively present in your stack traces.) The TSAN_OPTIONS variable also allows for increasing the “history size”, e.g.: TSAN_OPTIONS="history_size=7" ./my_instrumented_program TSan’s history records events such as function entry and exit, and is used to reconstruct stack traces. Increasing the history size can sometimes be necessary to obtain the second stack trace, but it also increases memory consumption. This setting does not change the number of memory accesses remembered per memory location.
## 5 Guidelines for linking As a general rule, OCaml programs instrumented with TSan should only be linked with OCaml or C objects also instrumented with TSan. Doing otherwise may result in crashes. The only exception to this rule are C libraries that do not call into the OCaml runtime system in any way, i.e., do not allocate, raise exceptions, call back into OCaml code, etc. Examples include the libc or system libraries. Data races in non-instrumented libraries will not be reported. C code interacting with OCaml should always be built through the ocamlopt command, which will pass the required instrumentation flags to the C compiler. The CAMLno_tsan qualifier can be used to prevent functions from being instrumented: CAMLno_tsan void f(int arg) { /* This function will not be instrumented. */ ... } Races from non-instrumented functions will not be reported. CAMLno_tsan should only be used by experts. It can be used to reduce the performance overhead in certain corner cases, or to suppress some known alarms. For the latter, using a suppressions file with TSAN_OPTIONS should be preferred when possible, as it allows for finer-grained control, and qualifying a function f with CAMLno_tsan results in missing entries in TSan’s stack traces when a data race happens in a transitive callee of f. There is no way to disable instrumentation in OCaml code.
## 6 Changes in the delivery of signals TSan intercepts all signals and passes them down to the instrumented program. This overlay from TSan is not always transparent for the program. Synchronous signals such as SIGSEV, SIGILL, SIGBUS, etc. will be passed down immediately, whereas asynchronous signals such as SIGINT will be delayed until the next call to the TSan runtime (e.g. until the next access to mutable data). This limitation of TSan can have surprising effects: for instance, pure, recursive functions that do not allocate cannot be interrupted until they terminate. ------------------------------------------------------------------------ [« The “Tail Modulo Constructor” program transformation](tail_mod_cons.html)[The core library »](core.html) Copyright © 2024 Institut National de Recherche en Informatique et en Automatique ------------------------------------------------------------------------
# OCaml - The core library Source: https://ocaml.org/manual/5.2/core.html ☰ - [The core library](core.html) - [The standard library](stdlib.html) - [The compiler front-end](parsing.html) - [The unix library: Unix system calls](libunix.html) - [The str library: regular expressions and string processing](libstr.html) - [The runtime_events library](runtime_events.html) - [The threads library](libthreads.html) - [The dynlink library: dynamic loading and linking of object files](libdynlink.html) - [Recently removed or moved libraries (Graphics, Bigarray, Num, LablTk)](old.html)
# Chapter 28 The core library This chapter describes the OCaml core library, which is composed of declarations for built-in types and exceptions, plus the module Stdlib that provides basic operations on these built-in types. The Stdlib module is special in two ways: - It is automatically linked with the user’s object code files by the ocamlc command (chapter ‍[13](comp.html#c%3Acamlc)). - It is automatically “opened” when a compilation starts, or when the toplevel system is launched. Hence, it is possible to use unqualified identifiers to refer to the functions provided by the Stdlib module, without adding a open Stdlib directive.
## 1 Built-in types and predefined exceptions The following built-in types and predefined exceptions are always defined in the compilation environment, but are not part of any module. As a consequence, they can only be referred by their short names.
### Built-in types type int > The type of integer numbers. type char > The type of characters. type bytes > The type of (writable) byte sequences. type string > The type of (read-only) character strings. type float > The type of floating-point numbers. type bool = false | true > The type of booleans (truth values). type unit = () > The type of the unit value. type exn > The type of exception values. type 'a array > The type of arrays whose elements have type 'a. type 'a list = [] | :: of 'a * 'a list > The type of lists whose elements have type 'a. type 'a option = None | Some of 'a > The type of optional values of type 'a. type int32 > The type of signed 32-bit integers. Literals for 32-bit integers are suffixed by l. See the [Int32](../5.2/api/Int32.html) module. type int64 > The type of signed 64-bit integers. Literals for 64-bit integers are suffixed by L. See the [Int64](../5.2/api/Int64.html) module. type nativeint > The type of signed, platform-native integers (32 bits on 32-bit processors, 64 bits on 64-bit processors). Literals for native integers are suffixed by n. See the [Nativeint](../5.2/api/Nativeint.html) module. type ('a, 'b, 'c, 'd, 'e, 'f) format6
### Built-in types > The type of format strings. 'a is the type of the parameters of the format, 'f is the result type for the printf-style functions, 'b is the type of the first argument given to %a and %t printing functions (see module [Printf](../5.2/api/Printf.html)), 'c is the result type of these functions, and also the type of the argument transmitted to the first argument of kprintf-style functions, 'd is the result type for the scanf-style functions (see module [Scanf](../5.2/api/Scanf.html)), and 'e is the type of the receiver function for the scanf-style functions. type 'a lazy_t > This type is used to implement the [Lazy](../5.2/api/Lazy.html) module. It should not be used directly.
### Predefined exceptions exception Match_failure of (string * int * int) > Exception raised when none of the cases of a pattern-matching apply. The arguments are the location of the match keyword in the source code (file name, line number, column number). exception Assert_failure of (string * int * int) > Exception raised when an assertion fails. The arguments are the location of the assert keyword in the source code (file name, line number, column number). exception Invalid_argument of string > Exception raised by library functions to signal that the given arguments do not make sense. The string gives some information to the programmer. As a general rule, this exception should not be caught, it denotes a programming error and the code should be modified not to trigger it. exception Failure of string > Exception raised by library functions to signal that they are undefined on the given arguments. The string is meant to give some information to the programmer; you must *not* pattern match on the string literal because it may change in future versions (use `Failure _` instead). exception Not_found > Exception raised by search functions when the desired object could not be found. exception Out_of_memory > Exception raised by the garbage collector when there is insufficient memory to complete the computation. (Not reliable for allocations on the minor heap.) exception Stack_overflow
### Predefined exceptions > Exception raised by the bytecode interpreter when the evaluation stack reaches its maximal size. This often indicates infinite or excessively deep recursion in the user’s program. Before 4.10, it was not fully implemented by the native-code compiler. exception Sys_error of string > Exception raised by the input/output functions to report an operating system error. The string is meant to give some information to the programmer; you must *not* pattern match on the string literal because it may change in future versions (use `Sys_error _` instead). exception End_of_file > Exception raised by input functions to signal that the end of file has been reached. exception Division_by_zero > Exception raised by integer division and remainder operations when their second argument is zero. exception Sys_blocked_io > A special case of Sys_error raised when no I/O is possible on a non-blocking I/O channel. exception Undefined_recursive_module of (string * int * int) > Exception raised when an ill-founded recursive module definition is evaluated. (See section ‍[12.2](recursivemodules.html#s%3Arecursive-modules).) The arguments are the location of the definition in the source code (file name, line number, column number).
## 2 Module Stdlib: the initially opened module - [Module Stdlib](../5.2/api/Stdlib.html): the initially opened module ------------------------------------------------------------------------ [« Runtime detection of data races with ThreadSanitizer](tsan.html)[The standard library »](stdlib.html) Copyright © 2024 Institut National de Recherche en Informatique et en Automatique ------------------------------------------------------------------------
# OCaml - The standard library Source: https://ocaml.org/manual/5.2/stdlib.html ☰ - [The core library](core.html) - [The standard library](stdlib.html) - [The compiler front-end](parsing.html) - [The unix library: Unix system calls](libunix.html) - [The str library: regular expressions and string processing](libstr.html) - [The runtime_events library](runtime_events.html) - [The threads library](libthreads.html) - [The dynlink library: dynamic loading and linking of object files](libdynlink.html) - [Recently removed or moved libraries (Graphics, Bigarray, Num, LablTk)](old.html)
# Chapter 29 The standard library This chapter describes the functions provided by the OCaml standard library. The modules from the standard library are automatically linked with the user’s object code files by the ocamlc command. Hence, these modules can be used in standalone programs without having to add any .cmo file on the command line for the linking phase. Similarly, in interactive use, these globals can be used in toplevel phrases without having to load any .cmo file in memory. Unlike the core Stdlib module, submodules are not automatically “opened” when compilation starts, or when the toplevel system is launched. Hence it is necessary to use qualified identifiers to refer to the functions provided by these modules, or to add open directives. - [Module Arg](../5.2/api/Arg.html): parsing of command line arguments - [Module Array](../5.2/api/Array.html): array operations - [Module ArrayLabels](../5.2/api/ArrayLabels.html): array operations (with labels) - [Module Atomic](../5.2/api/Atomic.html): atomic references - [Module Bigarray](../5.2/api/Bigarray.html): large, multi-dimensional, numerical arrays - [Module Bool](../5.2/api/Bool.html): boolean values - [Module Buffer](../5.2/api/Buffer.html): extensible buffers - [Module Bytes](../5.2/api/Bytes.html): byte sequences - [Module BytesLabels](../5.2/api/BytesLabels.html): byte sequences (with labels) - [Module Callback](../5.2/api/Callback.html): registering OCaml values with the C runtime - [Module Char](../5.2/api/Char.html): character operations
# Chapter 29 The standard library - [Module Complex](../5.2/api/Complex.html): complex numbers - [Module Condition](../5.2/api/Condition.html): condition variables to synchronize between threads - [Module Domain](../5.2/api/Domain.html): Domain spawn/join and domain local variables - [Module Digest](../5.2/api/Digest.html): MD5 message digest - [Module Dynarray](../5.2/api/Dynarray.html): Dynamic arrays - [Module Effect](../5.2/api/Effect.html): deep and shallow effect handlers - [Module Either](../5.2/api/Either.html): either values - [Module Ephemeron](../5.2/api/Ephemeron.html): Ephemerons and weak hash table - [Module Filename](../5.2/api/Filename.html): operations on file names - [Module Float](../5.2/api/Float.html): floating-point numbers - [Module Format](../5.2/api/Format.html): pretty printing - [Module Fun](../5.2/api/Fun.html): function values - [Module Gc](../5.2/api/Gc.html): memory management control and statistics; finalized values - [Module Hashtbl](../5.2/api/Hashtbl.html): hash tables and hash functions - [Module In_channel](../5.2/api/In_channel.html): input channels - [Module Int](../5.2/api/Int.html): integers - [Module Int32](../5.2/api/Int32.html): 32-bit integers - [Module Int64](../5.2/api/Int64.html): 64-bit integers - [Module Lazy](../5.2/api/Lazy.html): deferred computations - [Module Lexing](../5.2/api/Lexing.html): the run-time library for lexers generated by ocamllex - [Module List](../5.2/api/List.html): list operations
# Chapter 29 The standard library - [Module ListLabels](../5.2/api/ListLabels.html): list operations (with labels) - [Module Map](../5.2/api/Map.html): association tables over ordered types - [Module Marshal](../5.2/api/Marshal.html): marshaling of data structures - [Module MoreLabels](../5.2/api/MoreLabels.html): include modules Hashtbl, Map and Set with labels - [Module Mutex](../5.2/api/Mutex.html): locks for mutual exclusion - [Module Nativeint](../5.2/api/Nativeint.html): processor-native integers - [Module Oo](../5.2/api/Oo.html): object-oriented extension - [Module Option](../5.2/api/Option.html): option values - [Module Out_channel](../5.2/api/Out_channel.html): output channels - [Module Parsing](../5.2/api/Parsing.html): the run-time library for parsers generated by ocamlyacc - [Module Printexc](../5.2/api/Printexc.html): facilities for printing exceptions - [Module Printf](../5.2/api/Printf.html): formatting printing functions - [Module Queue](../5.2/api/Queue.html): first-in first-out queues - [Module Random](../5.2/api/Random.html): pseudo-random number generator (PRNG) - [Module Result](../5.2/api/Result.html): result values - [Module Scanf](../5.2/api/Scanf.html): formatted input functions - [Module Seq](../5.2/api/Seq.html): functional iterators - [Module Set](../5.2/api/Set.html): sets over ordered types - [Module Semaphore](../5.2/api/Semaphore.html): semaphores, another thread synchronization mechanism - [Module Stack](../5.2/api/Stack.html): last-in first-out stacks
# Chapter 29 The standard library - [Module StdLabels](../5.2/api/StdLabels.html): include modules Array, List and String with labels - [Module String](../5.2/api/String.html): string operations - [Module StringLabels](../5.2/api/StringLabels.html): string operations (with labels) - [Module Sys](../5.2/api/Sys.html): system interface - [Module Type](../5.2/api/Type.html): type introspection - [Module Uchar](../5.2/api/Uchar.html): Unicode characters - [Module Unit](../5.2/api/Unit.html): unit values - [Module Weak](../5.2/api/Weak.html): arrays of weak pointers ------------------------------------------------------------------------ [« The core library](core.html)[The compiler front-end »](parsing.html) Copyright © 2024 Institut National de Recherche en Informatique et en Automatique ------------------------------------------------------------------------
# OCaml - The compiler front-end Source: https://ocaml.org/manual/5.2/parsing.html ☰ - [The core library](core.html) - [The standard library](stdlib.html) - [The compiler front-end](parsing.html) - [The unix library: Unix system calls](libunix.html) - [The str library: regular expressions and string processing](libstr.html) - [The runtime_events library](runtime_events.html) - [The threads library](libthreads.html) - [The dynlink library: dynamic loading and linking of object files](libdynlink.html) - [Recently removed or moved libraries (Graphics, Bigarray, Num, LablTk)](old.html)
# Chapter 30 The compiler front-end This chapter describes the OCaml front-end, which declares the abstract syntax tree used by the compiler, provides a way to parse, print and pretty-print OCaml code, and ultimately allows one to write abstract syntax tree preprocessors invoked via the -ppx flag (see chapters ‍[13](comp.html#c%3Acamlc) and ‍[16](native.html#c%3Anativecomp)). It is important to note that the exported front-end interface follows the evolution of the OCaml language and implementation, and thus does not provide any backwards compatibility guarantees. The front-end is a part of compiler-libs library. Programs that use the compiler-libs library should be built as follows: ocamlfind ocamlc other options -package compiler-libs.common other files ocamlfind ocamlopt other options -package compiler-libs.common other files Use of the ocamlfind utility is recommended. However, if this is not possible, an alternative method may be used: ocamlc other options -I +compiler-libs ocamlcommon.cma other files ocamlopt other options -I +compiler-libs ocamlcommon.cmxa other files For interactive use of the compiler-libs library, start ocaml and type #load "compiler-libs/ocamlcommon.cma";;. - [Module Ast_helper](../5.2/api/compilerlibref/Ast_helper.html): helper functions for AST construction - [Module Ast_mapper](../5.2/api/compilerlibref/Ast_mapper.html): -ppx rewriter interface - [Module Asttypes](../5.2/api/compilerlibref/Asttypes.html): auxiliary types used by Parsetree
# Chapter 30 The compiler front-end - [Module Location](../5.2/api/compilerlibref/Location.html): source code locations - [Module Longident](../5.2/api/compilerlibref/Longident.html): long identifiers - [Module Parse](../5.2/api/compilerlibref/Parse.html): OCaml syntax parsing - [Module Parsetree](../5.2/api/compilerlibref/Parsetree.html): OCaml syntax tree - [Module Pprintast](../5.2/api/compilerlibref/Pprintast.html): OCaml syntax printing ------------------------------------------------------------------------ [« The standard library](stdlib.html)[The unix library: Unix system calls »](libunix.html) Copyright © 2024 Institut National de Recherche en Informatique et en Automatique ------------------------------------------------------------------------
# OCaml - The unix library: Unix system calls Source: https://ocaml.org/manual/5.2/libunix.html ☰ - [The core library](core.html) - [The standard library](stdlib.html) - [The compiler front-end](parsing.html) - [The unix library: Unix system calls](libunix.html) - [The str library: regular expressions and string processing](libstr.html) - [The runtime_events library](runtime_events.html) - [The threads library](libthreads.html) - [The dynlink library: dynamic loading and linking of object files](libdynlink.html) - [Recently removed or moved libraries (Graphics, Bigarray, Num, LablTk)](old.html)
# Chapter 31 The unix library: Unix system calls The unix library makes many Unix system calls and system-related library functions available to OCaml programs. This chapter describes briefly the functions provided. Refer to sections 2 ‍and ‍3 of the Unix manual for more details on the behavior of these functions. - [Module Unix](../5.2/api/Unix.html): Unix system calls - [Module UnixLabels](../5.2/api/UnixLabels.html): Labeled Unix system calls Not all functions are provided by all Unix variants. If some functions are not available, they will raise Invalid_arg when called. Programs that use the unix library must be linked as follows: ocamlc other options -I +unix unix.cma other files ocamlopt other options -I +unix unix.cmxa other files For interactive use of the unix library, do: ocamlmktop -o mytop -I +unix unix.cma ./mytop or (if dynamic linking of C libraries is supported on your platform), start ocaml and type ```ocaml # #directory "+unix";; # #load "unix.cma";; ``` > Windows:  The Cygwin port of OCaml fully implements all functions from the Unix module. The native Win32 ports implement a subset of them. Below is a list of the functions that are not implemented, or only partially implemented, by the Win32 ports. Functions not mentioned are fully implemented and behave as described previously in this chapter.
# Chapter 31 The unix library: Unix system calls | | | |-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | Functions | Comment | | fork | not implemented, use create_process or threads | | wait | not implemented, use waitpid | | waitpid | can only wait for a given PID, not any child process | | getppid | not implemented (meaningless under Windows) | | nice | not implemented | | truncate, ftruncate | implemented (since 4.10.0) | | link | implemented (since 3.02) | | fchmod | not implemented | | chown, fchown | not implemented (make no sense on a DOS file system) | | umask | not implemented | | access | execute permission X_OK cannot be tested, it just tests for read permission instead | | chroot | not implemented | | mkfifo | not implemented | | symlink, readlink | implemented (since 4.03.0) | | kill | partially implemented (since 4.00.0): only the sigkill signal is implemented | | sigprocmask, sigpending, sigsuspend | not implemented (no inter-process signals on Windows | | pause | not implemented (no inter-process signals in Windows) | | alarm | not implemented | | times | partially implemented, will not report timings for child processes | | getitimer, setitimer | not implemented | | getuid, geteuid, getgid, getegid | always return 1 | | setuid, setgid, setgroups, initgroups | not implemented | | getgroups | always returns \[\|1\|\] (since 2.00) | | getpwnam, getpwuid | always raise Not_found | | getgrnam, getgrgid | always raise Not_found | | type socket_domain | PF_INET is fully supported; PF_INET6 is fully supported (since 4.01.0); PF_UNIX is supported since 4.14.0, but only works on Windows 10 1803 and later. | | establish_server | not implemented; use threads | | terminal functions (tc\*) | not implemented | | setsid | not implemented |
# Chapter 31 The unix library: Unix system calls ------------------------------------------------------------------------ [« The compiler front-end](parsing.html)[The str library: regular expressions and string processing »](libstr.html) Copyright © 2024 Institut National de Recherche en Informatique et en Automatique ------------------------------------------------------------------------
# OCaml - The str library: regular expressions and string processing Source: https://ocaml.org/manual/5.2/libstr.html ☰ - [The core library](core.html) - [The standard library](stdlib.html) - [The compiler front-end](parsing.html) - [The unix library: Unix system calls](libunix.html) - [The str library: regular expressions and string processing](libstr.html) - [The runtime_events library](runtime_events.html) - [The threads library](libthreads.html) - [The dynlink library: dynamic loading and linking of object files](libdynlink.html) - [Recently removed or moved libraries (Graphics, Bigarray, Num, LablTk)](old.html)
# Chapter 32 The str library: regular expressions and string processing The str library provides high-level string processing functions, some based on regular expressions. It is intended to support the kind of file processing that is usually performed with scripting languages such as awk, perl or sed. Programs that use the str library must be linked as follows: ocamlc other options -I +str str.cma other files ocamlopt other options -I +str str.cmxa other files For interactive use of the str library, do: ocamlmktop -o mytop str.cma ./mytop or (if dynamic linking of C libraries is supported on your platform), start ocaml and type ```ocaml # #directory "+str";; # #load "str.cma";; ``` - [Module Str](../5.2/api/Str.html): regular expressions and string processing ------------------------------------------------------------------------ [« The unix library: Unix system calls](libunix.html)[The runtime_events library »](runtime_events.html) Copyright © 2024 Institut National de Recherche en Informatique et en Automatique ------------------------------------------------------------------------
# OCaml - The runtime_events library Source: https://ocaml.org/manual/5.2/runtime_events.html ☰ - [The core library](core.html) - [The standard library](stdlib.html) - [The compiler front-end](parsing.html) - [The unix library: Unix system calls](libunix.html) - [The str library: regular expressions and string processing](libstr.html) - [The runtime_events library](runtime_events.html) - [The threads library](libthreads.html) - [The dynlink library: dynamic loading and linking of object files](libdynlink.html) - [Recently removed or moved libraries (Graphics, Bigarray, Num, LablTk)](old.html)
# Chapter 33 The runtime_events library The runtime_events library provides an API for consuming runtime tracing and metrics information from the runtime. See chapter ‍[25](runtime-tracing.html#c%3Aruntime-tracing) for more information. Programs that use runtime_events must be linked as follows: ocamlc -I +runtime_events other options unix.cma runtime_events.cma other files ocamlopt -I +runtime_events other options unix.cmxa runtime_events.cmxa other files Compilation units that use the runtime_events library must also be compiled with the -I +runtime_events option (see chapter ‍[13](comp.html#c%3Acamlc)). - [Module Runtime_events](../5.2/api/Runtime_events.html): tracing system ------------------------------------------------------------------------ [« The str library: regular expressions and string processing](libstr.html)[The threads library »](libthreads.html) Copyright © 2024 Institut National de Recherche en Informatique et en Automatique ------------------------------------------------------------------------
# OCaml - The threads library Source: https://ocaml.org/manual/5.2/libthreads.html ☰ - [The core library](core.html) - [The standard library](stdlib.html) - [The compiler front-end](parsing.html) - [The unix library: Unix system calls](libunix.html) - [The str library: regular expressions and string processing](libstr.html) - [The runtime_events library](runtime_events.html) - [The threads library](libthreads.html) - [The dynlink library: dynamic loading and linking of object files](libdynlink.html) - [Recently removed or moved libraries (Graphics, Bigarray, Num, LablTk)](old.html)
# Chapter 34 The threads library The threads library allows concurrent programming in OCaml. It provides multiple threads of control (also called lightweight processes) that execute concurrently in the same memory space. Threads communicate by in-place modification of shared data structures, or by sending and receiving data on communication channels. The threads library is implemented on top of the threading facilities provided by the operating system: POSIX 1003.1c threads for Linux, MacOS, and other Unix-like systems; Win32 threads for Windows. Only one thread at a time is allowed to run OCaml code on a particular domain ‍[9.5.1](parallelism.html#s%3Apar_systhread_interaction). Hence, opportunities for parallelism are limited to the parts of the program that run system or C library code. However, threads provide concurrency and can be used to structure programs as several communicating processes. Threads also efficiently support concurrent, overlapping I/O operations. Programs that use threads must be linked as follows: ocamlc -I +unix -I +threads other options unix.cma threads.cma other files ocamlopt -I +unix -I +threads other options unix.cmxa threads.cmxa other files Compilation units that use the threads library must also be compiled with the -I +threads option (see chapter ‍[13](comp.html#c%3Acamlc)). - [Module Thread](../5.2/api/Thread.html): lightweight threads - [Module Event](../5.2/api/Event.html): first-class synchronous communication ------------------------------------------------------------------------
# Chapter 34 The threads library [« The runtime_events library](runtime_events.html)[The dynlink library: dynamic loading and linking of object files »](libdynlink.html) Copyright © 2024 Institut National de Recherche en Informatique et en Automatique ------------------------------------------------------------------------
# OCaml - The dynlink library: dynamic loading and linking of object files Source: https://ocaml.org/manual/5.2/libdynlink.html ☰ - [The core library](core.html) - [The standard library](stdlib.html) - [The compiler front-end](parsing.html) - [The unix library: Unix system calls](libunix.html) - [The str library: regular expressions and string processing](libstr.html) - [The runtime_events library](runtime_events.html) - [The threads library](libthreads.html) - [The dynlink library: dynamic loading and linking of object files](libdynlink.html) - [Recently removed or moved libraries (Graphics, Bigarray, Num, LablTk)](old.html)
# Chapter 35 The dynlink library: dynamic loading and linking of object files The dynlink library supports type-safe dynamic loading and linking of bytecode object files (.cmo and .cma files) in a running bytecode program, or of native plugins (usually .cmxs files) in a running native program. Type safety is ensured by limiting the set of modules from the running program that the loaded object file can access, and checking that the running program and the loaded object file have been compiled against the same interfaces for these modules. In native code, there are also some compatibility checks on the implementations (to avoid errors with cross-module optimizations); it might be useful to hide .cmx files when building native plugins so that they remain independent of the implementation of modules in the main program. Programs that use the dynlink library simply need to include the dynlink library directory with -I +dynlink and link dynlink.cma or dynlink.cmxa with their object files and other libraries. Note: in order to insure that the dynamically-loaded modules have access to all the libraries that are visible to the main program (and not just to the parts of those libraries that are actually used in the main program), programs using the dynlink library should be linked with -linkall. - [Module Dynlink](../5.2/api/Dynlink.html): dynamic loading of bytecode object files ------------------------------------------------------------------------ [« The threads library](libthreads.html)[Recently removed or moved libraries (Graphics, Bigarray, Num, LablTk) »](old.html)
# Chapter 35 The dynlink library: dynamic loading and linking of object files Copyright © 2024 Institut National de Recherche en Informatique et en Automatique ------------------------------------------------------------------------
# OCaml - Recently removed or moved libraries (Graphics, Bigarray, Num, LablTk) Source: https://ocaml.org/manual/5.2/old.html ☰ - [The core library](core.html) - [The standard library](stdlib.html) - [The compiler front-end](parsing.html) - [The unix library: Unix system calls](libunix.html) - [The str library: regular expressions and string processing](libstr.html) - [The runtime_events library](runtime_events.html) - [The threads library](libthreads.html) - [The dynlink library: dynamic loading and linking of object files](libdynlink.html) - [Recently removed or moved libraries (Graphics, Bigarray, Num, LablTk)](old.html)
# Chapter 36 Recently removed or moved libraries (Graphics, Bigarray, Num, LablTk) This chapter describes three libraries which were formerly part of the OCaml distribution (Graphics, Num, and LablTk), and a library which has now become part of OCaml’s standard library, and is documented there (Bigarray).
## 1 The Graphics Library Since OCaml 4.09, the graphics library is distributed as an external package. Its new home is: [https://github.com/ocaml/graphics](https://github.com/ocaml/graphics) If you are using the opam package manager, you should install the corresponding graphics package: opam install graphics Before OCaml 4.09, this package simply ensures that the graphics library was installed by the compiler, and starting from OCaml 4.09 this package effectively provides the graphics library.
## 2 The Bigarray Library As of OCaml 4.07, the bigarray library has been integrated into OCaml’s standard library. The bigarray functionality may now be found in the standard library [Bigarray module](../5.2/api/Bigarray.html), except for the map_file function which is now part of the [Unix library](libunix.html#c%3Aunix). The documentation has been integrated into the documentation for the standard library. The legacy bigarray library bundled with the compiler is a compatibility library with exactly the same interface as before, i.e. with map_file included. We strongly recommend that you port your code to use the standard library version instead, as the changes required are minimal. If you choose to use the compatibility library, you must link your programs as follows: ocamlc other options bigarray.cma other files ocamlopt other options bigarray.cmxa other files For interactive use of the bigarray compatibility library, do: ocamlmktop -o mytop bigarray.cma ./mytop or (if dynamic linking of C libraries is supported on your platform), start ocaml and type #load "bigarray.cma";;.
## 3 The Num Library The num library implements integer arithmetic and rational arithmetic in arbitrary precision. It was split off the core OCaml distribution starting with the 4.06.0 release, and can now be found at [https://github.com/ocaml/num](https://github.com/ocaml/num). New applications that need arbitrary-precision arithmetic should use the Zarith library ([https://github.com/ocaml/Zarith](https://github.com/ocaml/Zarith)) instead of the Num library, and older applications that already use Num are encouraged to switch to Zarith. Zarith delivers much better performance than Num and has a nicer API.
## 4 The Labltk Library and OCamlBrowser Since OCaml version 4.02, the OCamlBrowser tool and the Labltk library are distributed separately from the OCaml compiler. The project is now hosted at [https://github.com/garrigue/labltk](https://github.com/garrigue/labltk). ------------------------------------------------------------------------ [« The dynlink library: dynamic loading and linking of object files](libdynlink.html)[manual075.html](manual075.html) Copyright © 2024 Institut National de Recherche en Informatique et en Automatique ------------------------------------------------------------------------