text
stringlengths
10
16.2k
#### Comments in .mli files A special comment is associated to an element if it is placed before or after the element. A special comment before an element is associated to this element if ‍: - There is no blank line or another special comment between the special comment and the element. However, a regular comment can occur between the special comment and the element. - The special comment is not already associated to the previous element. - The special comment is not the first one of a toplevel module. A special comment after an element is associated to this element if there is no blank line or comment between the special comment and the element. There are two exceptions: for constructors and record fields in type definitions, the associated comment can only be placed after the constructor or field definition, without blank lines or other comments between them. The special comment for a constructor with another constructor following must be placed before the ’\|’ character separating the two constructors. The following sample interface file foo.mli illustrates the placement rules for comments in .mli files.
### 2.1 Placement of documentation comments (\*\* The first special comment of the file is the comment associated with the whole module.\*) (\*\* Special comments can be placed between elements and are kept by the OCamldoc tool, but are not associated to any element. @-tags in these comments are ignored.\*) (\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*) (\*\* Comments like the one above, with more than two asterisks, are ignored. \*) (\*\* The comment for function f. \*) val f : int -> int -> int (\*\* The continuation of the comment for function f. \*) (\*\* Comment for exception My_exception, even with a simple comment between the special comment and the exception.\*) (\* Hello, I'm a simple comment :-) \*) exception My_exception of (int -> int) \* int (\*\* Comment for type weather \*) type weather = \| Rain of int (\*\* The comment for constructor Rain \*) \| Sun (\*\* The comment for constructor Sun \*) (\*\* Comment for type weather2 \*) type weather2 = \| Rain of int (\*\* The comment for constructor Rain \*) \| Sun (\*\* The comment for constructor Sun \*) (\*\* I can continue the comment for type weather2 here because there is already a comment associated to the last constructor.\*) (\*\* The comment for type my_record \*) type my_record = { foo : int ; (\*\* Comment for field foo \*) bar : string ; (\*\* Comment for field bar \*) } (\*\* Continuation of comment for type my_record \*) (\*\* Comment for foo \*) val foo : string (\*\* This comment is associated to foo and not to bar. \*) val bar : string (\*\* This comment is associated to bar. \*) (\*\* The comment for class my_class \*) class my_class : object (\*\* A comment to describe inheritance from cl \*) inherit cl (\*\* The comment for attribute tutu \*) val mutable tutu : string (\*\* The comment for attribute toto. \*) val toto : int (\*\* This comment is not attached to titi since there is a blank line before titi, but is kept as a comment in the class. \*) val titi : string (\*\* Comment for method toto \*) method toto : string (\*\* Comment for method m \*) method m : float -> int end (\*\* The comment for the class type my_class_type \*) class type my_class_type = object (\*\* The comment for variable x. \*) val mutable x : int (\*\* The comment for method m. \*) method m : int -> int end (\*\* The comment for module Foo \*) module Foo : sig (\*\* The comment for x \*) val x : int (\*\* A special comment that is kept but not associated to any element \*) end (\*\* The comment for module type my_module_type. \*) module type my_module_type = sig (\*\* The comment for value x. \*) val x : int (\*\* The comment for module M. \*) module M : sig (\*\* The comment for value y. \*) val y : int (\* ... \*) end end
#### Comments in .ml files A special comment is associated to an element if it is placed before the element and there is no blank line between the comment and the element. Meanwhile, there can be a simple comment between the special comment and the element. There are two exceptions, for constructors and record fields in type definitions, whose associated comment must be placed after the constructor or field definition, without blank line between them. The special comment for a constructor with another constructor following must be placed before the ’\|’ character separating the two constructors. The following example of file toto.ml shows where to place comments in a .ml file.
### 2.1 Placement of documentation comments (\*\* The first special comment of the file is the comment associated to the whole module. \*) (\*\* The comment for function f \*) let f x y = x + y (\*\* This comment is not attached to any element since there is another special comment just before the next element. \*) (\*\* Comment for exception My_exception, even with a simple comment between the special comment and the exception.\*) (\* A simple comment. \*) exception My_exception of (int -> int) \* int (\*\* Comment for type weather \*) type weather = \| Rain of int (\*\* The comment for constructor Rain \*) \| Sun (\*\* The comment for constructor Sun \*) (\*\* The comment for type my_record \*) type my_record = { foo : int ; (\*\* Comment for field foo \*) bar : string ; (\*\* Comment for field bar \*) } (\*\* The comment for class my_class \*) class my_class = object (\*\* A comment to describe inheritance from cl \*) inherit cl (\*\* The comment for the instance variable tutu \*) val mutable tutu = "tutu" (\*\* The comment for toto \*) val toto = 1 val titi = "titi" (\*\* Comment for method toto \*) method toto = tutu ^ "!" (\*\* Comment for method m \*) method m (f : float) = 1 end (\*\* The comment for class type my_class_type \*) class type my_class_type = object (\*\* The comment for the instance variable x. \*) val mutable x : int (\*\* The comment for method m. \*) method m : int -> int end (\*\* The comment for module Foo \*) module Foo = struct (\*\* The comment for x \*) let x = 0 (\*\* A special comment in the class, but not associated to any element. \*) end (\*\* The comment for module type my_module_type. \*) module type my_module_type = sig (\* Comment for value x. \*) val x : int (\* ... \*) end
### 2.2 The Stop special comment The special comment (\*\*/\*\*) tells OCamldoc to discard elements placed after this comment, up to the end of the current class, class type, module or module type, or up to the next stop comment. For instance: class type foo = object (\*\* comment for method m \*) method m : string (\*\*/\*\*) (\*\* This method won't appear in the documentation \*) method bar : int end (\*\* This value appears in the documentation, since the Stop special comment in the class does not affect the parent module of the class.\*) val foo : string (\*\*/\*\*) (\*\* The value bar does not appear in the documentation.\*) val bar : string (\*\*/\*\*) (\*\* The type t appears since in the documentation since the previous stop comment toggled off the "no documentation mode". \*) type t = string The -no-stop option to ocamldoc causes the Stop special comments to be ignored.
### 2.3 Syntax of documentation comments The inside of documentation comments (\*\*…\*) consists of free-form text with optional formatting annotations, followed by optional *tags* giving more specific information about parameters, version, authors, … The tags are distinguished by a leading @ character. Thus, a documentation comment has the following shape: (** The comment begins with a description, which is text formatted according to the rules described in the next section. The description continues until the first non-escaped '@' character. @author Mr Smith @param x description for parameter x *) Some elements support only a subset of all @-tags. Tags that are not relevant to the documented element are simply ignored. For instance, all tags are ignored when documenting type constructors, record fields, and class inheritance clauses. Similarly, a @param tag on a class instance variable is ignored. At last, (\*\*) is the empty documentation comment.
### 2.4 Text formatting Here is the BNF grammar for the simple markup language used to format text descriptions. <table class="display dcenter"><colgroup><col style="width: 100%" /></colgroup><tbody><tr class="odd c009"><td class="dcell"><table class="c001 cellpading0"><tbody><tr class="odd"><td class="c008">text</td><td class="c005">::=</td><td class="c007"> {[text-element](#text-element)}<sup>+</sup></td></tr><tr class="even"><td class="c008"> </td><td></td><td></td></tr></tbody></table></td></tr></tbody></table> <table class="display dcenter"><colgroup><col style="width: 100%" /></colgroup><tbody><tr class="odd c009"><td class="dcell"><table class="c001 cellpading0"><tbody><tr class="odd"><td class="c008">inline-text</td><td class="c005">::=</td><td class="c007"> {[inline-text-element](#inline-text-element)}<sup>+</sup></td></tr><tr class="even"><td class="c008"> </td><td></td><td></td></tr></tbody></table></td></tr></tbody></table> | | | |---------------------------------------------------------------------------------------------|-----| | text-element | ::= |
### 2.4 Text formatting | | | | |-----|--------------------------------------------------------------------------------------------------------|-------------------| | ∣ | [inline-text-element](#inline-text-element) |   | | ∣ | blank-line | force a new line. | | | | |-----------------------------------------------------------------------------------------------------------|-----| | inline-text-element | ::= |
### 2.4 Text formatting | | | | |-----|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | ∣ | { { 0 … 9 }<sup>+</sup> [inline-text](#inline-text) } | format [text](#text) as a section header; the integer following { indicates the sectioning level. | | ∣ | { { 0 … 9 }<sup>+</sup> : label [inline-text](#inline-text) } | same, but also associate the name label to the current point. This point can be referenced by its fully-qualified label in a {! command, just like any other element. | | ∣ | {b [inline-text](#inline-text) } | set [text](#text) in bold. | | ∣ | {i [inline-text](#inline-text) } | set [text](#text) in italic. | | ∣ | {e [inline-text](#inline-text) } | emphasize [text](#text). | | ∣ | {C [inline-text](#inline-text) } | center [text](#text). | | ∣ | {L [inline-text](#inline-text) } | left align [text](#text). | | ∣ | {R [inline-text](#inline-text) } | right align [text](#text). | | ∣ | {ul [list](#list) } | build a list. | | ∣ | {ol [list](#list) } | build an enumerated list. | | ∣ | {{: string } [inline-text](#inline-text) } | put a link to the given address (given as string) on the given [text](#text). | | ∣ | \[ string \] | set the given string in source code style. | | ∣ | {\[ string \]} | set the given string in preformatted source code style. | | ∣ | {v string v} | set the given string in verbatim style. | | ∣ | {% string %} | target-specific content (L<sup>A</sup>T<sub>E</sub>X code by default, see details in [19.2.4.4](#sss%3Aocamldoc-target-specific-syntax)) | | ∣ | {! string } | insert a cross-reference to an element (see section [19.2.4.2](#sss%3Aocamldoc-crossref) for the syntax of cross-references). | | ∣ | {{! string } [inline-text](#inline-text) } | insert a cross-reference with the given text. | | ∣ | {!modules: string string ... } | insert an index table for the given module names. Used in HTML only. | | ∣ | {!indexlist} | insert a table of links to the various indexes (types, values, modules, ...). Used in HTML only. | | ∣ | {^ [inline-text](#inline-text) } | set text in superscript. | | ∣ | {\_ [inline-text](#inline-text) } | set text in subscript. | | ∣ | escaped-string | typeset the given string as is; special characters (’{’, ’}’, ’\[’, ’\]’ and ’@’) must be escaped by a ’\\’ |
#### 2.4.1 List formatting <table class="display dcenter"><colgroup><col style="width: 100%" /></colgroup><tbody><tr class="odd c009"><td class="dcell"><table class="c001 cellpading0"><tbody><tr class="odd"><td class="c008">list</td><td class="c005">::=</td><td class="c007"> </td></tr><tr class="even"><td class="c008"> </td><td class="c005">∣</td><td class="c007"> { {- [inline-text](#inline-text) } }<sup>+</sup></td></tr><tr class="odd"><td class="c008"> </td><td class="c005">∣</td><td class="c007"> { {li [inline-text](#inline-text) } }<sup>+</sup></td></tr></tbody></table></td></tr></tbody></table> A shortcut syntax exists for lists and enumerated lists: (** Here is a {b list} - item 1 - item 2 - item 3 The list is ended by the blank line.*) is equivalent to: (** Here is a {b list} {ul {- item 1} {- item 2} {- item 3}} The list is ended by the blank line.*) The same shortcut is available for enumerated lists, using ’+’ instead of ’-’. Note that only one list can be defined by this shortcut in nested lists.
#### 2.4.2 Cross-reference formatting Cross-references are fully qualified element names, as in the example {!Foo.Bar.t}. This is an ambiguous reference as it may designate a type name, a value name, a class name, etc. It is possible to make explicit the intended syntactic class, using {!type:Foo.Bar.t} to designate a type, and {!val:Foo.Bar.t} a value of the same name. The list of possible syntactic class is as follows: | | | |----------------------------------------------------------------------|---------------------| | tag | syntactic class | | | | | module: | module | | modtype: | module type | | class: | class | | classtype: | class type | | val: | value | | type: | type | | exception: | exception | | attribute: | attribute | | method: | class method | | section: | ocamldoc section | | const: | variant constructor | | recfield: | record field | In the case of variant constructors or record fields, the constructor or field name should be preceded by the name of the corresponding type to avoid the ambiguity of several types having the same constructor names. For example, the constructor Node of the type tree will be referenced as {!tree.Node} or {!const:tree.Node}, or possibly {!Mod1.Mod2.tree.Node} from outside the module.
#### 2.4.3 First sentence In the description of a value, type, exception, module, module type, class or class type, the *first sentence* is sometimes used in indexes, or when just a part of the description is needed. The first sentence is composed of the first characters of the description, until - the first dot followed by a blank, or - the first blank line outside of the following text formatting : {ul [list](#list) } , {ol [list](#list) } , \[ string \] , {\[ string \]} , {v string v} , {% string %} , {! string } , {^ [text](#text) } , {\_ [text](#text) } .
#### 2.4.4 Target-specific formatting The content inside {%foo: ... %} is target-specific and will be interpreted only by the backend foo, and ignored by other backends. The backends of the distribution are latex, html, texi and man. If no target is specified (syntax {% ... %}), latex is chosen by default. Custom generators may support their own target prefix.
#### 2.4.5 Recognized HTML tags The HTML tags \<b>..\</b>, \<code>..\</code>, \<i>..\</i>, \<ul>..\</ul>, \<ol>..\</ol>, \<li>..\</li>, \<center>..\</center> and \<h\[0-9\]\>..\</h\[0-9\]\> can be used instead of, respectively, {b ..} , \[..\] , {i ..} , {ul ..} , {ol ..} , {li ..} , {C ..} and {\[0-9\] ..}.
### 2.5 Documentation tags (@-tags)
#### Predefined tags The following table gives the list of predefined @-tags, with their syntax and meaning. | | | |--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | @author string | The author of the element. One author per @author tag. There may be several @author tags for the same element. | | @deprecated [text](#text) | The [text](#text) should describe when the element was deprecated, what to use as a replacement, and possibly the reason for deprecation. | | @param id [text](#text) | Associate the given description ([text](#text)) to the given parameter name id. This tag is used for functions, methods, classes and functors. | | @raise Exc [text](#text) | Explain that the element may raise the exception Exc. | | @return [text](#text) | Describe the return value and its possible values. This tag is used for functions and methods. | | @see \< URL \> [text](#text) | Add a reference to the URL with the given [text](#text) as comment. | | @see 'filename' [text](#text) | Add a reference to the given file name (written between single quotes), with the given [text](#text) as comment. | | @see "document-name" [text](#text) | Add a reference to the given document name (written between double quotes), with the given [text](#text) as comment. | | @since string | Indicate when the element was introduced. | | @before version [text](#text) | Associate the given description ([text](#text)) to the given version in order to document compatibility issues. | | @version string | The version number for the element. |
#### Custom tags You can use custom tags in the documentation comments, but they will have no effect if the generator used does not handle them. To use a custom tag, for example foo, just put @foo with some text in your comment, as in: (** My comment to show you a custom tag. @foo this is the text argument to the [foo] custom tag. *) To handle custom tags, you need to define a custom generator, as explained in section [19.3.2](#ss%3Aocamldoc-handling-custom-tags).
## 3 Custom generators OCamldoc operates in two steps: 1. analysis of the source files; 2. generation of documentation, through a documentation generator, which is an object of class Odoc_args.class_generator. Users can provide their own documentation generator to be used during step 2 instead of the default generators. All the information retrieved during the analysis step is available through the Odoc_info module, which gives access to all the types and functions representing the elements found in the given modules, with their associated description. The files you can use to define custom generators are installed in the ocamldoc sub-directory of the OCaml standard library.
### 3.1 The generator modules The type of a generator module depends on the kind of generated documentation. Here is the list of generator module types, with the name of the generator class in the module ‍: - for HTML ‍: Odoc_html.Html_generator (class html), - for L<sup>A</sup>T<sub>E</sub>X ‍: Odoc_latex.Latex_generator (class latex), - for TeXinfo ‍: Odoc_texi.Texi_generator (class texi), - for man pages ‍: Odoc_man.Man_generator (class man), - for graphviz (dot) ‍: Odoc_dot.Dot_generator (class dot), - for other kinds ‍: Odoc_gen.Base (class generator). That is, to define a new generator, one must implement a module with the expected signature, and with the given generator class, providing the generate method as entry point to make the generator generates documentation for a given list of modules ‍: method generate : Odoc_info.Module.t_module list -> unit This method will be called with the list of analysed and possibly merged Odoc_info.t_module structures. It is recommended to inherit from the current generator of the same kind as the one you want to define. Doing so, it is possible to load various custom generators to combine improvements brought by each one. This is done using first class modules (see chapter [12.5](firstclassmodules.html#s%3Afirst-class-modules)). The easiest way to define a custom generator is the following this example, here extending the current HTML generator. We don’t have to know if this is the original HTML generator defined in ocamldoc or if it has been extended already by a previously loaded custom generator ‍:
### 3.1 The generator modules module Generator (G : Odoc_html.Html_generator) = struct class html = object(self) inherit G.html as html (* ... *) method generate module_list = (* ... *) () (* ... *) end end;; let _ = Odoc_args.extend_html_generator (module Generator : Odoc_gen.Html_functor);; To know which methods to override and/or which methods are available, have a look at the different base implementations, depending on the kind of generator you are extending ‍: - for HTML ‍: [odoc_html.ml](https://github.com/ocaml/ocaml/blob/5.2/ocamldoc/odoc_html.ml), - for L<sup>A</sup>T<sub>E</sub>X ‍: [odoc_latex.ml](https://github.com/ocaml/ocaml/blob/5.2/ocamldoc/odoc_latex.ml), - for TeXinfo ‍: [odoc_texi.ml](https://github.com/ocaml/ocaml/blob/5.2/ocamldoc/odoc_texi.ml), - for man pages ‍: [odoc_man.ml](https://github.com/ocaml/ocaml/blob/5.2/ocamldoc/odoc_man.ml), - for graphviz (dot) ‍: [odoc_dot.ml](https://github.com/ocaml/ocaml/blob/5.2/ocamldoc/odoc_dot.ml).
### 3.2 Handling custom tags Making a custom generator handle custom tags (see [19.2.5](#sss%3Aocamldoc-custom-tags)) is very simple.
#### For HTML Here is how to develop a HTML generator handling your custom tags. The class Odoc_html.Generator.html inherits from the class Odoc_html.info, containing a field tag_functions which is a list pairs composed of a custom tag (e.g. "foo") and a function taking a text and returning HTML code (of type string). To handle a new tag bar, extend the current HTML generator and complete the tag_functions field: module Generator (G : Odoc_html.Html_generator) = struct class html = object(self) inherit G.html (** Return HTML code for the given text of a bar tag. *) method html_of_bar t = (* your code here *) initializer tag_functions <- ("bar", self#html_of_bar) :: tag_functions end end let _ = Odoc_args.extend_html_generator (module Generator : Odoc_gen.Html_functor);; Another method of the class Odoc_html.info will look for the function associated to a custom tag and apply it to the text given to the tag. If no function is associated to a custom tag, then the method prints a warning message on stderr.
#### For other generators You can act the same way for other kinds of generators.
## 4 Adding command line options The command line analysis is performed after loading the module containing the documentation generator, thus allowing command line options to be added to the list of existing ones. Adding an option can be done with the function Odoc_args.add_option : string * Arg.spec * string -> unit Note: Existing command line options can be redefined using this function.
### 4.1 Compilation and usage
#### Defining a custom generator class in one file Let custom.ml be the file defining a new generator class. Compilation of custom.ml can be performed by the following command ‍: ocamlc -I +ocamldoc -c custom.ml The file custom.cmo is created and can be used this way ‍: ocamldoc -g custom.cmo other-options source-files Options selecting a built-in generator to ocamldoc, such as -html, have no effect if a custom generator of the same kind is provided using -g. If the kinds do not match, the selected built-in generator is used and the custom one is ignored.
#### Defining a custom generator class in several files It is possible to define a generator class in several modules, which are defined in several files file<sub>1</sub>.ml\[i\], file<sub>2</sub>.ml\[i\], ..., file<sub>n</sub>.ml\[i\]. A .cma library file must be created, including all these files. The following commands create the custom.cma file from files file<sub>1</sub>.ml\[i\], ..., file<sub>n</sub>.ml\[i\] ‍: ocamlc -I +ocamldoc -c file1.ml[i] ocamlc -I +ocamldoc -c file2.ml[i] ... ocamlc -I +ocamldoc -c filen.ml[i] ocamlc -o custom.cma -a file1.cmo file2.cmo ... filen.cmo Then, the following command uses custom.cma as custom generator: ocamldoc -g custom.cma other-options source-files ------------------------------------------------------------------------ [« Dependency generator (ocamldep)](depend.html)[The debugger (ocamldebug) »](debugger.html) Copyright © 2024 Institut National de Recherche en Informatique et en Automatique ------------------------------------------------------------------------
# OCaml - The debugger (ocamldebug) Source: https://ocaml.org/manual/5.2/debugger.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 20 The debugger (ocamldebug) This chapter describes the OCaml source-level replay debugger ocamldebug. > Unix:  The debugger is available on Unix systems that provide BSD sockets. > Windows:  The debugger is available under the Cygwin port of OCaml, but not under the native Win32 ports.
## 1 Compiling for debugging Before the debugger can be used, the program must be compiled and linked with the -g option: all .cmo and .cma files that are part of the program should have been created with ocamlc -g, and they must be linked together with ocamlc -g. Compiling with -g entails no penalty on the running time of programs: object files and bytecode executable files are bigger and take longer to produce, but the executable files run at exactly the same speed as if they had been compiled without -g.
## 2 Invocation
### 2.1 Starting the debugger The OCaml debugger is invoked by running the program ocamldebug with the name of the bytecode executable file as first argument: ocamldebug [options] program [arguments] The arguments following program are optional, and are passed as command-line arguments to the program being debugged. (See also the set arguments command.) The following command-line options are recognized: -c count Set the maximum number of simultaneously live checkpoints to count. -cd dir Run the debugger program from the working directory dir, instead of the current directory. (See also the cd command.) -emacs Tell the debugger it is executed under Emacs. (See section ‍[20.10](#s%3Ainf-debugger) for information on how to run the debugger under Emacs.) -I directory Add directory to the list of directories searched for source files and compiled files. (See also the directory command.) -s socket Use socket for communicating with the debugged program. See the description of the command set socket (section ‍[20.8.8](#ss%3Adebugger-communication)) for the format of socket. -version Print version string and exit. -vnum Print short version number and exit. -help or --help Display a short usage summary and exit.
### 2.2 Initialization file On start-up, the debugger will read commands from an initialization file before giving control to the user. The default file is .ocamldebug in the current directory if it exists, otherwise .ocamldebug in the user’s home directory.
### 2.3 Exiting the debugger The command quit exits the debugger. You can also exit the debugger by typing an end-of-file character (usually ctrl-D). Typing an interrupt character (usually ctrl-C) will not exit the debugger, but will terminate the action of any debugger command that is in progress and return to the debugger command level.
## 3 Commands A debugger command is a single line of input. It starts with a command name, which is followed by arguments depending on this name. Examples: run goto 1000 set arguments arg1 arg2 A command name can be truncated as long as there is no ambiguity. For instance, go 1000 is understood as goto 1000, since there are no other commands whose name starts with go. For the most frequently used commands, ambiguous abbreviations are allowed. For instance, r stands for run even though there are others commands starting with r. You can test the validity of an abbreviation using the help command. If the previous command has been successful, a blank line (typing just RET) will repeat it.
### 3.1 Getting help The OCaml debugger has a simple on-line help system, which gives a brief description of each command and variable. help Print the list of commands. help command Give help about the command command. help set variable, help show variable Give help about the variable variable. The list of all debugger variables can be obtained with help set. help info topic Give help about topic. Use help info to get a list of known topics.
### 3.2 Accessing the debugger state set variable value Set the debugger variable variable to the value value. show variable Print the value of the debugger variable variable. info subject Give information about the given subject. For instance, info breakpoints will print the list of all breakpoints.
## 4 Executing a program
### 4.1 Events Events are “interesting” locations in the source code, corresponding to the beginning or end of evaluation of “interesting” sub-expressions. Events are the unit of single-stepping (stepping goes to the next or previous event encountered in the program execution). Also, breakpoints can only be set at events. Thus, events play the role of line numbers in debuggers for conventional languages. During program execution, a counter is incremented at each event encountered. The value of this counter is referred as the *current time*. Thanks to reverse execution, it is possible to jump back and forth to any time of the execution. Here is where the debugger events (written ⋈) are located in the source code: - Following a function application: (f arg)⋈ - On entrance to a function: fun x y z -> ⋈ ... - On each case of a pattern-matching definition (function, match…with construct, try…with construct): function pat1 -> ⋈ expr1 | ... | patN -> ⋈ exprN - Between subexpressions of a sequence: expr1; ⋈ expr2; ⋈ ...; ⋈ exprN - In the two branches of a conditional expression: if cond then ⋈ expr1 else ⋈ expr2 - At the beginning of each iteration of a loop: while cond do ⋈ body done for i = a to b do ⋈ body done Exceptions: A function application followed by a function return is replaced by the compiler by a jump (tail-call optimization). In this case, no event is put after the function application.
### 4.2 Starting the debugged program The debugger starts executing the debugged program only when needed. This allows setting breakpoints or assigning debugger variables before execution starts. There are several ways to start execution: run Run the program until a breakpoint is hit, or the program terminates. goto 0 Load the program and stop on the first event. goto time Load the program and execute it until the given time. Useful when you already know approximately at what time the problem appears. Also useful to set breakpoints on function values that have not been computed at time 0 (see section ‍[20.5](#s%3Abreakpoints)). The execution of a program is affected by certain information it receives when the debugger starts it, such as the command-line arguments to the program and its working directory. The debugger provides commands to specify this information (set arguments and cd). These commands must be used before program execution starts. If you try to change the arguments or the working directory after starting your program, the debugger will kill the program (after asking for confirmation).
### 4.3 Running the program The following commands execute the program forward or backward, starting at the current time. The execution will stop either when specified by the command or when a breakpoint is encountered. run Execute the program forward from current time. Stops at next breakpoint or when the program terminates. reverse Execute the program backward from current time. Mostly useful to go to the last breakpoint encountered before the current time. step \[count\] Run the program and stop at the next event. With an argument, do it count times. If count is 0, run until the program terminates or a breakpoint is hit. backstep \[count\] Run the program backward and stop at the previous event. With an argument, do it count times. next \[count\] Run the program and stop at the next event, skipping over function calls. With an argument, do it count times. previous \[count\] Run the program backward and stop at the previous event, skipping over function calls. With an argument, do it count times. finish Run the program until the current function returns. start Run the program backward and stop at the first event before the current function invocation.
### 4.4 Time travel You can jump directly to a given time, without stopping on breakpoints, using the goto command. As you move through the program, the debugger maintains an history of the successive times you stop at. The last command can be used to revisit these times: each last command moves one step back through the history. That is useful mainly to undo commands such as step and next. goto time Jump to the given time. last \[count\] Go back to the latest time recorded in the execution history. With an argument, do it count times. set history size Set the size of the execution history.
### 4.5 Killing the program kill Kill the program being executed. This command is mainly useful if you wish to recompile the program without leaving the debugger.
## 5 Breakpoints A breakpoint causes the program to stop whenever a certain point in the program is reached. It can be set in several ways using the break command. Breakpoints are assigned numbers when set, for further reference. The most comfortable way to set breakpoints is through the Emacs interface (see section ‍[20.10](#s%3Ainf-debugger)). break Set a breakpoint at the current position in the program execution. The current position must be on an event (i.e., neither at the beginning, nor at the end of the program). break function Set a breakpoint at the beginning of function. This works only when the functional value of the identifier function has been computed and assigned to the identifier. Hence this command cannot be used at the very beginning of the program execution, when all identifiers are still undefined; use goto time to advance execution until the functional value is available. break @ \[module\] line Set a breakpoint in module module (or in the current module if module is not given), at the first event of line line. break @ \[module\] line column Set a breakpoint in module module (or in the current module if module is not given), at the event closest to line line, column column. break @ \[module\] # character Set a breakpoint in module module at the event closest to character number character.
## 5 Breakpoints break frag:pc, break pc Set a breakpoint at code address frag:pc. The integer frag is the identifier of a code fragment, a set of modules that have been loaded at once, either initially or with the Dynlink module. The integer pc is the instruction counter within this code fragment. If frag is omitted, it defaults to 0, which is the code fragment of the program loaded initially. delete \[breakpoint-numbers\] Delete the specified breakpoints. Without argument, all breakpoints are deleted (after asking for confirmation). info breakpoints Print the list of all breakpoints.
## 6 The call stack Each time the program performs a function application, it saves the location of the application (the return address) in a block of data called a stack frame. The frame also contains the local variables of the caller function. All the frames are allocated in a region of memory called the call stack. The command backtrace (or bt) displays parts of the call stack. At any time, one of the stack frames is “selected” by the debugger; several debugger commands refer implicitly to the selected frame. In particular, whenever you ask the debugger for the value of a local variable, the value is found in the selected frame. The commands frame, up and down select whichever frame you are interested in. When the program stops, the debugger automatically selects the currently executing frame and describes it briefly as the frame command does. frame Describe the currently selected stack frame. frame frame-number Select a stack frame by number and describe it. The frame currently executing when the program stopped has number 0; its caller has number 1; and so on up the call stack. backtrace \[count\], bt \[count\] Print the call stack. This is useful to see which sequence of function calls led to the currently executing frame. With a positive argument, print only the innermost count frames. With a negative argument, print only the outermost -count frames. up \[count\] Select and display the stack frame just “above” the selected frame, that is, the frame that called the selected frame. An argument says how many frames to go up.
## 6 The call stack down \[count\] Select and display the stack frame just “below” the selected frame, that is, the frame that was called by the selected frame. An argument says how many frames to go down.
## 7 Examining variable values The debugger can print the current value of simple expressions. The expressions can involve program variables: all the identifiers that are in scope at the selected program point can be accessed. Expressions that can be printed are a subset of OCaml expressions, as described by the following grammar: <table class="display dcenter"><colgroup><col style="width: 100%" /></colgroup><tbody><tr class="odd c009"><td class="dcell"><table class="c001 cellpading0"><tbody><tr class="odd"><td class="c008">simple-expr</td><td class="c005">::=</td><td class="c007">[lowercase-ident](lex.html#lowercase-ident)</td></tr><tr class="even"><td class="c008"> </td><td class="c005">∣</td><td class="c007"> { [capitalized-ident](lex.html#capitalized-ident) . } [lowercase-ident](lex.html#lowercase-ident)</td></tr><tr class="odd"><td class="c008"> </td><td class="c005">∣</td><td class="c007"> *</td></tr><tr class="even"><td class="c008"> </td><td class="c005">∣</td><td class="c007"> $ integer</td></tr><tr class="odd"><td class="c008"> </td><td class="c005">∣</td><td class="c007"> [simple-expr](#simple-expr) . [lowercase-ident](lex.html#lowercase-ident)</td></tr><tr class="even"><td class="c008"> </td><td class="c005">∣</td><td class="c007"> [simple-expr](#simple-expr) .( integer )</td></tr><tr class="odd"><td class="c008"> </td><td class="c005">∣</td><td class="c007"> [simple-expr](#simple-expr) .[ integer ]</td></tr><tr class="even"><td class="c008"> </td><td class="c005">∣</td><td class="c007"> ! [simple-expr](#simple-expr)</td></tr><tr class="odd"><td class="c008"> </td><td class="c005">∣</td><td class="c007"> ( [simple-expr](#simple-expr) )</td></tr></tbody></table></td></tr></tbody></table>
## 7 Examining variable values The first two cases refer to a value identifier, either unqualified or qualified by the path to the structure that define it. \* refers to the result just computed (typically, the value of a function application), and is valid only if the selected event is an “after” event (typically, a function application). $ integer refer to a previously printed value. The remaining four forms select part of an expression: respectively, a record field, an array element, a string element, and the current contents of a reference. print variables Print the values of the given variables. print can be abbreviated as p. display variables Same as print, but limit the depth of printing to 1. Useful to browse large data structures without printing them in full. display can be abbreviated as d. When printing a complex expression, a name of the form $integer is automatically assigned to its value. Such names are also assigned to parts of the value that cannot be printed because the maximal printing depth is exceeded. Named values can be printed later on with the commands p $integer or d $integer. Named values are valid only as long as the program is stopped. They are forgotten as soon as the program resumes execution. set print_depth d Limit the printing of values to a maximal depth of d. set print_length l Limit the printing of values to at most l nodes printed.
## 8 Controlling the debugger
### 8.1 Setting the program name and arguments set program file Set the program name to file. set arguments arguments Give arguments as command-line arguments for the program. A shell is used to pass the arguments to the debugged program. You can therefore use wildcards, shell variables, and file redirections inside the arguments. To debug programs that read from standard input, it is recommended to redirect their input from a file (using set arguments \< input-file), otherwise input to the program and input to the debugger are not properly separated, and inputs are not properly replayed when running the program backwards.
### 8.2 How programs are loaded The loadingmode variable controls how the program is executed. set loadingmode direct The program is run directly by the debugger. This is the default mode. set loadingmode runtime The debugger execute the OCaml runtime ocamlrun on the program. Rarely useful; moreover it prevents the debugging of programs compiled in “custom runtime” mode. set loadingmode manual The user starts manually the program, when asked by the debugger. Allows remote debugging (see section ‍[20.8.8](#ss%3Adebugger-communication)).
### 8.3 Search path for files The debugger searches for source files and compiled interface files in a list of directories, the search path. The search path initially contains the current directory . and the standard library directory. The directory command adds directories to the path. Whenever the search path is modified, the debugger will clear any information it may have cached about the files. directory directorynames Add the given directories to the search path. These directories are added at the front, and will therefore be searched first. directory directorynames for modulename Same as directory directorynames, but the given directories will be searched only when looking for the source file of a module that has been packed into modulename. directory Reset the search path. This requires confirmation.
### 8.4 Working directory Each time a program is started in the debugger, it inherits its working directory from the current working directory of the debugger. This working directory is initially whatever it inherited from its parent process (typically the shell), but you can specify a new working directory in the debugger with the cd command or the -cd command-line option. cd directory Set the working directory for ocamldebug to directory. pwd Print the working directory for ocamldebug.
### 8.5 Turning reverse execution on and off In some cases, you may want to turn reverse execution off. This speeds up the program execution, and is also sometimes useful for interactive programs. Normally, the debugger takes checkpoints of the program state from time to time. That is, it makes a copy of the current state of the program (using the Unix system call fork). If the variable checkpoints is set to off, the debugger will not take any checkpoints. set checkpoints on/off Select whether the debugger makes checkpoints or not.
### 8.6 Behavior of the debugger with respect to fork When the program issues a call to fork, the debugger can either follow the child or the parent. By default, the debugger follows the parent process. The variable follow_fork_mode controls this behavior: set follow_fork_mode child/parent Select whether to follow the child or the parent in case of a call to fork.
### 8.7 Stopping execution when new code is loaded The debugger is compatible with the Dynlink module. However, when an external module is not yet loaded, it is impossible to set a breakpoint in its code. In order to facilitate setting breakpoints in dynamically loaded code, the debugger stops the program each time new modules are loaded. This behavior can be disabled using the break_on_load variable: set break_on_load on/off Select whether to stop after loading new code.
### 8.8 Communication between the debugger and the program The debugger communicate with the program being debugged through a Unix socket. You may need to change the socket name, for example if you need to run the debugger on a machine and your program on another. set socket socket Use socket for communication with the program. socket can be either a file name, or an Internet port specification host:port, where host is a host name or an Internet address in dot notation, and port is a port number on the host. On the debugged program side, the socket name is passed through the CAML_DEBUG_SOCKET environment variable.
### 8.9 Fine-tuning the debugger Several variables enables to fine-tune the debugger. Reasonable defaults are provided, and you should normally not have to change them. set processcount count Set the maximum number of checkpoints to count. More checkpoints facilitate going far back in time, but use more memory and create more Unix processes. As checkpointing is quite expensive, it must not be done too often. On the other hand, backward execution is faster when checkpoints are taken more often. In particular, backward single-stepping is more responsive when many checkpoints have been taken just before the current time. To fine-tune the checkpointing strategy, the debugger does not take checkpoints at the same frequency for long displacements (e.g. run) and small ones (e.g. step). The two variables bigstep and smallstep contain the number of events between two checkpoints in each case. set bigstep count Set the number of events between two checkpoints for long displacements. set smallstep count Set the number of events between two checkpoints for small displacements. The following commands display information on checkpoints and events: info checkpoints Print a list of checkpoints. info events \[module\] Print the list of events in the given module (the current module, by default).
### 8.10 User-defined printers Just as in the toplevel system (section ‍[14.2](toplevel.html#s%3Atoplevel-directives)), the user can register functions for printing values of certain types. For technical reasons, the debugger cannot call printing functions that reside in the program being debugged. The code for the printing functions must therefore be loaded explicitly in the debugger. load_printer "file-name" Load in the debugger the indicated .cmo or .cma object file. The file is loaded in an environment consisting only of the OCaml standard library plus the definitions provided by object files previously loaded using load_printer. If this file depends on other object files not yet loaded, the debugger automatically loads them if it is able to find them in the search path. The loaded file does not have direct access to the modules of the program being debugged. install_printer printer-name Register the function named printer-name (a value path) as a printer for objects whose types match the argument type of the function. That is, the debugger will call printer-name when it has such an object to print. The printing function printer-name must use the Format library module to produce its output, otherwise its output will not be correctly located in the values printed by the toplevel loop. The value path printer-name must refer to one of the functions defined by the object files loaded using load_printer. It cannot reference the functions of the program being debugged. remove_printer printer-name Remove the named function from the table of value printers.
## 9 Miscellaneous commands list \[module\] \[beginning\] \[end\] List the source of module module, from line number beginning to line number end. By default, 20 lines of the current module are displayed, starting 10 lines before the current position. source filename Read debugger commands from the script filename.
## 10 Running the debugger under Emacs The most user-friendly way to use the debugger is to run it under Emacs with the OCaml mode available through MELPA and also at [https://github.com/ocaml/caml-mode](https://github.com/ocaml/caml-mode). The OCaml debugger is started under Emacs by the command M-x camldebug, with argument the name of the executable file progname to debug. Communication with the debugger takes place in an Emacs buffer named \*camldebug-progname\*. The editing and history facilities of Shell mode are available for interacting with the debugger. In addition, Emacs displays the source files containing the current event (the current position in the program execution) and highlights the location of the event. This display is updated synchronously with the debugger action. The following bindings for the most common debugger commands are available in the \*camldebug-progname\* buffer: C-c C-s (command step): execute the program one step forward. C-c C-k (command backstep): execute the program one step backward. C-c C-n (command next): execute the program one step forward, skipping over function calls. Middle mouse button (command display): display named value. $n under mouse cursor (support incremental browsing of large data structures). C-c C-p (command print): print value of identifier at point. C-c C-d (command display): display value of identifier at point. C-c C-r (command run): execute the program forward to next breakpoint. C-c C-v (command reverse): execute the program backward to latest breakpoint.
## 10 Running the debugger under Emacs C-c C-l (command last): go back one step in the command history. C-c C-t (command backtrace): display backtrace of function calls. C-c C-f (command finish): run forward till the current function returns. C-c \< (command up): select the stack frame below the current frame. C-c \> (command down): select the stack frame above the current frame. In all buffers in OCaml editing mode, the following debugger commands are also available: C-x C-a C-b (command break): set a breakpoint at event closest to point C-x C-a C-p (command print): print value of identifier at point C-x C-a C-d (command display): display value of identifier at point ------------------------------------------------------------------------ [« The documentation generator (ocamldoc)](ocamldoc.html)[Profiling (ocamlprof) »](profil.html) Copyright © 2024 Institut National de Recherche en Informatique et en Automatique ------------------------------------------------------------------------
# OCaml - Profiling (ocamlprof) Source: https://ocaml.org/manual/5.2/profil.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 21 Profiling (ocamlprof) This chapter describes how the execution of OCaml programs can be profiled, by recording how many times functions are called, branches of conditionals are taken, …
## 1 Compiling for profiling Before profiling an execution, the program must be compiled in profiling mode, using the ocamlcp front-end to the ocamlc compiler (see chapter ‍[13](comp.html#c%3Acamlc)) or the ocamloptp front-end to the ocamlopt compiler (see chapter ‍[16](native.html#c%3Anativecomp)). When compiling modules separately, ocamlcp or ocamloptp must be used when compiling the modules (production of .cmo or .cmx files), and can also be used (though this is not strictly necessary) when linking them together.
##### Note If a module (.ml file) doesn’t have a corresponding interface (.mli file), then compiling it with ocamlcp will produce object files (.cmi and .cmo) that are not compatible with the ones produced by ocamlc, which may lead to problems (if the .cmi or .cmo is still around) when switching between profiling and non-profiling compilations. To avoid this problem, you should always have a .mli file for each .ml file. The same problem exists with ocamloptp.
##### Note To make sure your programs can be compiled in profiling mode, avoid using any identifier that begins with \_\_ocaml_prof. The amount of profiling information can be controlled through the -P option to ocamlcp or ocamloptp, followed by one or several letters indicating which parts of the program should be profiled: a all options f function calls : a count point is set at the beginning of each function body i if …then …else … : count points are set in both then branch and else branch l while, for loops: a count point is set at the beginning of the loop body m match branches: a count point is set at the beginning of the body of each branch t try …with … branches: a count point is set at the beginning of the body of each branch For instance, compiling with ocamlcp -P film profiles function calls, if…then…else…, loops and pattern matching. Calling ocamlcp or ocamloptp without the -P option defaults to -P fm, meaning that only function calls and pattern matching are profiled.
##### Note For compatibility with previous releases, ocamlcp also accepts the -p option, with the same arguments and behaviour as -P. The ocamlcp and ocamloptp commands also accept all the options of the corresponding ocamlc or ocamlopt compiler, except the -pp (preprocessing) option.
## 2 Profiling an execution Running an executable that has been compiled with ocamlcp or ocamloptp records the execution counts for the specified parts of the program and saves them in a file called ocamlprof.dump in the current directory. If the environment variable OCAMLPROF_DUMP is set when the program exits, its value is used as the file name instead of ocamlprof.dump. The dump file is written only if the program terminates normally (by calling exit or by falling through). It is not written if the program terminates with an uncaught exception. If a compatible dump file already exists in the current directory, then the profiling information is accumulated in this dump file. This allows, for instance, the profiling of several executions of a program on different inputs. Note that dump files produced by byte-code executables (compiled with ocamlcp) are compatible with the dump files produced by native executables (compiled with ocamloptp).
## 3 Printing profiling information The ocamlprof command produces a source listing of the program modules where execution counts have been inserted as comments. For instance, ocamlprof foo.ml prints the source code for the foo module, with comments indicating how many times the functions in this module have been called. Naturally, this information is accurate only if the source file has not been modified after it was compiled. The following options are recognized by ocamlprof: -args filename Read additional newline-terminated command line arguments from filename. -args0 filename Read additional null character terminated command line arguments from filename. -f dumpfile Specifies an alternate dump file of profiling information to be read. -F string Specifies an additional string to be output with profiling information. By default, ocamlprof will annotate programs with comments of the form (\* n \*) where n is the counter value for a profiling point. With option -F s, the annotation will be (\* sn \*). -impl filename Process the file filename as an implementation file, even if its extension is not .ml. -intf filename Process the file filename as an interface file, even if its extension is not .mli. -version Print version string and exit. -vnum Print short version number and exit. -help or --help Display a short usage summary and exit.
## 4 Time profiling Profiling with ocamlprof only records execution counts, not the actual time spent within each function. There is currently no way to perform time profiling on bytecode programs generated by ocamlc. For time profiling of native code, users are recommended to use standard tools such as perf (on Linux), Instruments (on macOS) and DTrace. Profiling with gprof is no longer supported. ------------------------------------------------------------------------ [« The debugger (ocamldebug)](debugger.html)[Interfacing C with OCaml »](intfc.html) Copyright © 2024 Institut National de Recherche en Informatique et en Automatique ------------------------------------------------------------------------
# OCaml - Interfacing C with OCaml Source: https://ocaml.org/manual/5.2/intfc.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 22 Interfacing C with OCaml This chapter describes how user-defined primitives, written in C, can be linked with OCaml code and called from OCaml functions, and how these C functions can call back to OCaml code.
## 1 Overview and compilation information
### 1.1 Declaring primitives <table class="display dcenter"><colgroup><col style="width: 100%" /></colgroup><tbody><tr class="odd c009"><td class="dcell"><table class="c001 cellpading0"><tbody><tr class="odd"><td class="c008">[definition](modules.html#definition)</td><td class="c005">::=</td><td class="c007"> ...</td></tr><tr class="even"><td class="c008"> </td><td class="c005">∣</td><td class="c007"> external [value-name](names.html#value-name) : [typexpr](types.html#typexpr) = [external-declaration](#external-declaration)</td></tr><tr class="odd"><td class="c008"> </td><td></td><td></td></tr><tr class="even"><td class="c008">external-declaration</td><td class="c005">::=</td><td class="c007"> [string-literal](lex.html#string-literal) [ [string-literal](lex.html#string-literal) [ [string-literal](lex.html#string-literal) ] ]</td></tr></tbody></table></td></tr></tbody></table> User primitives are declared in an implementation file or struct…end module expression using the external keyword: external name : type = C-function-name This defines the value name name as a function with type type that executes by calling the given C function. For instance, here is how the seek_in primitive is declared in the standard library module Stdlib: external seek_in : in_channel -> int -> unit = "caml_ml_seek_in" Primitives with several arguments are always curried. The C function does not necessarily have the same name as the ML function. External functions thus defined can be specified in interface files or sig…end signatures either as regular values
### 1.1 Declaring primitives val name : type thus hiding their implementation as C functions, or explicitly as “manifest” external functions external name : type = C-function-name The latter is slightly more efficient, as it allows clients of the module to call directly the C function instead of going through the corresponding OCaml function. On the other hand, it should not be used in library modules if they have side-effects at toplevel, as this direct call interferes with the linker’s algorithm for removing unused modules from libraries at link-time. The arity (number of arguments) of a primitive is automatically determined from its OCaml type in the external declaration, by counting the number of function arrows in the type. For instance, seek_in above has arity 2, and the caml_ml_seek_in C function is called with two arguments. Similarly, external seek_in_pair: in_channel * int -> unit = "caml_ml_seek_in_pair" has arity 1, and the caml_ml_seek_in_pair C function receives one argument (which is a pair of OCaml values). Type abbreviations are not expanded when determining the arity of a primitive. For instance, type int_endo = int -> int external f : int_endo -> int_endo = "f" external g : (int -> int) -> (int -> int) = "f" f has arity 1, but g has arity 2. This allows a primitive to return a functional value (as in the f example above): just remember to name the functional return type in a type abbreviation.
### 1.1 Declaring primitives The language accepts external declarations with one or two flag strings in addition to the C function’s name. These flags are reserved for the implementation of the standard library.
### 1.2 Implementing primitives User primitives with arity n ≤ 5 are implemented by C functions that take n arguments of type value, and return a result of type value. The type value is the type of the representations for OCaml values. It encodes objects of several base types (integers, floating-point numbers, strings, ‍…) as well as OCaml data structures. The type value and the associated conversion functions and macros are described in detail below. For instance, here is the declaration for the C function implementing the In_channel.input primitive, which takes 4 arguments: CAMLprim value input(value channel, value buffer, value offset, value length) { ... } When the primitive function is applied in an OCaml program, the C function is called with the values of the expressions to which the primitive is applied as arguments. The value returned by the function is passed back to the OCaml program as the result of the function application. User primitives with arity greater than 5 should be implemented by two C functions. The first function, to be used in conjunction with the bytecode compiler ocamlc, receives two arguments: a pointer to an array of OCaml values (the values for the arguments), and an integer which is the number of arguments provided. The other function, to be used in conjunction with the native-code compiler ocamlopt, takes its arguments directly. For instance, here are the two C functions for the 7-argument primitive Nat.add_nat:
### 1.2 Implementing primitives CAMLprim value add_nat_native(value nat1, value ofs1, value len1, value nat2, value ofs2, value len2, value carry_in) { ... } CAMLprim value add_nat_bytecode(value * argv, int argn) { return add_nat_native(argv[0], argv[1], argv[2], argv[3], argv[4], argv[5], argv[6]); } The names of the two C functions must be given in the primitive declaration, as follows: external name : type = bytecode-C-function-name native-code-C-function-name For instance, in the case of add_nat, the declaration is: external add_nat: nat -> int -> int -> nat -> int -> int -> int -> int = "add_nat_bytecode" "add_nat_native"
### 1.2 Implementing primitives Implementing a user primitive is actually two separate tasks: on the one hand, decoding the arguments to extract C values from the given OCaml values, and encoding the return value as an OCaml value; on the other hand, actually computing the result from the arguments. Except for very simple primitives, it is often preferable to have two distinct C functions to implement these two tasks. The first function actually implements the primitive, taking native C values as arguments and returning a native C value. The second function, often called the “stub code”, is a simple wrapper around the first function that converts its arguments from OCaml values to C values, calls the first function, and converts the returned C value to an OCaml value. For instance, here is the stub code for the Int64.float_of_bits primitive: CAMLprim value caml_int64_float_of_bits(value vi) { return caml_copy_double(caml_int64_float_of_bits_unboxed(Int64_val(vi))); } (Here, caml_copy_double and Int64_val are conversion functions and macros for the type value, that will be described later. The CAMLprim macro expands to the required compiler directives to ensure that the function is exported and accessible from OCaml.) The hard work is performed by the function caml_int64_float_of_bits_unboxed, which is declared as: double caml_int64_float_of_bits_unboxed(int64_t i) { ... } To write C code that operates on OCaml values, the following include files are provided:
### 1.2 Implementing primitives | | | |---------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------| | Include file | Provides | | caml/mlvalues.h | definition of the value type, and conversion macros | | caml/alloc.h | allocation functions (to create structured OCaml objects) | | caml/memory.h | miscellaneous memory-related functions and macros (for GC interface, in-place modification of structures, etc). | | caml/fail.h | functions for raising exceptions (see section ‍[22.4.5](#ss%3Ac-exceptions)) | | caml/callback.h | callback from C to OCaml (see section ‍[22.7](#s%3Ac-callback)). | | caml/custom.h | operations on custom blocks (see section ‍[22.9](#s%3Ac-custom)). | | caml/intext.h | operations for writing user-defined serialization and deserialization functions for custom blocks (see section ‍[22.9](#s%3Ac-custom)). | | caml/threads.h | operations for interfacing in the presence of multiple threads (see section ‍[22.12](#s%3AC-multithreading)). |
### 1.2 Implementing primitives These files reside in the caml/ subdirectory of the OCaml standard library directory, which is returned by the command ocamlc -where (usually /usr/local/lib/ocaml or /usr/lib/ocaml).
### 1.3 Statically linking C code with OCaml code The OCaml runtime system comprises three main parts: the bytecode interpreter, the memory manager, and a set of C functions that implement the primitive operations. Some bytecode instructions are provided to call these C functions, designated by their offset in a table of functions (the table of primitives). In the default mode, the OCaml linker produces bytecode for the standard runtime system, with a standard set of primitives. References to primitives that are not in this standard set result in the “unavailable C primitive” error. (Unless dynamic loading of C libraries is supported – see section ‍[22.1.4](#ss%3Adynlink-c-code) below.) In the “custom runtime” mode, the OCaml linker scans the object files and determines the set of required primitives. Then, it builds a suitable runtime system, by calling the native code linker with: - the table of the required primitives; - a library that provides the bytecode interpreter, the memory manager, and the standard primitives; - libraries and object code files (.o files) mentioned on the command line for the OCaml linker, that provide implementations for the user’s primitives. This builds a runtime system with the required primitives. The OCaml linker generates bytecode for this custom runtime system. The bytecode is appended to the end of the custom runtime system, so that it will be automatically executed when the output file (custom runtime + bytecode) is launched. To link in “custom runtime” mode, execute the ocamlc command with: - the -custom option;
### 1.3 Statically linking C code with OCaml code - the names of the desired OCaml object files (.cmo and .cma files) ; - the names of the C object files and libraries (.o and .a files) that implement the required primitives. Under Unix and Windows, a library named libname.a (respectively, .lib) residing in one of the standard library directories can also be specified as -cclib -lname. If you are using the native-code compiler ocamlopt, the -custom flag is not needed, as the final linking phase of ocamlopt always builds a standalone executable. To build a mixed OCaml/C executable, execute the ocamlopt command with: - the names of the desired OCaml native object files (.cmx and .cmxa files); - the names of the C object files and libraries (.o, .a, .so or .dll files) that implement the required primitives. Starting with Objective Caml 3.00, it is possible to record the -custom option as well as the names of C libraries in an OCaml library file .cma or .cmxa. For instance, consider an OCaml library mylib.cma, built from the OCaml object files a.cmo and b.cmo, which reference C code in libmylib.a. If the library is built as follows: ocamlc -a -o mylib.cma -custom a.cmo b.cmo -cclib -lmylib users of the library can simply link with mylib.cma: ocamlc -o myprog mylib.cma ... and the system will automatically add the -custom and -cclib -lmylib options, achieving the same effect as ocamlc -o myprog -custom a.cmo b.cmo ... -cclib -lmylib The alternative is of course to build the library without extra options:
### 1.3 Statically linking C code with OCaml code ocamlc -a -o mylib.cma a.cmo b.cmo and then ask users to provide the -custom and -cclib -lmylib options themselves at link-time: ocamlc -o myprog -custom mylib.cma ... -cclib -lmylib The former alternative is more convenient for the final users of the library, however.
### 1.4 Dynamically linking C code with OCaml code Starting with Objective Caml 3.03, an alternative to static linking of C code using the -custom code is provided. In this mode, the OCaml linker generates a pure bytecode executable (no embedded custom runtime system) that simply records the names of dynamically-loaded libraries containing the C code. The standard OCaml runtime system ocamlrun then loads dynamically these libraries, and resolves references to the required primitives, before executing the bytecode. This facility is currently available on all platforms supported by OCaml except Cygwin 64 bits. To dynamically link C code with OCaml code, the C code must first be compiled into a shared library (under Unix) or DLL (under Windows). This involves 1- compiling the C files with appropriate C compiler flags for producing position-independent code (when required by the operating system), and 2- building a shared library from the resulting object files. The resulting shared library or DLL file must be installed in a place where ocamlrun can find it later at program start-up time (see section ‍[15.3](runtime.html#s%3Aocamlrun-dllpath)). Finally (step 3), execute the ocamlc command with - the names of the desired OCaml object files (.cmo and .cma files) ; - the names of the C shared libraries (.so or .dll files) that implement the required primitives. Under Unix and Windows, a library named dllname.so (respectively, .dll) residing in one of the standard library directories can also be specified as -dllib -lname.
### 1.4 Dynamically linking C code with OCaml code Do *not* set the -custom flag, otherwise you’re back to static linking as described in section ‍[22.1.3](#ss%3Astaticlink-c-code). The ocamlmklib tool (see section ‍[22.14](#s%3Aocamlmklib)) automates steps 2 and 3. As in the case of static linking, it is possible (and recommended) to record the names of C libraries in an OCaml .cma library archive. Consider again an OCaml library mylib.cma, built from the OCaml object files a.cmo and b.cmo, which reference C code in dllmylib.so. If the library is built as follows: ocamlc -a -o mylib.cma a.cmo b.cmo -dllib -lmylib users of the library can simply link with mylib.cma: ocamlc -o myprog mylib.cma ... and the system will automatically add the -dllib -lmylib option, achieving the same effect as ocamlc -o myprog a.cmo b.cmo ... -dllib -lmylib Using this mechanism, users of the library mylib.cma do not need to know that it references C code, nor whether this C code must be statically linked (using -custom) or dynamically linked.
### 1.5 Choosing between static linking and dynamic linking After having described two different ways of linking C code with OCaml code, we now review the pros and cons of each, to help developers of mixed OCaml/C libraries decide. The main advantage of dynamic linking is that it preserves the platform-independence of bytecode executables. That is, the bytecode executable contains no machine code, and can therefore be compiled on platform A and executed on other platforms B, C, …, as long as the required shared libraries are available on all these platforms. In contrast, executables generated by ocamlc -custom run only on the platform on which they were created, because they embark a custom-tailored runtime system specific to that platform. In addition, dynamic linking results in smaller executables. Another advantage of dynamic linking is that the final users of the library do not need to have a C compiler, C linker, and C runtime libraries installed on their machines. This is no big deal under Unix and Cygwin, but many Windows users are reluctant to install Microsoft Visual C just to be able to do ocamlc -custom.
### 1.5 Choosing between static linking and dynamic linking There are two drawbacks to dynamic linking. The first is that the resulting executable is not stand-alone: it requires the shared libraries, as well as ocamlrun, to be installed on the machine executing the code. If you wish to distribute a stand-alone executable, it is better to link it statically, using ocamlc -custom -ccopt -static or ocamlopt -ccopt -static. Dynamic linking also raises the “DLL hell” problem: some care must be taken to ensure that the right versions of the shared libraries are found at start-up time. The second drawback of dynamic linking is that it complicates the construction of the library. The C compiler and linker flags to compile to position-independent code and build a shared library vary wildly between different Unix systems. Also, dynamic linking is not supported on all Unix systems, requiring a fall-back case to static linking in the Makefile for the library. The ocamlmklib command (see section ‍[22.14](#s%3Aocamlmklib)) tries to hide some of these system dependencies. In conclusion: dynamic linking is highly recommended under the native Windows port, because there are no portability problems and it is much more convenient for the end users. Under Unix, dynamic linking should be considered for mature, frequently used libraries because it enhances platform-independence of bytecode executables. For new or rarely-used libraries, static linking is much simpler to set up in a portable way.
### 1.6 Building standalone custom runtime systems It is sometimes inconvenient to build a custom runtime system each time OCaml code is linked with C libraries, like ocamlc -custom does. For one thing, the building of the runtime system is slow on some systems (that have bad linkers or slow remote file systems); for another thing, the platform-independence of bytecode files is lost, forcing to perform one ocamlc -custom link per platform of interest. An alternative to ocamlc -custom is to build separately a custom runtime system integrating the desired C libraries, then generate “pure” bytecode executables (not containing their own runtime system) that can run on this custom runtime. This is achieved by the -make-runtime and -use-runtime flags to ocamlc. For example, to build a custom runtime system integrating the C parts of the “Unix” and “Threads” libraries, do: ocamlc -make-runtime -o /home/me/ocamlunixrun unix.cma threads.cma To generate a bytecode executable that runs on this runtime system, do: ocamlc -use-runtime /home/me/ocamlunixrun -o myprog \ unix.cma threads.cma your .cmo and .cma files The bytecode executable myprog can then be launched as usual: myprog args or /home/me/ocamlunixrun myprog args. Notice that the bytecode libraries unix.cma and threads.cma must be given twice: when building the runtime system (so that ocamlc knows which C primitives are required) and also when building the bytecode executable (so that the bytecode from unix.cma and threads.cma is actually linked in).
## 2 The value type All OCaml objects are represented by the C type value, defined in the include file caml/mlvalues.h, along with macros to manipulate values of that type. An object of type value is either: - an unboxed integer; - or a pointer to a block inside the heap, allocated through one of the `caml_alloc_*` functions described in section ‍[22.4.4](#ss%3Ac-block-allocation).
### 2.1 Integer values Integer values encode 63-bit signed integers (31-bit on 32-bit architectures). They are unboxed (unallocated).
### 2.2 Blocks Blocks in the heap are garbage-collected, and therefore have strict structure constraints. Each block includes a header containing the size of the block (in words), and the tag of the block. The tag governs how the contents of the blocks are structured. A tag lower than No_scan_tag indicates a structured block, containing well-formed values, which is recursively traversed by the garbage collector. A tag greater than or equal to No_scan_tag indicates a raw block, whose contents are not scanned by the garbage collector. For the benefit of ad-hoc polymorphic primitives such as equality and structured input-output, structured and raw blocks are further classified according to their tags as follows:
### 2.2 Blocks | | | |------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | Tag | Contents of the block | | 0 to No_scan_tag−1 | A structured block (an array of OCaml objects). Each field is a value. | | Closure_tag | A closure representing a functional value. The first word is a pointer to a piece of code, the remaining words are value containing the environment. | | String_tag | A character string or a byte sequence. | | Double_tag | A double-precision floating-point number. | | Double_array_tag | An array or record of double-precision floating-point numbers. | | Abstract_tag | A block representing an abstract datatype. | | Custom_tag | A block representing an abstract datatype with user-defined finalization, comparison, hashing, serialization and deserialization functions attached. |
### 2.3 Pointers outside the heap In earlier versions of OCaml, it was possible to use word-aligned pointers to addresses outside the heap as OCaml values, just by casting the pointer to type value. This usage is no longer supported since OCaml 5.0. A correct way to manipulate pointers to out-of-heap blocks from OCaml is to store those pointers in OCaml blocks with tag Abstract_tag or Custom_tag, then use the blocks as the OCaml values. Here is an example of encapsulation of out-of-heap pointers of C type ty \* inside Abstract_tag blocks. Section ‍[22.6](#s%3Ac-intf-example) gives a more complete example using Custom_tag blocks. /* Create an OCaml value encapsulating the pointer p */ static value val_of_typtr(ty * p) { value v = caml_alloc(1, Abstract_tag); *((ty **) Data_abstract_val(v)) = p; return v; } /* Extract the pointer encapsulated in the given OCaml value */ static ty * typtr_of_val(value v) { return *((ty **) Data_abstract_val(v)); } Alternatively, out-of-heap pointers can be treated as “native” integers, that is, boxed 32-bit integers on a 32-bit platform and boxed 64-bit integers on a 64-bit platform. /* Create an OCaml value encapsulating the pointer p */ static value val_of_typtr(ty * p) { return caml_copy_nativeint((intnat) p); } /* Extract the pointer encapsulated in the given OCaml value */ static ty * typtr_of_val(value v) { return (ty *) Nativeint_val(v); }
### 2.3 Pointers outside the heap For pointers that are at least 2-aligned (the low bit is guaranteed to be zero), we have yet another valid representation as an OCaml tagged integer. /* Create an OCaml value encapsulating the pointer p */ static value val_of_typtr(ty * p) { assert (((uintptr_t) p & 1) == 0); /* check correct alignment */ return (value) p | 1; } /* Extract the pointer encapsulated in the given OCaml value */ static ty * typtr_of_val(value v) { return (ty *) (v & ~1); }
## 3 Representation of OCaml data types This section describes how OCaml data types are encoded in the value type.
### 3.1 Atomic types | | | |---------------------------------------------------------------------|---------------------------------------------------------------------------------------| | OCaml type | Encoding | | int | Unboxed integer values. | | char | Unboxed integer values (ASCII code). | | float | Blocks with tag Double_tag. | | bytes | Blocks with tag String_tag. | | string | Blocks with tag String_tag. | | int32 | Blocks with tag Custom_tag. | | int64 | Blocks with tag Custom_tag. | | nativeint | Blocks with tag Custom_tag. |
### 3.2 Tuples and records Tuples are represented by pointers to blocks, with tag ‍0. Records are also represented by zero-tagged blocks. The ordering of labels in the record type declaration determines the layout of the record fields: the value associated to the label declared first is stored in field ‍0 of the block, the value associated to the second label goes in field ‍1, and so on. As an optimization, records whose fields all have static type float are represented as arrays of floating-point numbers, with tag Double_array_tag. (See the section below on arrays.) As another optimization, unboxable record types are represented specially; unboxable record types are the immutable record types that have only one field. An unboxable type will be represented in one of two ways: boxed or unboxed. Boxed record types are represented as described above (by a block with tag 0 or Double_array_tag). An unboxed record type is represented directly by the value of its field (i.e. there is no block to represent the record itself). The representation is chosen according to the following, in decreasing order of priority: - An attribute (\[@@boxed\] or \[@@unboxed\]) on the type declaration. - A compiler option (-unboxed-types or -no-unboxed-types). - The default representation. In the present version of OCaml, the default is the boxed representation.