-stars

Remove blank characters until the first asterisk (`*`) in each line of comments.

-t *title*

Use *title* as the title for the generated documentation.

-intro *file*

Use content of *file* as ocamldoc text to use as introduction (HTML, LATEX and TeXinfo only).
For HTML, the file is used to create the whole *index.html* file.

-v
Verbose mode. Display progress information.

-version

Print version string and exit.

-vnum

Print short version number and exit.

-warn-error

Treat Ocamldoc warnings as errors.

-hide-warnings

Do not print OCamldoc warnings.

-help or --help

Display a short usage summary and exit.

Type-checking options

OCamldoc calls the OCaml type-checker to obtain type information. The following options impact
the type-checking phase. They have the same meaning as for the ocamlc and ocamlopt commands.

-I *directory*

Add *directory* to the list of directories search for compiled interface files (`.cmi` files).

-H *directory*

Like -I, but the -H directories are searched last and the program may not directly refer to
the modules added to the search path this way.

-nolabels

Ignore non-optional labels in types.

-rectypes

Allow arbitrary recursive types. (See the -rectypes option to ocamlc.)
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.

### 19.2.9 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}`, `{ol list}`, `[ string ]`, `[[ string ]]`, `{v string v}`, `{% string %}`, `{! string}`, `{~ text}`, `{_ text}`.

### 19.2.10 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.

### 19.2.11 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]..`.

### 19.2.12 Documentation tags (@-tags)

### 19.2.13 Predefined tags

The following table gives the list of predefined @-tags, with their syntax and meaning.
## Options for generating HTML pages

The following options apply in conjunction with the `-html` option:

**-all-params**

Display the complete list of parameters for functions and methods.

**-charset charset**

Add information about character encoding being `charset` (default is `iso-8859-1`).

**-colorize-code**

Colorize the OCaml code enclosed in `[]` and `[[ ]]`, using colors to emphasize keywords, etc.
If the code fragments are not syntactically correct, no color is added.

**-css-style filename**

Use `filename` as the Cascading Style Sheet file.

**-index-only**

Generate only index files.

**-short-functors**

Use a short form to display functors:

```
module M : functor (A:Module) -> functor (B:Module2) -> sig .. end
```

is displayed as:

```
module M (A:Module) (B:Module2) : sig .. end
```

## Options for generating LATEX files

The following options apply in conjunction with the `-latex` option:

**-latex-value-prefix prefix**

Give a prefix to use for the labels of the values in the generated LATEX document. The default prefix is the empty string. You can also use the options `-latex-type-prefix`, `-latex-exception-prefix`, `-latex-module-prefix`, `-latex-module-type-prefix`, `-latex-class-prefix`, `-latex-class-type-prefix`, `-latex-attribute-prefix` and `-latex-method-prefix`.

These options are useful when you have, for example, a type and a value with the same name. If you do not specify prefixes, LATEX will complain about multiply defined labels.

**-latextitle n,style**

Associate style number `n` to the given LATEX sectioning command `style`, e.g. `section` or `subsection`. (LATEX only.) This is useful when including the generated document in another LATEX document, at a given sectioning level. The default association is 1 for `section`, 2 for `subsection`, 3 for `subsubsection`, 4 for `paragraph` and 5 for `subparagraph`.
<table><tr><td>author string</td><td>The author of the element. One author per author tag. There may be several author tags for the same element.</td></tr><tr><td>deprecated text</td><td>The text should describe when the element was deprecated, what to use as a replacement, and possibly the reason for deprecation.</td></tr><tr><td>param id text</td><td>Associate the given description (text) to the given parameter name id. This tag is used for functions, methods, classes and functors.</td></tr><tr><td>raise Exc text</td><td>Explain that the element may raise the exception Exc.</td></tr><tr><td>return text</td><td>Describe the return value and its possible values. This tag is used for functions and methods.</td></tr><tr><td>see &lt; URL &gt; text</td><td>Add a reference to the URL with the given text as comment.</td></tr><tr><td>see 'filename' text</td><td>Add a reference to the given file name (written between single quotes), with the given text as comment.</td></tr><tr><td>see "document-name" text</td><td>Add a reference to the given document name (written between double quotes), with the given text as comment.</td></tr><tr><td>since string</td><td>Indicate when the element was introduced.</td></tr><tr><td>before version text</td><td>Associate the given description (text) to the given version in order to document compatibility issues.</td></tr><tr><td>version string</td><td>The version number for the element.</td></tr></table>

### 19.2.14 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.

## 19.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.
-noheader

Suppress header in generated documentation.

-notoc

Do not generate a table of contents.

-notrailer

Suppress trailer in generated documentation.

-sepfiles

Generate one .tex file per toplevel module, instead of the global ocamldoc.out file.

## Options for generating TeXinfo files

The following options apply in conjunction with the -texi option:

-esc8

Escape accented characters in Info files.

-info-entry

Specify Info directory entry.

-info-section

Specify section of Info directory.

-noheader

Suppress header in generated documentation.

-noindex

Do not build index for Info files.

-notrailer

Suppress trailer in generated documentation.

## Options for generating dot graphs

The following options apply in conjunction with the -dot option:

-dot-colors colors

Specify the colors to use in the generated dot code. When generating module dependencies, ocamldoc uses different colors for modules, depending on the directories in which they reside. When generating types dependencies, ocamldoc uses different colors for types, depending on the modules in which they are defined. colors is a list of color names separated by ',' , as in Red,Blue,Green . The available colors are the ones supported by the dot tool.

-dot-include-all

Include all modules in the dot output, not only modules given on the command line or loaded with the -load option.
### 19.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 LATEX: `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:

```python
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).

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:

```python
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);;
```
-dot-reduce

Perform a transitive reduction of the dependency graph before outputting the dot code. This
can be useful if there are a lot of transitive dependencies that clutter the graph.

-dot-types

Output dot code describing the type dependency graph instead of the module dependency graph.

Options for generating man files

The following options apply in conjunction with the `-man` option:

-man-mini

Generate man pages only for modules, module types, classes and class types, instead of pages
for all elements.

-man-suffix *suffix*

Set the suffix used for generated man filenames. Default is '3o', as in List.3o.

-man-section *section*

Set the section number used for generated man filenames. Default is '3'.

19.1.2 Merging of module information

Information on a module can be extracted either from the .mli or .ml file, or both, depending on
the files given on the command line. When both .mli and .ml files are given for the same module,
information extracted from these files is merged according to the following rules:

* Only elements (values, types, classes, ...) declared in the .mli file are kept. In other terms, definitions from the .ml file that are not exported in the .mli file are not documented.

* Descriptions of elements and descriptions in @-tags are handled as follows. If a description for the same element or in the same @-tag of the same element is present in both files, then the description of the .ml file is concatenated to the one in the .mli file, if the corresponding -m flag is given on the command line. If a description is present in the .ml file and not in the .mli file, the .ml description is kept. In either case, all the information given in the .mli file is kept.

19.1.3 Coding rules

The following rules must be respected in order to avoid name clashes resulting in cross-reference
errors:

* In a module, there must not be two modules, two module types or a module and a module type with the same name. In the default HTML generator, modules ab and AB will be printed to the same file on case insensitive file systems.

* In a module, there must not be two classes, two class types or a class and a class type with the same name.
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`,

* for LATEX : `odoc_latex.ml`,

* for TeXinfo : `odoc_texti.ml`,

* for man pages : `odoc_man.ml`,

* for graphviz (dot) : `odoc.dot.ml`.

### 19.3.2 Handling custom tags

Making a custom generator handle custom tags (see 19.2.14) 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:

```python
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`.

### 19.3.3 For other generators

You can act the same way for other kinds of generators.
* In a module, there must not be two values, two types, or two exceptions with the same name.

* Values defined in tuple, as in `let (x,y,z) = (1,2,3)` are not kept by OCamldoc.

* Avoid the following construction:

```hml
open Foo (* which has a module Bar with a value x *)
```

```hml
module Foo =
    struct
        module Bar =
            struct
                let x = 1
            end
    end
    let dummy = Bar.x
```

In this case, OCamldoc will associate `Bar.x` to the `x` of module `Foo` defined just above, instead of to the `Bar.x` defined in the opened module `Foo`.

## 19.2 Syntax of documentation comments

Comments containing documentation material are called *special comments* and are written between (**) and *. Special comments must start exactly with (**). Comments beginning with ( and more than two * are ignored.

### 19.2.1 Placement of documentation comments

OCamldoc can associate comments to some elements of the language encountered in the source files. The association is made according to the locations of comments with respect to the language elements. The locations of comments in `.mli` and `.ml` files are different.

### 19.2.2 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.
## 19.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.

### 19.4.1 Compilation and usage

### 19.4.2 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.

### 19.4.3 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₁.ml[i]`, `file₂.ml[i]`, ..., `fileₙ.ml[i]`. A `.cma` library file must be created, including all these files.

The following commands create the `custom.cma` file from files `file₁.ml[i]`, ..., `fileₙ.ml[i]` :

`ocamlc -I +ocamldoc -c file₁.ml[i]`

`ocamlc -I +ocamldoc -c file₂.ml[i]`

...

`ocamlc -I +ocamldoc -c fileₙ.ml[i]`

`ocamlc -o custom.cma -a file₁.cmo file₂.cmo ... fileₙ.cmo`

Then, the following command uses `custom.cma` as custom generator:

`ocamldoc -g custom.cma other-options source-files`
The following sample interface file `foo.mli` illustrates the placement rules for comments in `.mli` files.

(** 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 *)
# 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.

### 20.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`.

### 20.2 Invocation

#### 20.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*.
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

19.2.3 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.

(** 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 *)
**-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 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) 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.

**20.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.

**20.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.

**20.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
```
| **Sun** (**The comment for constructor Sun** *)

(** The comment for type my\_record *)

```h
type my_record = {
    foo : int ;      (** Comment for field foo *)
    bar : string ;   (** Comment for field bar *)
}
```

(** The comment for class my\_class *)

```h
class my_class =
    object
        (** A comment to describe inheritance from cl *)
        inherit cl
```

(** The comment for the instance variable tutu *)

```h
val mutable tutu = "tutu"
```

(** The comment for toto *)

```h
val toto = 1
val titi = "titi"
```

(** Comment for method toto *)

```h
method toto = tutu ^ "!"
```

(** Comment for method m *)

```h
method m (f : float) = 1
end
```

(** The comment for class type my\_class\_type *)

```h
class type my_class_type =
    object
        (** The comment for the instance variable x. *)
        val mutable x : int
```

(** The comment for method m. *)

```h
method m : int -> int
end
```

(** The comment for module Foo *)

```h
module Foo =
    struct
        (** The comment for x *)
        let x = 0
```

(** A special comment in the class, but not associated to any element. *)

```h
end
```

(** The comment for module type my\_module\_type. *)

```h
module type my_module_type =
    sig
```
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.

### 20.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.

### 20.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.

## 20.4 Executing a program

### 20.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 $\dagger$) are located in the source code:
(* Comment for value x. *)

val x : int

(* ... *)

end

### 19.2.4 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.

### 19.2.5 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
* 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.

### 20.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).

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).
@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.

19.2.6 Text formatting

Here is the BNF grammar for the simple markup language used to format text descriptions.
### 20.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.

### 20.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.
text ::= {text-element}⁺

inline-text ::= {inline-text-element}⁺

text-element ::=

<table><tr><td>inline-text-element</td><td></td></tr><tr><td>blank-line</td><td>force a new line.</td></tr></table>

inline-text-element ::=

<table><tr><td>{ {0...9}⁺ inline-text }</td><td>format text as a section header; the integer following { indicates the sectioning level.</td></tr><tr><td>{ {0...9}⁺ : label inline-text }</td><td>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.</td></tr><tr><td>{b inline-text }</td><td>set text in bold.</td></tr><tr><td>{i inline-text }</td><td>set text in italic.</td></tr><tr><td>{e inline-text }</td><td>emphasize text.</td></tr><tr><td>{C inline-text }</td><td>center text.</td></tr><tr><td>{L inline-text }</td><td>left align text.</td></tr><tr><td>{R inline-text }</td><td>right align text.</td></tr><tr><td>{ul list }</td><td>build a list.</td></tr><tr><td>{ol list }</td><td>build an enumerated list.</td></tr><tr><td>{[: string ] inline-text }</td><td>put a link to the given address (given as string) on the given text.</td></tr><tr><td>[ string ]</td><td>set the given string in source code style.</td></tr><tr><td>{[ string ]}</td><td>set the given string in preformatted source code style.</td></tr><tr><td>{v string v}</td><td>set the given string in verbatim style.</td></tr><tr><td>{% string %}</td><td>target-specific content (LATEX code by default, see details in 19.2.10)</td></tr><tr><td>{! string }</td><td>insert a cross-reference to an element (see section 19.2.8 for the syntax of cross-references).</td></tr><tr><td>{{! string } inline-text }</td><td>insert a cross-reference with the given text.</td></tr><tr><td>{!modules: string string... }</td><td>insert an index table for the given module names. Used in HTML only.</td></tr><tr><td>{!indexlist}</td><td>insert a table of links to the various indexes (types, values, modules, ...). Used in HTML only.</td></tr><tr><td>{^ inline-text }</td><td>set text in superscript.</td></tr><tr><td>{_ inline-text }</td><td>set text in subscript.</td></tr><tr><td>escaped-string</td><td>typeset the given string as is; special characters ('{', '}', '[' , ']', and '@') must be escaped by a '\'</td></tr></table>
### 20.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.

## 20.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).

**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*.

**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.
### 19.2.7 List formatting

$$ \texttt{list ::=} \\ \quad | \{\{- inline-text \}\}^{+} \\ \quad | \{\{li inline-text \}\}^{+} $$

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.

### 19.2.8 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:

<table><thead><tr><th>tag</th><th>syntactic class</th></tr></thead><tbody><tr><td>module:</td><td>module</td></tr><tr><td>modtype:</td><td>module type</td></tr><tr><td>class:</td><td>class</td></tr><tr><td>classtype:</td><td>class type</td></tr><tr><td>val:</td><td>value</td></tr><tr><td>type:</td><td>type</td></tr><tr><td>exception:</td><td>exception</td></tr><tr><td>attribute:</td><td>attribute</td></tr><tr><td>method:</td><td>class method</td></tr><tr><td>section:</td><td>ocamldoc section</td></tr><tr><td>const:</td><td>variant constructor</td></tr><tr><td>recfield:</td><td>record field</td></tr></tbody></table>
## 20.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.

### 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.

## 20.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
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.

### 19.2.9 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}`, `{ol list}`, `[ string ]`, `[[ string ]]`, `{v string v}`, `{% string %}`, `{! string}`, `{~ text}`, `{_ text}`.

### 19.2.10 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.

### 19.2.11 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] ..]`.

### 19.2.12 Documentation tags (@-tags)

### 19.2.13 Predefined tags

The following table gives the list of predefined @-tags, with their syntax and meaning.
grammar:

<table><tr><td>simple-expr</td><td>::=</td><td>lowercase-ident</td></tr><tr><td></td><td></td><td>| {capitalized-ident .} lowercase-ident</td></tr><tr><td></td><td></td><td>| *</td></tr><tr><td></td><td></td><td>| $ integer</td></tr><tr><td></td><td></td><td>| simple-expr . lowercase-ident</td></tr><tr><td></td><td></td><td>| simple-expr . ( integer )</td></tr><tr><td></td><td></td><td>| simple-expr . [ integer ]</td></tr><tr><td></td><td></td><td>| ! simple-expr</td></tr><tr><td></td><td></td><td>| ( simple-expr )</td></tr></table>

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.

## 20.8 Controlling the debugger

### 20.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.
<table><tr><td>author string</td><td>The author of the element. One author per author tag. There may be several author tags for the same element.</td></tr><tr><td>deprecated text</td><td>The text should describe when the element was deprecated, what to use as a replacement, and possibly the reason for deprecation.</td></tr><tr><td>param id text</td><td>Associate the given description (text) to the given parameter name id. This tag is used for functions, methods, classes and functors.</td></tr><tr><td>raise Exc text</td><td>Explain that the element may raise the exception Exc.</td></tr><tr><td>return text</td><td>Describe the return value and its possible values. This tag is used for functions and methods.</td></tr><tr><td>see &lt; URL &gt; text</td><td>Add a reference to the URL with the given text as comment.</td></tr><tr><td>see 'filename' text</td><td>Add a reference to the given file name (written between single quotes), with the given text as comment.</td></tr><tr><td>see "document-name" text</td><td>Add a reference to the given document name (written between double quotes), with the given text as comment.</td></tr><tr><td>since string</td><td>Indicate when the element was introduced.</td></tr><tr><td>before version text</td><td>Associate the given description (text) to the given version in order to document compatibility issues.</td></tr><tr><td>version string</td><td>The version number for the element.</td></tr></table>

### 19.2.14 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.

## 19.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.
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.

### 20.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).

### 20.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.

### 20.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`.
### 19.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_htmlCCRHtml_generator` (class `html`),

* for LATEX: `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 DotDot_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:

```python
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).

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:

```python
module Generator (G : Odoc_htmlCCRHtml_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_genCCRHtml functor);;
```
`pwd` Print the working directory for `ocamldebug`.

### 20.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.

### 20.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`.

### 20.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.

### 20.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.
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`,

* for LATEX : `odoc_latex.ml`,

* for TeXinfo : `odoc_texti.ml`,

* for man pages : `odoc_man.ml`,

* for graphviz (dot) : `odocicular.ml`.

### 19.3.2 Handling custom tags

Making a custom generator handle custom tags (see 19.2.14) 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:

```python
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`.

### 19.3.3 For other generators

You can act the same way for other kinds of generators.
### 20.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).

### 20.8.10 User-defined printers

Just as in the toplevel system (section 14.2), 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_printers "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_printers`. 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_printers 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
## 19.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.

### 19.4.1 Compilation and usage

### 19.4.2 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.

### 19.4.3 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₁.ml[i]`, `file₂.ml[i]`, ..., `fileₙ.ml[i]`. A `.cma` library file must be created, including all these files. The following commands create the `custom.cma` file from files `file₁.ml[i]`, ..., `fileₙ.ml[i]` :

`ocamlc -I +ocamldoc -c file₁.ml[i]`

`ocamlc -I +ocamldoc -c file₂.ml[i]`

...

`ocamlc -I +ocamldoc -c fileₙ.ml[i]`

`ocamlc -o custom.cma -a file₁.cmo file₂.cmo ... fileₙ.cmo`

Then, the following command uses `custom.cma` as custom generator:

`ocamldoc -g custom.cma other-options source-files`
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_printers`. It cannot reference the functions of the program being debugged.

`remove_printers printer-name`

Remove the named function from the table of value printers.

## 20.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*.

## 20.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.

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.

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
# Chapter 20

## The debugger (ocamldebug)

This chapter describes the OCaml source-level replay debugger `ocamldebug`.

The debugger is available on systems that provide BSD sockets, including Windows. Under the native Windows ports, the `replay` functions are not enabled.

### 20.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`.

### 20.2 Invocation

#### 20.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 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) 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.

20.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.

20.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.

20.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.
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, ...

**21.1 Compiling for profiling**

Before profiling an execution, the program must be compiled in profiling mode, using the ocamlc
front-end to the ocamlc compiler (see chapter 13) or the ocamloptp front-end to the ocamlopt
compiler (see chapter 16). When compiling modules separately, ocamlc 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 ocamlc 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
### 20.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.

### 20.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.

## 20.4 Executing a program

### 20.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 $\dagger$) are located in the source code:

* Following a function application:

$(f arg)\dagger$

* On entrance to a function:
**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.

## 21.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`).

## 21.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.
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.

### 20.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).

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).
-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.

## 21.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.
### 20.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.

### 20.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.
### 20.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.

## 20.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).

**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*.

**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.
# 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.

### 22.1 Overview and compilation information

#### 22.1.1 Declaring primitives

```
definition ::= ...
               | external value-name : typexpr = external-declaration
```

```
external-declaration ::= string-literal [string-literal [string-literal]]
```

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

```
val name : type
```

thus hiding their implementation as C functions, or explicitly as "manifest" external functions

```
external name : type = C-function-name
```
## 20.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.

**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.

## 20.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
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.

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.

### 22.1.2 Implementing primitives

User primitives with arity $n \le 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`:
grammar:

<table><tr><td>simple-expr</td><td>::=</td><td>lowercase-ident</td></tr><tr><td></td><td></td><td>| {capitalized-ident .} lowercase-ident</td></tr><tr><td></td><td></td><td>| *</td></tr><tr><td></td><td></td><td>| $ integer</td></tr><tr><td></td><td></td><td>| simple-expr . lowercase-ident</td></tr><tr><td></td><td></td><td>| simple-expr . ( integer )</td></tr><tr><td></td><td></td><td>| simple-expr . [ integer ]</td></tr><tr><td></td><td></td><td>| ! simple-expr</td></tr><tr><td></td><td></td><td>| ( simple-expr )</td></tr></table>

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.

## 20.8 Controlling the debugger

### 20.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.
```c
CAMLprim value add_native(value nat1, value ofs1, value len1,
                             value nat2, value ofs2, value len2,
                             value carry_in)
{
    ...
}

CAMLprim value add natbytecode(value * argv, int argn)
{
    return add natnative(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
    = "add nat bytecode" "add nat native"
```

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:

```c
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:

```c
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:
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.

### 20.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).

### 20.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.

### 20.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`.
<table><thead><tr><td>Include file</td><td>Provides</td></tr></thead><tbody><tr><td>caml/mlvalues.h</td><td>definition of the value type, and conversion macros</td></tr><tr><td>caml/alloc.h</td><td>allocation functions (to create structured OCaml objects)</td></tr><tr><td>caml/memory.h</td><td>miscellaneous memory-related functions and macros (for GC interface, in-place modification of structures, etc).</td></tr><tr><td>caml/fail.h</td><td>functions for raising exceptions (see section 22.4.7)</td></tr><tr><td>caml/callback.h</td><td>callback from C to OCaml (see section 22.7).</td></tr><tr><td>caml/custom.h</td><td>operations on custom blocks (see section 22.9).</td></tr><tr><td>caml/intext.h</td><td>operations for writing user-defined serialization and deserialization functions for custom blocks (see section 22.9).</td></tr><tr><td>caml/threads.h</td><td>operations for interfacing in the presence of multiple threads (see section 22.12).</td></tr></tbody></table>

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`).

### 22.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 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;

* the names of the desired OCaml object files (`.cmo` and `.cma` files);
`pwd` Print the working directory for ocamldebug.

### 20.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.

### 20.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`.

### 20.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.

### 20.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.
* 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:

```
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.

### 22.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). Finally (step 3), execute the `ocamlc` command with
20.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).

20.8.10 User-defined printers

Just as in the toplevel system (section 14.2), 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_printers "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_printers`. 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_printers *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
* 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`.

Do not set the `-custom` flag, otherwise you're back to static linking as described in section 22.1.3, The `ocamlmklib` tool (see section 22.14) 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.

### 22.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`.

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
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_printers*. It cannot reference the functions of the program being debugged.

`remove_printers printer-name`

Remove the named function from the table of value printers.

## 20.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*.

## 20.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.

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.
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) 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.

22.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).

22.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.
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.

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
### 22.2.1 Integer values

Integer values encode 63-bit signed integers (31-bit on 32-bit architectures). They are unboxed (unallocated).

### 22.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:

<table><thead><tr><td>Tag</td><td>Contents of the block</td></tr></thead><tbody><tr><td>0 to No_scan_tag - 1</td><td>A structured block (an array of OCaml objects). Each field is a value.</td></tr><tr><td>Closure_tag</td><td>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.</td></tr><tr><td>String_tag</td><td>A character string or a byte sequence.</td></tr><tr><td>Double_tag</td><td>A double-precision floating-point number.</td></tr><tr><td>Double_array_tag</td><td>An array or record of double-precision floating-point numbers.</td></tr><tr><td>Abstract_tag</td><td>A block representing an abstract datatype.</td></tr><tr><td>Custom_tag</td><td>A block representing an abstract datatype with user-defined finalization, comparison, hashing, serialization and deserialization functions attached.</td></tr></tbody></table>

### 22.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 gives a more complete example using `Custom_tag` blocks.

```c
/* Create an OCaml value encapsulating the pointer p */
static value val_ofTyptr(ty *p)
{
    value v = caml_alloc(1, Abstract_tag);
    *((ty **) Data GALVAL(v)) = p;
    return v;
}
```
```c
/* 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.

```c
/* Create an OCaml value encapsulating the pointer p */
static value val_ofTyptr(ty * p)
{
    return caml_copy_nativeint((intnat) p);
}
```

```c
/* Extract the pointer encapsulated in the given OCaml value */
static ty * typtr_of_val(value v)
{
    return (ty *) Nativeint_val(v);
}
```

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.

```c
/* Create an OCaml value encapsulating the pointer p */
static value val_ofTyptr(ty * p)
{
    assert (((基金管理器_t) p & 1) == 0); /* check correct alignment */
    return (value) p | 1;
}
```

```c
/* Extract the pointer encapsulated in the given OCaml value */
static ty * typtr_of_val(value v)
{
    return (ty *) (v & ~1);
}
```

## 22.3 Representation of OCaml data types

This section describes how OCaml data types are encoded in the *value type*.
Chapter 21

Profiling (ocamlprof, perf)

This chapter describes different ways to profile the execution of OCaml programs.

21.1 Profiling execution counts with ocamlprof

This section describes how the execution of OCaml programs can be profiled, by recording how
many times functions are called, and branches of conditionals are taken. This approach applies to
OCaml programs compiled with the bytecode and native backends.

21.1.1 Compiling for profiling

Before profiling an execution, the program must be compiled in profiling mode, using the ocamlc
front-end to the ocamlc compiler (see chapter 13) or the ocamloptp front-end to the ocamlopt
compiler (see chapter 16). When compiling modules separately, ocamlc 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
### 22.3.1 Atomic types

<table><thead><tr><td>OCaml type</td><td>Encoding</td></tr></thead><tbody><tr><td>int</td><td>Unboxed integer values.</td></tr><tr><td>char</td><td>Unboxed integer values (ASCII code).</td></tr><tr><td>float</td><td>Blocks with tag Double_tag.</td></tr><tr><td>bytes</td><td>Blocks with tag String_tag.</td></tr><tr><td>string</td><td>Blocks with tag String_tag.</td></tr><tr><td>int32</td><td>Blocks with tag Custom_tag.</td></tr><tr><td>int64</td><td>Blocks with tag Custom_tag.</td></tr><tr><td>nativeint</td><td>Blocks with tag Custom_tag.</td></tr></tbody></table>

### 22.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, unboxed record types are represented specially; unboxed record types are the immutable record types that have only one field. An unboxed 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.

### 22.3.3 Arrays

Arrays of integers and pointers are represented like tuples and records, that is, as pointers to blocks tagged 0. They are accessed with the `Field` macro for reading and the `caml_modify` function for writing.

Values of type `floatarray` (as manipulated by the `Float Array` module), as well as records whose declaration contains only float fields, use an efficient unboxed representation: blocks with tag `Double_array_tag` whose content consist of raw double values, which are not themselves valid OCaml values. They should be accessed using the `Double_flat_field` and `Store_double_flat_field` macros.

Finally, arrays of type `float array` may use either the boxed or the unboxed representation depending on the how the compiler is configured. They currently use the unboxed representation by default, but can be made to use the boxed representation by passing the `--disable-flat-float-array`
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 ocamlc -P film profiles function calls, if...then...else..., loops and pattern matching.

Calling ocamlc 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, ocamlc also accepts the -p option, with the same arguments and behaviour as -P.

The ocamlc and ocamloptp commands also accept all the options of the corresponding ocamlc or ocamlopt compiler, except the -pp (preprocessing) option.

### 21.1.2 Profiling an execution

Running an executable that has been compiled with ocamlc 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 ocamlc) are compatible with the dump files produced by native executables (compiled with ocamloptp).

### 21.1.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.
flag to the 'configure' script. They should be accessed using the `Double_array_field` and `Store_double_array_field` macros, which will work correctly under both modes.

### 22.3.4 Concrete data types

Constructed terms are represented either by unboxed integers (for constant constructors) or by blocks whose tag encode the constructor (for non-constant constructors). The constant constructors and the non-constant constructors for a given concrete type are numbered separately, starting from 0, in the order in which they appear in the concrete type declaration. A constant constructor is represented by the unboxed integer equal to its constructor number. A non-constant constructor declared with *n* arguments is represented by a block of size *n*, tagged with the constructor number; the *n* fields contain its arguments. Example:

<table><thead><tr><td>Constructed term</td><td>Representation</td></tr></thead><tbody><tr><td>()</td><td>Val_int(0)</td></tr><tr><td>false</td><td>Val_int(0)</td></tr><tr><td>true</td><td>Val_int(1)</td></tr><tr><td>[]</td><td>Val_int(0)</td></tr><tr><td>h::t</td><td>Block with size = 2 and tag = 0; first field contains h, second field t.</td></tr></tbody></table>

As a convenience, `caml/mlvalues.h` defines the macros `Val_unit`, `Val_false` and `Val_true` to refer to `()`, `false` and `true`.

The following example illustrates the assignment of integers and block tags to constructors:

```c
type t =
  | A          (* First constant constructor -> integer "Val_int(0)" *)
  | B of string (* First non-constant constructor -> block with tag 0 *)
  | C          (* Second constant constructor -> integer "Val_int(1)" *)
  | D of bool   (* Second non-constant constructor -> block with tag 1 *)
  | E of t * t  (* Third non-constant constructor -> block with tag 2 *)
```

As an optimization, unboxed concrete data types are represented specially; a concrete data type is unboxed if it has exactly one constructor and this constructor has exactly one argument. Unboxed concrete data types are represented in the same ways as unboxed record types: see the description in section 22.3.2.

### 22.3.5 Objects

Objects are represented as blocks with tag `Object_tag`. The first field of the block refers to the object's class and associated method suite, in a format that cannot easily be exploited from C. The second field contains a unique object ID, used for comparisons. The remaining fields of the object contain the values of the instance variables of the object. It is unsafe to access directly instance variables, as the type system provides no guarantee about the instance variables contained by an object.

One may extract a public method from an object using the C function `caml_get_public_method` (declared in `<caml/mlvalues.h>`) . Since public method tags are hashed in the same way as variant
-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`.

-keywords version+list

Set keywords according to the *version+list* specification.

-version

Print version string and exit.

-vnum

Print short version number and exit.

-help or --help

Display a short usage summary and exit.

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`.

## 21.2 Time profiling with Linux perf

This section describes how to use `perf` to profile OCaml programs. Linux Performance Events (aka `perf`) is a suite of tools for performance observability included with the Linux kernel. The main features covered here are recording events using `perf-record(1)`, and visualising recorded events using `perf-report(1)`. `perf` has many additional profiling and visualising features, for more comprehensive documentation, see (man `perf(1)`, `perf wiki` or Brendan Gregg's Blog).

### 21.2.1 Background

Time profiling is typically performed by sampling the CPU call graph at frequent intervals to gather statistics on the code paths that are consuming CPU resources. To profile OCaml code, `perf` needs to understand the call graph of an OCaml program. `perf` supports multiple options for recording call graphs:

* Frame Pointers, which is the default.

* DWARF's Call Frame Information (CFI).
tags, and methods are functions taking self as first argument, if you want to do the method call `foo#bar` from the C side, you should call:

```c
callback.caml_get_public_method(foo, hash("bar")), foo);
```

### 22.3.6 Polymorphic variants

Like constructed terms, polymorphic variant values are represented either as integers (for polymorphic variants without argument), or as blocks (for polymorphic variants with an argument). Unlike constructed terms, variant constructors are not numbered starting from 0, but identified by a hash value (an OCaml integer), as computed by the C function `hash` (declared in `<caml/mlvalues.h>`): the hash value for a variant constructor named, say, `VConstr` is `hasheprofile("VConstr")`.

The variant value `VConstr` is represented by `hasheprofile("VConstr")`. The variant value `VConstr(v)` is represented by a block of size 2 and tag 0, with field number 0 containing `hasheprofile("VConstr")` and field number 1 containing `v`.

Unlike constructed values, polymorphic variant values taking several arguments are not flattened. That is, `VConstr(v, w)` is represented by a block of size 2, whose field number 1 contains the representation of the pair `(v, w)`, rather than a block of size 3 containing `v` and `w` in fields 1 and 2.

## 22.4 Operations on values

### 22.4.1 Kind tests

* `Is_long(v)` is true if value `v` is an immediate integer, false otherwise

* `Is_block(v)` is true if value `v` is a pointer to a block, and false if it is an immediate integer.

* `Is_none(v)` is true if value `v` is `None`.

* `Is_some(v)` is true if value `v` (assumed to be of option type) corresponds to the Some constructor.

### 22.4.2 Operations on integers

* `Val_long(l)` returns the value encoding the `long int l`.

* `Long_val(v)` returns the `long int` encoded in value `v`.

* `Val_int(i)` returns the value encoding the `int i`.

* `Int_val(v)` returns the `int` encoded in value `v`.

* `Val_bool(x)` returns the OCaml boolean representing the truth value of the C integer `x`.

* `Bool_val(v)` returns 0 if `v` is the OCaml boolean `false`, 1 if `v` is `true`.

* `Val_true`, `Val_false` represent the OCaml booleans `true` and `false`.

* `Val_none` represents the OCaml value `None`.
* Hardware Last Branch Record (LBR).

Frame pointer based call graphs use a convention where a register called the frame pointer holds the address for the beginning of the stack frame, and the previous values for the frame pointer are stored at a known offset from the current frame pointer. Using this information the call graph for the current function can be calculated purely based on the current stack, a process called unwinding. On x86_64 the register used for storing the frame pointer is $rbp, while ARM64 uses the register x29. OCaml 5 introduced non-contiguous stacks as part of the implementation of effects, see *Retrofitting effect handlers onto OCaml* (Section 5.5). Due to this implementation detail, frame pointers work better with the copying nature of perf.

DWARF based call graphs use the DWARF CFI information to perform unwinding. However this interacts poorly with the copying nature of perf, often leading to truncated call graphs where not enough of the stack has been copied by *perf*. It also produces larger trace files that are more costly to capture and process. Finally it requires including CFI debugging information in your program resulting in slightly larger binaries.

Hardware Last Branch Record (LBR) uses a processor provided method to record call graphs. This has the limitations of restricted availability (only on certain Intel CPUs) and a limited stack depth (16 on Haswell and 32 since Skylake).

Of these options, frame pointers are recommended for profiling OCaml code. It has the following advantages:

* Unwinding is faster to calculate.

* Tracing data produced is smaller.

* Frame pointers provide more complete call graphs, particularly when used with a Linux distribution that supports them.

* Frame pointers work better with *perf*'s copying nature and OCaml 5's non-contiguous stacks.

### 21.2.2 Compiling for Profiling

The process for compiling an executable for time profiling depends on the OCaml version. For OCaml versions 4.14 and earlier, either frame pointers or DWARF can be used, while for OCaml 5.0 and later, enabling frame pointers is recommended.

To enable frame pointers, configure the compiler with `--enable-frame-pointers`. Alternatively, you can install an opam switch with frame pointers enabled, as follows:

```
opam switch create <YOUR-SWITCH-NAME-HERE> ocaml-option-fp
```

Frame pointer support for OCaml is available on x86_64 architecture for Linux starting with OCaml 4.12 and on macOS from OCaml 5.3. ARM64 architecture is supported on Linux and macOS from OCaml 5.4, while other Tier-1 architectures (POWER, RISC-V, and s390x) are currently unsupported.
### 22.4.3 Accessing blocks

* `Wosize_val(v)` returns the size of the block `v`, in words, excluding the header.

* `Tag_val(v)` returns the tag of the block `v`.

* `Field(v, n)` returns the value contained in the $n$-bit field of the structured block `v`. Fields are numbered from 0 to `Wosize_val(v) - 1`.

* `Store_field(b, n, v)` stores the value `v` in the field number `n` of value `b`, which must be a structured block.

* `Code_val(v)` returns the code part of the closure `v`.

* `caml_string_length(v)` returns the length (number of bytes) of the string or byte sequence `v`.

* `Byte(v, n)` returns the $n$-bit byte of the string or byte sequence `v`, with type `char`. Bytes are numbered from 0 to `string_length(v) - 1`.

* `Byte_u(v, n)` returns the $n$-bit byte of the string or byte sequence `v`, with type `unsigned char`. Bytes are numbered from 0 to `string_length(v) - 1`.

* `String_val(v)` returns a pointer to the first byte of the string `v`, with type `const char *`. This pointer is a valid C string: there is a null byte after the last byte in the string. However, OCaml strings can contain embedded null bytes, which will confuse the usual C functions over strings.

* `Bytes_val(v)` returns a pointer to the first byte of the byte sequence `v`, with type `unsigned char *`.

* `Double_val(v)` returns the floating-point number contained in value `v`, with type `double`.

* `Double_array_field(v, n)` returns the $n$-bit element of a `float` array `v`.

* `Store_double_array_field(v, n, d)` stores the double precision floating-point number `d` in the $n$-bit element of a `float` array `v`.

* `Double_flat_field(v, n)` returns the $n$-bit element of a `float` array or a record of floats `v` (an unboxed block tagged `Double_array_tag`).

* `Store_double_flat_field(v, n, d)` stores the double precision floating-point number `d` in the $n$-bit element of a `float` array or a record of floats `v`.

* `Data_custom_val(v)` returns a pointer to the data part of the custom block `v`. This pointer has type `void *` and must be cast to the type of the data contained in the custom block.

* `Int32_val(v)` returns the 32-bit integer contained in the `int32 v`.

* `Int64_val(v)` returns the 64-bit integer contained in the `int64 v`.

* `Nativeint_val(v)` returns the long integer contained in the `nativeint v`.
### 21.2.3 Profiling an Execution

The basic `perf` command for profiling is:

```
perf record -F 99 --call-graph fp PROGRAM
```

The `-F 99` option sets `perf` to sample at 99Hz, reducing excessive data generation during longer runs and minimising overlap with other periodic activities. The `--call-graph fp` instructs `perf` to use frame pointers to get the call graph, followed by the OCaml executable you want to profile. This command creates a `perf.data` file in the current directory. Alternatively use `--output` to choose a more descriptive filename.

The `perf record` command works by copying a segment of the call stack at each sample and recording this data into a `perf.data` file. These samples can then be processed after recording using `perf report` to reconstruct the profiled program's call stack at every sample.

`perf` uses the symbols present in an OCaml executable, so it helps to understand OCaml's name mangling scheme to map names to OCaml source locations. OCaml 5.4 onwards uses a name mangling scheme of `caml<MODULE_NAME>$$<FUNCTION_NAME>_<NNN>`, where NNN is a randomly generated number. In OCaml 5.3 the separator is a dot `caml<MODULE_NAME>.<FUNCTION_NAME>_<NNN>`, and before OCaml 5.1 the separator is double underscores. All formats are supported by `perf`.

Consider the following program:

``` Ocaml
(* fib.ml *)
module Compute = struct
  let rec fib n =
    if n = 0 then 0
  else if n = 1 then 1
  else fib (n-1) + fib (n-2)
end

let main () =
  let r = Compute.fib 20 in
  Printfprintf "fib(20) = %d" r

let _ = main ()
```

This program produces the names `camlFib$main_274` for the `main` function and `camlFib$fib_271` for the `fib` function in the `Compute` module.

### 21.2.4 Displaying profiling information

The `perf report` command summarises data in the `perf.data` file. The basic `perf report` command is:

```
perf report -f --no-children -i perf.data
```

This command provides an interactive interface where you can navigate through the accumulated call graphs and select functions and threads for detailed information. Alternatively `--stdio` will
* `caml_field_unboxed(v)` returns the value of the field of a value `v` of any unboxed type (record or concrete data type).

* `caml_field_boxed(v)` returns the value of the field of a value `v` of any boxed type (record or concrete data type).

* `caml_field_unboxed(v)` calls either `caml_field_unboxed` or `caml_field_boxed` according to the default representation of unboxed types in the current version of OCaml.

* `Some_val(v)` returns the argument `\var{x}` of a value `v` of the form `Some(x)`.

The expressions `Field(v, n)`, `Byte(v, n)` and `Byte_u(v, n)` are valid l-values. Hence, they can be assigned to, resulting in an in-place modification of value `v`. Assigning directly to `Field(v, n)` must be done with care to avoid confusing the garbage collector (see below).

### 22.4.4 Allocating blocks

### 22.4.5 Simple interface

* `Atom(t)` returns an "atom" (zero-sized block) with tag `t`. Zero-sized blocks are preallocated outside of the heap. It is incorrect to try and allocate a zero-sized block using the functions below. For instance, `Atom(0)` represents the empty array.

* `caml_alloc(n, t)` returns a fresh block of size `n` with tag `t`. If `t` is less than `No_scan_tag`, then the fields of the block are initialized with a valid value in order to satisfy the GC constraints.

* `caml_alloc_tuple(n)` returns a fresh block of size `n` words, with tag 0.

* `caml_alloc_string(n)` returns a byte sequence (or string) value of length `n` bytes. The sequence initially contains uninitialized bytes.

* `caml_alloc_initialize_string(n, p)` returns a byte sequence (or string) value of length `n` bytes. The value is initialized from the `n` bytes starting at address `p`.

* `caml_copy_string(s)` returns a string or byte sequence value containing a copy of the null-terminated C string `s` (a `char *`).

* `caml_copy_double(d)` returns a floating-point value initialized with the double `d`.

* `caml_copy_int32(i)`, `caml_copy_int64(i)` and `caml_copy_nativeint(i)` return a value of OCaml type `int32`, `int64` and `nativeint`, respectively, initialized with the integer `i`.

* `caml_alloc_array(f, a)` allocates an array of values, calling function `f` over each element of the input array `a` to transform it into a value. The array `a` is an array of pointers terminated by the null pointer. The function `f` receives each pointer as argument, and returns a value. The zero-tagged block returned by `alloc_array(f, a)` is filled with the values returned by the successive calls to `f`. (This function must not be used to build an array of floating-point numbers.)

* `caml_copy_string_array(p)` allocates an array of strings or byte sequences, copied from the pointer to a string array `p` (a `char **`). `p` must be NULL-terminated.
output similar data using a text based report written to stdout. Note that if stack traces appear broken, it may be due to software not having frame pointer support enabled.

Consider the following program which calculates the Tak function.

```hml
let (x,y,z) =
  try
    let x = int_of_string Sys.argv.(1) in
    let y = int_of_string Sys.argv.(2) in
    let z = int_of_string Sys.argv.(3) in
    (x,y,z)
  with _ -> (18,12,6)
```

```hml
let rec tak x y z =
  if x > y then
    tak (tak (x-1) y z) (tak (y-1) z x) (tak (z-1) x y)
  else z
```

```hml
let main () =
  let r = tak x y z in
  Printf printf "tak %d %d %d = %d\n" x y z r
```

```hml
let _ = main ()
```
The perf report for this might resemble the following.

```
Samples: 809 of event 'cycles', Event count (approx.): 24701952617
Overhead Command      Shared Object      Symbol
- 100.00% tak-fp.exe   tak-fp.exe         [.] Tak\$tak_402
    Tak\$tak_402
    Tak\$tak_402
+ Tak\$tak_402
    0.00% tak-fp.exe   [kernel.kallsyms]  [k] 0xffffffffa5ff79d854
    0.00% perf-exec    [kernel.kallsyms]  [k] 0xffffffffa5ff719c34
```

For a more interesting program implementing a Sudoku solver using Norvig's Backtracking algorithm, the output might resemble.

```
Samples: 7K of event 'cycles:P', Event count (approx.): 141874642467
Overhead Command      Shared Object      Symbol
- 35.90% sudoku_norvig.e sudoku_norvig.exe  [.] Sudoku_norvig._pow_747
    - 35.29% Sudoku_norvig$\_pow_747
        + 17.70% Sudoku_norvig$eliminate_value_760
        + 15.74% Sudoku_norvig$\_pow_747
        + 1.03% Sudoku_norvig$fun_1435
    0.61% Sudoku_norvig$eliminate_value_760
- 12.99% sudoku_norvig.e sudoku_norvig.exe  [.] BatList$findnext_1543
    - 12.00% BatList$findnext_1543
        - 11.71% BatList$find_all_1539
```
* `caml_alloc_float_array(n)` allocates an array of floating point numbers of size `n`. The array initially contains uninitialized values.

* `caml_alloc_unboxed(v)` returns the value (of any unboxed type) whose field is the value `v`.

* `caml_alloc_boxed(v)` allocates and returns a value (of any boxed type) whose field is the value `v`.

* `caml_alloc_unboxed(v)` calls either `caml_alloc_unboxed` or `caml_alloc_boxed` according to the default representation of unboxed types in the current version of OCaml.

* `caml_alloc_some(v)` allocates a block representing `Some(v)`.

### 22.4.6 Low-level interface

The following functions are slightly more efficient than `caml_alloc`, but also much more difficult to use.

From the standpoint of the allocation functions, blocks are divided according to their size as zero-sized blocks, small blocks (with size less than or equal to `Max_young_wosize`), and large blocks (with size greater than `Max_young_wosize`). The constant `Max_young_wosize` is declared in the include file `mlvalues.h`. It is guaranteed to be at least 64 (words), so that any block with constant size less than or equal to 64 can be assumed to be small. For blocks whose size is computed at run-time, the size must be compared against `Max_young_wosize` to determine the correct allocation procedure.

* `caml_alloc_small(n, t)` returns a fresh small block of size $n \le \text{Max_young_wosize}$ words, with tag `t`. If this block is a structured block (i.e. if $t < \text{No_scan_tag}$), then the fields of the block (initially containing garbage) must be initialized with legal values (using direct assignment to the fields of the block) before the next allocation.

* `caml_alloc_shr(n, t)` returns a fresh block of size `n`, with tag `t`. The size of the block can be greater than `Max_young_wosize`. (It can also be smaller, but in this case it is more efficient to call `caml_alloc_small` instead of `caml_alloc_shr`.) If this block is a structured block (i.e. if $t < \text{No_scan_tag}$), then the fields of the block (initially containing garbage) must be initialized with legal values (using the `caml_initialize` function described below) before the next allocation.

### 22.4.7 Raising exceptions

Two functions are provided to raise two standard exceptions:

* `caml_failwith(s)`, where `s` is a null-terminated C string (with type `char *`), raises exception `Failure` with argument `s`.

* `caml_INVALID_argument(s)`, where `s` is a null-terminated C string (with type `char *`), raises exception `Invalid_argument` with argument `s`.
```
+ 8.07% Sudoku_norvig$fun_1421
+ 2.73% Sudoku_norvig$eliminate_948
+ 0.90% Sudoku_norvig$assign_949
- 10.63% sudoku_norvig.e sudoku_norvig.exe [.] Sudoku_norvig$eliminate_value_760
+ 8.29% Sudoku_norvig$eliminate_value_760
+ 1.93% Sudoku_norvig$pow_747
+ 9.50% sudoku_norvig.e [kernel.kallsyms] [k] asm_exc_nmi
+ 7.24% sudoku_norvig.e sudoku_norvig.exe [.] Sudoku_norvig$fun_1435
+ 5.06% sudoku_norvig.e sudoku_norvig.exe [.] caml_modify
+ 3.10% sudoku_norvig.e sudoku_norvig.exe [.] Sudoku_norvig$fun_1360
+ 2.11% sudoku_norvig.e sudoku_norvig.exe [.] Sudoku_norvig$eliminate_948
+ 2.00% sudoku_norvig.e sudoku_norvig.exe [.] Stdlib.List$iter_366
+ 1.54% sudoku_norvig.e sudoku_norvig.exe [.] Sudoku_norvig$fun_1421
+ 1.47% sudoku_norvig.e sudoku_norvig.exe [.] caml_apply2
+ 1.42% sudoku_norvig.e sudoku_norvig.exe [.] BatList$find_all_1539
+ 1.20% sudoku_norvig.e sudoku_norvig.exe [.] Sudoku_norvig$fun_1366
+ 1.09% sudoku_norvig.e sudoku_norvig.exe [.] Stdlib.List$fold_left_380
```

Note this implementation clearly has some optimisation possible in `__pow_747` a recursive Power of 2 function, and parts of the OCaml runtime `caml_modify` are present.

Profiling data can also be visualised as Flame Graphs, which highlight the most frequent code paths in stack traces. The original scripts `stackcollapse-perf.pl` and `flamegraph.pl` can be found at Brendan Gregg's Flame Graphs web page and work as follows:

```
git clone https://github.com/brendangregg/FlameGraph
cd FlameGraph
```

```
# Collect the results into perf.data
perf record -F 99 --call-graph fp PROGRAM
perf script -i perf.data | ./stackcollapse-perf.pl out.folded
flamegraph.pl out.folded > flamegraph.svg ## Create the FlameGraphsvg
```

Alternatively `inferno` is a Rust port of the Flame Graphs tools which works in a similar way and is faster to process large perf files.

```
cargo install inferno
```

```
# Collect the results into perf.data
perf script -i perf.data | inferno-collapse-perf > stacks.folded
cat stacks.folded | inferno-flamegraph > flamegraph.svg
```

Some `perf` tools (e.g., `perf-report(1)` and `perf-annotate(1)`) use DWARF debugging information to associate symbols with source code locations, if you need these features, the program and its dependencies need to be compiled with `-g` to include debugging information in the executable.

Captured profile data can also be processed using `perf script` in various ways or with online tools like `speedscope.app` and `profiler.firefox.com`, or any other tool that supports `perf-formatted` data.
Raising arbitrary exceptions from C is more delicate: the exception identifier is dynamically
allocated by the OCaml program, and therefore must be communicated to the C function using the
registration facility described below in section 22.7.3. Once the exception identifier is recovered in
C, the following functions actually raise the exception:

* `caml_Raiseconstant(id)` raises the exception `id` with no argument;

* `caml_Raise_with_argv(id, v)` raises the exception `id` with the OCaml value `v` as argument;

* `caml_Raise_with_args(id, n, v)` raises the exception `id` with the OCaml values `v[0], ..., v[n-1]` as arguments;

* `caml_Raise_with_string(id, s)`, where `s` is a null-terminated C string, raises the exception `id` with a copy of the C string `s` as argument.

## 22.5 Living in harmony with the garbage collector

Unused blocks in the heap are automatically reclaimed by the garbage collector. This requires some
cooperation from C code that manipulates heap-allocated blocks.

### 22.5.1 Simple interface

All the macros described in this section are declared in the `memory.h` header file.

**Rule 1** A function that has parameters or local variables of type value must begin with a call to one of the `CAMLparam` macros and return with `CAMLreturn`, `CAMLreturn0`, or `CAMLreturnT`.

There are six `CAMLparam` macros: `CAMLparam0` to `CAMLparam5`, which take zero to five arguments respectively. If your function has no more than 5 parameters of type `value`, use the corresponding macros with these parameters as arguments. If your function has more than 5 parameters of type `value`, use `CAMLparam5` with five of these parameters, and use one or more calls to the `CAMLxparam` macros for the remaining parameters (`CAMLxparam1` to `CAMLxparam5`).

The macros `CAMLreturn`, `CAMLreturn0`, and `CAMLreturnT` are used to replace the C keyword `return`; any function using a `CAMLparam` macro on entry should use `CAMLreturn` on all exit points. C functions exported as OCaml externals must return a `value`, and they should use `CAMLreturn` (`x`) instead of `return x`. Some helper functions may manipulate OCaml values yet return `void` or another datatype. `void`-returning procedures should explicitly use `CAMLreturn0`, and not have any implicit return. Helper functions returning C data of some type `t` should use `CAMLreturnT` (`t`, `x`) instead of `return x`.

**Note:** Some C compilers give bogus warnings about unused variables `caml__dummy_xxx` at each use of `CAMLparam` and `CAMLlocal`. You should ignore them.
### 21.2.5 Conclusion

For Time profiling of native code, standard tools such as `perf`, eBPF, DTrace, or Instruments (on macOS) are recommended. Compiling with frame pointers enabled is often necessary for these tools to work effectively. Profiling with `gprof` is no longer supported.

Enabling frame pointers can impact performance on certain architectures (up to 10% performance cost on x86_64 has been measured). Users of this feature are encouraged to benchmark their own applications to assess this impact.

## 21.3 Time profiling with macOS Instruments

Instruments is an application performance analyzer and visualizer provided in XCode on macOS. It includes a CLI tool `xctrace` that can capture Time Profiling information about OCaml programs, there is also a GUI application for running and visualising profiles. Here we only cover capturing time profiles with `xctrace`, for more information on Instruments consult Apple's documentation.

The same prerequisites hold for Time profiling with macOS Instruments as for Linux `perf`, consult `Background` (21.2.1) from the previous section for an explanation of call graphs and follow the setup from `Compiling for Profiling` (21.2.2).

The basic `xctrace` command for time profiling is:

```
$ xcrun xctrace record --output . --template "Time Profiler" \
    --target-stdout - --launch -- PROGRAM
```

The `--template Time Profiler` selects pre-defined template for time profiling which will create a trace file with extension `.trace` that can be opened with Instruments. Use the `--output` to select a name for the trace file, by default `xctrace` will create a new file each run rather than overwriting the existing file.

The resulting file can be opened with Instruments to view the profile, and it may be possible to generate Flame Graphs using `inferno` or the scripts from https://github.com/brendangregg/FlameGraph.

**Note** Sometimes Instruments requires adding entitlements to an OCaml binary before it is able to profile it. This typically shows as a failure to launch the process or as a permission error. To work around this issue run the following command, replacing 'PROGRAM' with the program to trace.

```
$ codesign -s - -v -f --entitlements =(echo -n '<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "https://www.apple.com/DTDs/PropertyList-1.0.dtd"/> <plist version="1.0"> <dict> <key>com.apple.security.get-task-allow</key> <true/> </dict> </plist> ') PROGRAM
```

For more details on entitlements and codesigning consult Apple's documentation.
Examples:

``` OCaml
CAMLprim value my_external (value v1, value v2, value v3)
{
  CAMLparam3 (v1, v2, v3);
  ...
  CAMLreturn (Val_unit);
}
```

``` OCaml
static void helper_procedure (value v1, value v2)
{
  CAMLparam2 (v1, v2);
  ...
  CAMLreturn0;
}
```

``` OCaml
static int helper_function (value v1, value v2)
{
  CAMLparam2 (v1, v2);
  ...
  CAMLreturnT (int, 0);
}
```

**Note:** If your function is a primitive with more than 5 arguments for use with the byte-code runtime, its arguments are not *values* and must not be declared (they have types `value *` and `int`).

**Warning:** `CAMLreturn0` should only be used for internal procedures that return `void`. `CAMLreturn (Val_unit)` should be used for functions that return an OCaml unit value. Primitives (C functions that can be called from OCaml) should never return `void`.

**Rule 2** *Local variables of type value must be declared with one of the CAMLlocal macros. Arrays of values are declared with CAMLlocalN. These macros must be used at the beginning of the function, not in a nested block.*

The macros `CAMLlocal1` to `CAMLlocal5` declare and initialize one to five local variables of type `value`. The variable names are given as arguments to the macros. `CAMLlocalN(x, n)` declares and initializes a local variable of type `value` `[n]`. You can use several calls to these macros if you have more than 5 local variables.

Example:

``` OCaml
CAMLprim value bar (value v1, value v2, value v3)
{
  CAMLparam3 (v1, v2, v3);
  CAMLlocal1 (result);
}
```
**21.4 Glossary**

The following terminology is used in this chapter of the manual.

**Call graph** The chain of function calls that have lead to the current function (also referred to as a call stack).

**Unwinding** The process of walking up the call stack (also called stack unwinding).

**Stack frame** Refers to the portion of the stack allocated to a single function call. (also called an activation frame, activation record or simply frame).
```c
result = caml_alloc (3, 0);
...
CAMLreturn (result);
}
```

**Warning:** `CAMLlocal` (and `CAMLxparam`) can only be called *after* `CAMLparam`. If a function declares local values but takes no value argument, it should start with `CAMLparam0()`.

```c
static value foo (int n)
{
    CAMLparam0 ();;
    CAMLlocal (result);
    ...
    CAMLreturn (result);
}
```

**Rule 3** Assignments to the fields of structured blocks must be done with the `Store_field` macro (for normal blocks), `Store_double_array_field` macro (for float array values) or `Store_double_flat_field` (for floatarray values and records of floating-point numbers). Other assignments must not use `Store_field`, `Store_double_array_field` nor `Store_double_flat_field`.

`Store_field` (`b`, `n`, `v`) stores the value `v` in the field number `n` of value `b`, which must be a block (i.e. `Is_block(b)` must be true).

Example:

```c
CAMLprim value bar (value v1, value v2, value v3)
{
    CAMLparam3 (v1, v2, v3);
    CAMLlocal1 (result);
    result = caml_alloc (3, 0);
    Store_field (result, 0, v1);
    Store_field (result, 1, v2);
    Store_field (result, 2, v3);
    CAMLreturn (result);
}
```

**Warning:** The first argument of `Store_field` and `Store_double_field` must be a variable declared by `CAMLparam*` or a parameter declared by `CAMLlocal*` to ensure that a garbage collection triggered by the evaluation of the other arguments will not invalidate the first argument after it is computed.

**Use with CAMLlocalN:** Arrays of values declared using `CAMLlocalN` must not be written to using `Store_field`. Use the normal C array syntax instead.
**Rule 4** Global variables containing values must be registered with the garbage collector using the `caml_register_global_root` function, save that global variables and locations that will only ever contain OCaml integers (and never pointers) do not have to be registered.

The same is true for any memory location outside the OCaml heap that contains a value and is not guaranteed to be reachable—for as long as it contains such value—from either another registered global variable or location, local variable declared with `CAMLlocal` or function parameter declared with `CAMLparam`.

Registration of a global variable `v` is achieved by calling `caml_register_global_root(&v)` just before or just after a valid value is stored in `v` for the first time; likewise, registration of an arbitrary location `p` is achieved by calling `caml_register_global_root(p)`.

You must not call any of the OCaml runtime functions or macros between registering and storing the value. Neither must you store anything in the variable `v` (likewise, the location `p`) that is not a valid value.

The registration causes the contents of the variable or memory location to be updated by the garbage collector whenever the value in such variable or location is moved within the OCaml heap. In the presence of threads care must be taken to ensure appropriate synchronisation with the OCaml runtime to avoid a race condition against the garbage collector when reading or writing the value. (See section 22.12.2.)

A registered global variable `v` can be un-registered by calling `caml_remove_global_root(&v)`.

If the contents of the global variable `v` are seldom modified after registration, better performance can be achieved by calling `caml_register_generational_global_root(&v)` to register `v` (after its initialization with a valid value, but before any allocation or call to the GC functions), and `caml_remove_generational_global_root(&v)` to un-register it. In this case, you must not modify the value of `v` directly, but you must use `caml_modify_generational_global_root(&v, x)` to set it to `x`. The garbage collector takes advantage of the guarantee that `v` is not modified between calls to `caml_modify_generational_global_root` to scan it less often. This improves performance if the modifications of `v` happen less often than minor collections.

**Note:** The `CAML` macros use identifiers (local variables, type identifiers, structure tags) that start with `caml_`. Do not use any identifier starting with `caml_` in your programs.

### 22.5.2 Low-level interface

We now give the GC rules corresponding to the low-level allocation functions `caml_alloc_small` and `caml_alloc_shr`. You can ignore those rules if you stick to the simplified allocation function `caml_alloc`.

**Rule 5** After a structured block (a block with tag less than `No_scan_tag`) is allocated with the low-level functions, all fields of this block must be filled with well-formed values before the next allocation operation. If the block has been allocated with `caml_alloc_small`, filling is performed by direct assignment to the fields of the block:

```
Field(v, n) = v_n;
```

If the block has been allocated with `caml_alloc_shr`, filling is performed through the `caml_initialize` function:
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.

22.1 Overview and compilation information

22.1.1 Declaring primitives

definition ::= ...
               | external value-name : typexpr = external-declaration

external-declaration ::= string-literal [string-literal [string-literal]]

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

`val name : type`

thus hiding their implementation as C functions, or explicitly as "manifest" external functions

`external name : type = C-function-name`
```c
    caml_initialize(&Field(v, n), v_n);
```

The next allocation can trigger a garbage collection. The garbage collector assumes that all structured blocks contain well-formed values. Newly created blocks contain random data, which generally do not represent well-formed values.

If you really need to allocate before the fields can receive their final value, first initialize with a constant value (e.g. `Val_unit`), then allocate, then modify the fields with the correct value (see rule 6).

**Rule 6** Direct assignment to a field of a block, as in

```c
    Field(v, n) = w;
```

is safe only if `v` is a block newly allocated by `caml_alloc_small`; that is, if no allocation took place between the allocation of `v` and the assignment to the field. In all other cases, never assign directly. If the block has just been allocated by `caml_alloc_shr`, use `caml_initialize` to assign a value to a field for the first time:

```c
    caml_initialize(&Field(v, n), w);
```

Otherwise, you are updating a field that previously contained a well-formed value; then, call the `caml_modify` function:

```c
    caml_modify(&Field(v, n), w);
```

To illustrate the rules above, here is a C function that builds and returns a list containing the two integers given as parameters. First, we write it using the simplified allocation functions:

```c
value alloc_list_int(int i1, int i2)
{
    CAMLparam0 ();
    CAMLlocal2 (result, r);

    r = caml_alloc(2, 0);          /* Allocate a cons cell */
    Store_field(r, 0, Val_int(i2));  /* car = the integer i2 */
    Store_field(r, 1, Val_int(0));  /* cdr = the empty list [] */
    result = caml_alloc(2, 0);      /* Allocate the other cons cell */
    Store_field(result, 0, Val_int(i1)); /* car = the integer i1 */
    Store_field(result, 1, r);       /* cdr = the first cons cell */
    CAMLreturn (result);
}
```

Here, the registering of `result` is not strictly needed, because no allocation takes place after it gets its value, but it's easier and safer to simply register all the local variables that have type `value`.

Here is the same function written using the low-level allocation functions. We notice that the cons cells are small blocks and can be allocated with `caml_alloc_small`, and filled by direct assignments on their fields.
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_m1_seek_in` C function is called with two arguments. Similarly,

```c
external seek_in_pair: in_channel * int -> unit = "caml_m1_seek_in_pair"
```

has arity 1, and the `caml_m1_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,

```c
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.

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.

### 22.1.2 Implementing primitives

User primitives with arity $n \le 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:

```c
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`:
``` OCaml
value alloc_list_int(int i1, int i2)
{
    CAMLparam0 ();
    CAMLlocal2 (result, r);

    r = caml_alloc_small(2, 0);          /* Allocate a cons cell */
    Field(r, 0) = Val_int(i2);            /* car = the integer i2 */
    Field(r, 1) = Val_int(0);            /* cdr = the empty list [] */
    result = caml_alloc_small(2, 0);     /* Allocate the other cons cell */
    Field(result, 0) = Val_int(i1);       /* car = the integer i1 */
    Field(result, 1) = r;                /* cdr = the first cons cell */
    CAMLreturn (result);
}
```

In the two examples above, the list is built bottom-up. Here is an alternate way, that proceeds top-down. It is less efficient, but illustrates the use of `caml_modify`.

``` OCaml
value alloc_list_int(int i1, int i2)
{
    CAMLparam0 ();
    CAMLlocal2 (tail, r);

    r = caml_alloc_small(2, 0);          /* Allocate a cons cell */
    Field(r, 0) = Val_int(i1);            /* car = the integer i1 */
    Field(r, 1) = Val_int(0);            /* A dummy value */
    tail = caml_alloc_small(2, 0);       /* Allocate the other cons cell */
    Field(tail, 0) = Val_int(i2);         /* car = the integer i2 */
    Field(tail, 1) = Val_int(0);          /* cdr = the empty list [] */
    caml_modify(&Field(r, 1), tail);    /* cdr of the result = tail */
    CAMLreturn (r);
}
```

It would be incorrect to perform `Field(r, 1) = tail` directly, because the allocation of `tail` has taken place since `r` was allocated.

### 22.5.3 Pending actions and asynchronous exceptions

Since 4.10, allocation functions are guaranteed not to call any OCaml callbacks from C, including finalisers and signal handlers, and delay their execution instead.

The function `caml_process_pendingActions` from `<caml/signals.h>` executes any pending signal handlers and finalisers, Memprof callbacks, and requested minor and major garbage collections. In particular, it can raise asynchronous exceptions. It is recommended to call it regularly at safe points inside long-running non-blocking C code.

The variant `caml_process_pendingActions_exn` is provided, that returns the exception instead of raising it directly into OCaml code. Its result must be tested using `Is_exception_result`, and followed by `Extract_exception` if appropriate. It is typically used for clean up before re-raising:
```c
CAMLprim value add_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
    = "add nat bytecode" "add nat native"
```

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:

```c
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:

```c
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:
```c
CAMLlocal1(exn);
...
exn = caml_process_pendingActions_exn();
if (Is_exception_result(exn)) {
    exn = Extract_exception(exn);
    ...cleanup...
    camlítent(exn);
}
```

Correct use of exceptional return, in particular in the presence of garbage collection, is further
detailed in Section 22.7.1.

## 22.6 A complete example

This section outlines how the functions from the Unix curses library can be made available to
OCaml programs. First of all, here is the interface curses.ml that declares the curses primitives
and data types:

```c
(* File curses.ml -- declaration of primitives and data types *)
type window              (* The type "window" remains abstract *)
external initscr: unit -> window = "caml_curses_initscr"
external endwin: unit -> unit = "caml_curses_endwin"
external refresh: unit -> unit = "caml_curses_refresh"
external wrefresh : window -> unit = "caml_curses_wrefresh"
external newwin: int -> int -> int -> int -> window = "caml_curses_newwin"
external addch: char -> unit = "caml_curses_addch"
external mvwaddch: window -> int -> int -> char -> unit = "caml_curses_mvwaddch"
external addstr: string -> unit = "caml_curses_addstr"
external mvwaddstr: window -> int -> int -> string -> unit
    = "caml_curses_mvwaddstr"
(* lots more omitted *)
```

To compile this interface:

```
ocamlc -c curses.ml
```

To implement these functions, we just have to provide the stub code; the core functions are
already implemented in the curses library. The stub code file, curses_stubs.c, looks like this:

```c
/* File curses_stubs.c -- stub code for curses */
#include <curses.h>
#include <caml/mlvalues.h>
#include <caml/memory.h>
#include <caml/alloc.h>
#include <caml/custom.h>

/* Encapsulation of opaque window handles (of type WINDOW *)
```
<table><thead><tr><td>Include file</td><td>Provides</td></tr></thead><tbody><tr><td>caml/mlvalues.h</td><td>definition of the value type, and conversion macros</td></tr><tr><td>caml/alloc.h</td><td>allocation functions (to create structured OCaml objects)</td></tr><tr><td>caml/memory.h</td><td>miscellaneous memory-related functions and macros (for GC interface, in-place modification of structures, etc).</td></tr><tr><td>caml/fail.h</td><td>functions for raising exceptions (see section 22.4.7)</td></tr><tr><td>caml/callback.h</td><td>callback from C to OCaml (see section 22.7).</td></tr><tr><td>caml/custom.h</td><td>operations on custom blocks (see section 22.9).</td></tr><tr><td>caml/intext.h</td><td>operations for writing user-defined serialization and deserialization functions for custom blocks (see section 22.9).</td></tr><tr><td>caml/threads.h</td><td>operations for interfacing in the presence of multiple threads (see section 22.12).</td></tr></tbody></table>

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`).

### 22.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 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;

* the names of the desired OCaml object files (`.cmo` and `.cma` files);
as OCaml custom blocks. */

static struct custom_operations curses window_ops = {
    "fr.inria.caml.curses_windows",
    custom finalize default,
    custom compare default,
    custom_hash default,
    custom serialize default,
    custom desynchronize default,
    custom compare ext default,
    custom fixed length default
};

/* Accessing the WINDOW * part of an OCaml custom block */
#define Window_val(v) (((WINDOW **) Data_custom_val(v)))

/* Allocating an OCaml custom block to hold the given WINDOW * */
static value alloc_windows(WINDOW * w)
{
    value v = caml_alloc_custom(&curses_windows_ops, sizeof(WINDOW *), 0, 1);
    Window_val(v) = w;
    return v;
}

CAMLprim value caml_curses_initscr(value unit)
{
    CAMLparam1 (unit);
    CAMLreturn (alloc_windows(initscr));
}

CAMLprim value caml_curses_endwin(value unit)
{
    CAMLparam1 (unit);
    endwin();
    CAMLreturn (Val_unit);
}

CAMLprim value caml_curses_refresh(value unit)
{
    CAMLparam1 (unit);
    refresh();
    CAMLreturn (Val_unit);
}

CAMLprim value caml_curses_wrefresh(value win)
* 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:

```
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.

### 22.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). Finally (step 3), execute the `ocamlc` command with
```c
{
    CAMLparam1 (win);
    wrefresh個人(Window_val win);
    CAMLreturn (Val_unit);
}

CAMLprim value caml_curses_newwin(value nlines, value ncols, value x0, value y0)
{
    CAMLparam4 (nlines, ncols, x0, y0);
    CAMLreturn (alloc_windows(newwin(Int_val(nlines), Int_val.ncols),
                             Int_val(x0), Int_val(y0)));
}

CAMLprim value caml_curses_addch(value c)
{
    CAMLparam1 (c);
    addch(Int_val(c));          /* Characters are encoded like integers */
    CAMLreturn (Val_unit);
}

CAMLprim value caml_curses_mvwaddch(value win, value x, value y, value c)
{
    CAMLparam4 (win, x, y, c);
    mvwaddch personal, Int_val(x), Int_val(y), Int_val(c);
    CAMLreturn (Val_unit);
}

CAMLprim value caml_curses_addstr(value s)
{
    CAMLparam1 (s);
    addstr personal(s);
    CAMLreturn (Val_unit);
}

CAMLprim value caml_curses_mvwaddstr(value win, value x, value y, value s)
{
    CAMLparam4 (win, x, y, s);
    mvwaddstr personal, Int_val(x), Int_val(y), String_val(s);
    CAMLreturn (Val_unit);
}

/* This goes on for pages. */
```

The file curses_stubs.c can be compiled with:

```
cc -c -I`ocamlc -where` curses_stubs.c
```
* 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`.

Do not set the `-custom` flag, otherwise you're back to static linking as described in section 22.1.3, The `ocamlmklib` tool (see section 22.14) 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.

### 22.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`.

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
or, even simpler,

```
ocamlc -c curses_stubs.c
```

(When passed a `.c` file, the `ocamlc` command simply calls the C compiler on that file, with the right `-I` option.)

Now, here is a sample OCaml program `prog.ml` that uses the `curses` module:

```ocaml
(* File prog.ml -- main program using curses *)
open Curses;;

let mainwindow = initscr () in
let smallwindow = newwin 10 5 20 10 in
mvwaddstr mainwindow 10 2 "Hello";
mvwaddstr smallwindow 4 3 "world";
refresh();
Unix.sleep 5;
endwin()
```

To compile and link this program, run:

```
ocamlc -custom -o prog unix.cma curses.cmo prog.ml curses_stubs.o -cclib -lcurses
```

(On some machines, you may need to put `-cclib -lcurses -cclib -ltermcap` or `-cclib -ltermcap` instead of `-cclib -lcurses`.)

## 22.7 Advanced topic: callbacks from C to OCaml

So far, we have described how to call C functions from OCaml. In this section, we show how C functions can call OCaml functions, either as callbacks (OCaml calls C which calls OCaml), or with the main program written in C.

### 22.7.1 Applying OCaml closures from C

C functions can apply OCaml function values (closures) to OCaml values. The following functions are provided to perform the applications:

* `caml_callback(f, a)` applies the functional value `f` to the value `a` and returns the value returned by `f`.

* `caml_callback2(f, a, b)` applies the functional value `f` (which is assumed to be a curried OCaml function with two arguments) to `a` and `b`.

* `caml_callback3(f, a, b, c)` applies the functional value `f` (a curried OCaml function with three arguments) to `a`, `b`, and `c`.

* `caml_callbackN(f, n, args)` applies the functional value `f` to the `n` arguments contained in the C array of values `args`.
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) 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.

22.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).

22.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.
If the function *f* does not return, but raises an exception that escapes the scope of the application, then this exception is propagated to the next enclosing OCaml code, skipping over the C code. That is, if an OCaml function *f* calls a C function *g* that calls back an OCaml function *h* that raises a stray exception, then the execution of *g* is interrupted and the exception is propagated back into *f*.

If the C code wishes to catch exceptions escaping the OCaml function, it can use the functions `caml_callback_exn`, `caml_callback2_exn`, `caml_callback3_exn`, `caml_callbackN_exn`. These functions take the same arguments as their non-`_exn` counterparts, but catch escaping exceptions and return them to the C code. The return value *v* of the `caml_callback* _exn` functions must be tested with the macro `Is_exception_result(v)`. If the macro returns "false", no exception occurred, and *v* is the value returned by the OCaml function. If `Is_exception_result(v)` returns "true", an exception escaped, and its value (the exception descriptor) can be recovered using `Extract_exception(v)`.

**Warning:** If the OCaml function returned with an exception, `Extract_exception` should be applied to the exception result prior to calling a function that may trigger garbage collection. Otherwise, if *v* is reachable during garbage collection, the runtime can crash since *v* does not contain a valid value.

Example:

```c
CAMLprim value call_caml_f_ex(value closure, value arg)
{
    CAMLparam2(closure, arg);
    CAMLlocal2(res, tmp);
    res = caml_callback_exn(closure, arg);
    if (Is_exception_result(res)) {
        res = Extract_exception(res);
        tmp = caml_alloc(3, 0); /* Safe to allocate: res contains valid value. */
        ...
    }
    CAMLreturn (res);
}
```

### 22.7.2 Obtaining or registering OCaml closures for use in C functions

There are two ways to obtain OCaml function values (closures) to be passed to the callback functions described above. One way is to pass the OCaml function as an argument to a primitive function. For example, if the OCaml code contains the declaration

```c
external apply : ('a -> 'b) -> 'a -> 'b = "caml_apply"
```

the corresponding C stub can be written as follows:

```c
CAMLprim value caml_apply(value vf, value vx)
{
    CAMLparam2(vf, vx);
    CAMLlocal1(vy);
    vy = caml_callback(vf, vx);
```
### 22.2.1 Integer values

Integer values encode 63-bit signed integers (31-bit on 32-bit architectures). They are unboxed (unallocated).

### 22.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:

<table><thead><tr><td>Tag</td><td>Contents of the block</td></tr></thead><tbody><tr><td>0 to No_scan_tag - 1</td><td>A structured block (an array of OCaml objects). Each field is a value.</td></tr><tr><td>Closure_tag</td><td>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.</td></tr><tr><td>String_tag</td><td>A character string or a byte sequence.</td></tr><tr><td>Double_tag</td><td>A double-precision floating-point number.</td></tr><tr><td>Double_array_tag</td><td>An array or record of double-precision floating-point numbers.</td></tr><tr><td>Abstract_tag</td><td>A block representing an abstract datatype.</td></tr><tr><td>Custom_tag</td><td>A block representing an abstract datatype with user-defined finalization, comparison, hashing, serialization and deserialization functions attached.</td></tr></tbody></table>

### 22.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 gives a more complete example using `Custom_tag` blocks.

```c
/* Create an OCaml value encapsulating the pointer p */
static value val_ofTyptr(ty *p)
{
    value v = caml_alloc(1, Abstract_tag);
    *((ty **) Data GALVAL(v)) = p;
    return v;
}
```
```c
        CAMLreturn(vy);
    }
```

Another possibility is to use the registration mechanism provided by OCaml. This registration mechanism enables OCaml code to register OCaml functions under some global name, and C code to retrieve the corresponding closure by this global name.

On the OCaml side, registration is performed by evaluating `Callback.register n v`. Here, *n* is the global name (an arbitrary string) and *v* the OCaml value. For instance:

```c
let f x = print_string "f is applied to "; print_int x; print_newline()
let _ = Callback.register "test function" f
```

On the C side, a pointer to the value registered under name *n* is obtained by calling `caml_named_value(n)`. The returned pointer must then be dereferenced to recover the actual OCaml value. If no value is registered under the name *n*, the null pointer is returned. For example, here is a C wrapper that calls the OCaml function *f* above:

```c
void call_caml_f(int arg)
{
    caml_callback(*caml_named_value("test function"), Val_int(arg));
}
```

The pointer returned by `caml_named_value` is constant and can safely be cached in a C variable to avoid repeated name lookups. The value pointed to cannot be changed from C. However, it might change during garbage collection, so must always be recomputed at the point of use. Here is a more efficient variant of `call_caml_f` above that calls `caml_named_value` only once:

```c
void call_caml_f(int arg)
{
    static const value * closure_f = NULL;
    if (closure_f == NULL) {
        /* First time around, look up by name */
        closure_f = caml_named_value("test function");
    }
    caml_callback(*closure_f, Val_int(arg));
}
```

### 22.7.3 Registering OCaml exceptions for use in C functions

The registration mechanism described above can also be used to communicate exception identifiers from OCaml to C. The OCaml code registers the exception by evaluating `Callback.register_exception n exn`, where *n* is an arbitrary name and *exn* is an exception value of the exception to register. For example:

```c
exception Error of string
let _ = Callback.register_exception "test exception" (Error "any string")
```
```c
/* 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.

```c
/* Create an OCaml value encapsulating the pointer p */
static value val_ofTyptr(ty * p)
{
    return caml_copy_nativeint((intnat) p);
}
```

```c
/* Extract the pointer encapsulated in the given OCaml value */
static ty * typtr_of_val(value v)
{
    return (ty *) Nativeint_val(v);
}
```

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.

```c
/* Create an OCaml value encapsulating the pointer p */
static value val_ofTyptr(ty * p)
{
    assert (((基金管理器_t) p & 1) == 0); /* check correct alignment */
    return (value) p | 1;
}
```

```c
/* Extract the pointer encapsulated in the given OCaml value */
static ty * typtr_of_val(value v)
{
    return (ty *) (v & ~1);
}
```

## 22.3 Representation of OCaml data types

This section describes how OCaml data types are encoded in the *value type*.