Chapter 11 The runtime system (ocamlrun)

The ocamlrun command executes bytecode files produced by thelinking phase of the ocamlc command.

11.1 Overview

The ocamlrun command comprises three main parts: the bytecodeinterpreter, that actually executes bytecode files; the memoryallocator and garbage collector; and a set of C functions thatimplement primitive operations such as input/output.

The usage for ocamlrun is:

  1. ocamlrun options bytecode-executable arg1 ... argn

The first non-option argument is taken to be the name of the filecontaining the executable bytecode. (That file is searched in theexecutable path as well as in the current directory.) The remainingarguments are passed to the OCaml program, in the string arraySys.argv. Element 0 of this array is the name of thebytecode executable file; elements 1 to n are the remainingarguments arg1 to argn.

As mentioned in chapter 9, the bytecode executable filesproduced by the ocamlc command are self-executable, and manage tolaunch the ocamlrun command on themselves automatically. That is,assuming a.out is a bytecode executable file,

  1. a.out arg1 ... argn

works exactly as

  1. ocamlrun a.out arg1 ... argn

Notice that it is not possible to pass options to ocamlrun wheninvoking a.out directly.

Windows:Under several versions of Windows, bytecode executable files areself-executable only if their name ends in .exe. It is recommendedto always give .exe names to bytecode executables, e.g. compilewith ocamlc -o myprog.exe … rather than ocamlc -o myprog ….

11.2 Options

The following command-line options are recognized by ocamlrun.

  • -b
  • When the program aborts due to an uncaught exception, print a detailed“back trace” of the execution, showing where the exception wasraised and which function calls were outstanding at this point. Theback trace is printed only if the bytecode executable containsdebugging information, i.e. was compiled and linked with the -goption to ocamlc set. This is equivalent to setting the b flagin the OCAMLRUNPARAM environment variable (see below).
  • -Idir
  • Search the directory dir for dynamically-loaded libraries,in addition to the standard search path (seesection 11.3).
  • -m
  • Print the magic number of the bytecode executable given as argumentand exit.
  • -M
  • Print the magic number expected by this version of the runtime and exit.
  • -p
  • Print the names of the primitives known to this version ofocamlrun and exit.
  • -v
  • Direct the memory manager to print some progress messages onstandard error. This is equivalent to setting v=63 in theOCAMLRUNPARAM environment variable (see below).
  • -version
  • Print version string and exit.
  • -vnum
  • Print short version number and exit.The following environment variables are also consulted:

  • CAML_LD_LIBRARY_PATH

  • Additional directories to search fordynamically-loaded libraries (see section 11.3).
  • OCAMLLIB
  • The directory containing the OCaml standardlibrary. (If OCAMLLIB is not set, CAMLLIB will be used instead.)Used to locate the ld.conf configuration file fordynamic loading (see section 11.3). If not set,default to the library directory specified when compiling OCaml.
  • OCAMLRUNPARAM
  • Set the runtime system optionsand garbage collection parameters.(If OCAMLRUNPARAM is not set, CAMLRUNPARAM will be used instead.)This variable must be a sequence of parameter specifications separatedby commas.A parameter specification is an option letter followed by an =sign, a decimal number (or an hexadecimal number prefixed by 0x),and an optional multiplier. The options are documented below;the last six correspond to the fields of thecontrol record documented inModule Gc.
    • b
    • (backtrace) Trigger the printing of a stack backtracewhen an uncaught exception aborts the program.This option takes no argument.
    • p
    • (parser trace) Turn on debugging support forocamlyacc-generated parsers. When this option is on,the pushdown automaton that executes the parsers prints atrace of its actions. This option takes no argument.
    • R
    • (randomize) Turn on randomization of all hash tables by default(seeModule Hashtbl).This option takes no argument.
    • h
    • The initial size of the major heap (in words).
    • a
    • (allocation_policy) The policy used for allocating in theOCaml heap. Possible values are 0 for the next-fit policy, and 1for the first-fit policy. Next-fit is usually faster, but first-fitis better for avoiding fragmentation and the associated heapcompactions.
    • s
    • (minor_heap_size) Size of the minor heap. (in words)
    • i
    • (major_heap_increment) Default size increment for themajor heap. (in words)
    • o
    • (space_overhead) The major GC speed setting.
    • O
    • (max_overhead) The heap compaction trigger setting.
    • l
    • (stack_limit) The limit (in words) of the stack size.
    • v
    • (verbose) What GC messages to print to stderr. Thisis a sum of values selected from the following:
      • 1 (= 0x001)
      • Start of major GC cycle.
      • 2 (= 0x002)
      • Minor collection and major GC slice.
      • 4 (= 0x004)
      • Growing and shrinking of the heap.
      • 8 (= 0x008)
      • Resizing of stacks and memory manager tables.
      • 16 (= 0x010)
      • Heap compaction.
      • 32 (= 0x020)
      • Change of GC parameters.
      • 64 (= 0x040)
      • Computation of major GC slice size.
      • 128 (= 0x080)
      • Calling of finalization functions
      • 256 (= 0x100)
      • Startup messages (loading the bytecodeexecutable file, resolving shared libraries).
      • 512 (= 0x200)
      • Computation of compaction-triggering condition.
      • 1024 (= 0x400)
      • Output GC statistics at program exit.
    • c
    • (cleanup_on_exit) Shut the runtime down gracefully on exit (seecaml_shutdown in section 19.7.5). The option also enablespooling (as in caml_startup_pooled). This mode can be used to detectleaks with a third-party memory debugger.
    • M
    • (custom_major_ratio) Target ratio of floating garbage tomajor heap size for out-of-heap memory held by custom values(e.g. bigarrays) located in the major heap. The GC speed is adjustedto try to use this much memory for dead values that are not yetcollected. Expressed as a percentage of major heap size. Default:44. Note: this only applies to values allocated withcaml_alloc_custom_mem.
    • m
    • (custom_minor_ratio) Bound on floating garbage forout-of-heap memoryheld by custom values in the minor heap. A minor GC is triggeredwhen this much memory is held by custom values located in the minorheap. Expressed as a percentage of minor heap size. Default:100. Note: this only applies to values allocated withcaml_alloc_custom_mem.
    • n
    • (custom_minor_max_size) Maximum amount of out-of-heapmemory for each custom value allocated in the minor heap. When a customvalue is allocated on the minor heap and holds more than this manybytes, only this value is counted against custom_minor_ratio andthe rest is directly counted against custom_major_ratio.Default: 8192 bytes. Note:this only applies to values allocated with caml_alloc_custom_mem.The multiplier is k, M, or G, for multiplication by 210,220, and 230 respectively.If the option letter is not recognized, the whole parameter is ignored;if the equal sign or the number is missing, the value is taken as 1;if the multiplier is not recognized, it is ignored.

For example, on a 32-bit machine, under bash the command

  1. export OCAMLRUNPARAM='b,s=256k,v=0x015'

tells a subsequent ocamlrun to print backtraces for uncaught exceptions,set its initial minor heap size to 1 megabyte andprint a message at the start of each major GC cycle, when the heapsize changes, and when compaction is triggered.

  • CAMLRUNPARAM
  • If OCAMLRUNPARAM is not found in theenvironment, then CAMLRUNPARAM will be used instead. IfCAMLRUNPARAM is also not found, then the default values will be used.
  • PATH
  • List of directories searched to find the bytecodeexecutable file.

11.3 Dynamic loading of shared libraries

On platforms that support dynamic loading, ocamlrun can linkdynamically with C shared libraries (DLLs) providing additional C primitivesbeyond those provided by the standard runtime system. The names forthese libraries are provided at link time as described insection 19.1.4), and recorded in the bytecode executablefile; ocamlrun, then, locates these libraries and resolves referencesto their primitives when the bytecode executable program starts.

The ocamlrun command searches shared libraries in the followingdirectories, in the order indicated:

  • Directories specified on the ocamlrun command line with the-I option.
  • Directories specified in the CAML_LD_LIBRARY_PATH environmentvariable.
  • Directories specified at link-time via the -dllpath option toocamlc. (These directories are recorded in the bytecode executablefile.)
  • Directories specified in the file ld.conf. This file residesin the OCaml standard library directory, and lists directorynames (one per line) to be searched. Typically, it contains only oneline naming the stublibs subdirectory of the OCaml standardlibrary directory. Users can add there the names of other directoriescontaining frequently-used shared libraries; however, for consistencyof installation, we recommend that shared libraries are installeddirectly in the system stublibs directory, rather than adding linesto the ld.conf file.
  • Default directories searched by the system dynamic loader.Under Unix, these generally include /lib and /usr/lib, plus thedirectories listed in the file /etc/ld.so.conf and the environmentvariable LD_LIBRARY_PATH. Under Windows, these include the Windowssystem directories, plus the directories listed in the PATHenvironment variable.

11.4 Common errors

This section describes and explains the most frequently encounterederror messages.

  • filename: no such file or directory
  • If filename is the name of a self-executable bytecode file, thismeans that either that file does not exist, or that it failed to runthe ocamlrun bytecode interpreter on itself. The second possibilityindicates that OCaml has not been properly installed on yoursystem.
  • Cannot exec ocamlrun
  • (When launching a self-executable bytecode file.) The ocamlruncould not be found in the executable path. Check that OCamlhas been properly installed on your system.
  • Cannot find the bytecode file
  • The file that ocamlrun is trying to execute (e.g. the file given asfirst non-option argument to ocamlrun) either does not exist, or isnot a valid executable bytecode file.
  • Truncated bytecode file
  • The file that ocamlrun is trying to execute is not a valid executablebytecode file. Probably it has been truncated or mangled sincecreated. Erase and rebuild it.
  • Uncaught exception
  • The program being executed contains a “stray” exception. That is,it raises an exception at some point, and this exception is nevercaught. This causes immediate termination of the program. The name ofthe exception is printed, along with its string, byte sequence, andinteger arguments(arguments of more complex types are not correctly printed).To locate the context of the uncaught exception, compile the programwith the -g option and either run it again under the ocamldebugdebugger (see chapter 16), or run it with ocamlrun -bor with the OCAMLRUNPARAM environment variable set to b=1.
  • Out of memory
  • The program being executed requires more memory than available. Eitherthe program builds excessively large data structures; or the programcontains too many nested function calls, and the stack overflows. Insome cases, your program is perfectly correct, it just requires morememory than your machine provides. In other cases, the “out ofmemory” message reveals an error in your program: non-terminatingrecursive function, allocation of an excessively large array,string or byte sequence, attempts to build an infinite list or otherdata structure, …To help you diagnose this error, run your program with the -v optionto ocamlrun, or with the OCAMLRUNPARAM environment variable set tov=63. If it displays lots of “Growing stack…”messages, this is probably a looping recursive function. If itdisplays lots of “Growing heap…” messages, with the heap sizegrowing slowly, this is probably an attempt to construct a datastructure with too many (infinitely many?) cells. If it displays few“Growing heap…” messages, but with a huge increment in theheap size, this is probably an attempt to build an excessively largearray, string or byte sequence.