# Runtime Profiler API

The profiler API can be used by dynamically loaded profiler modules to monitor different aspects of a running program. The API is also usable by embedders without having to compile a profiler module.

## Profiler Modules

A profiler module is simply a shared library with a single exported function which is the entry point that Mono calls at startup. It must have the following signature:

    void mono_profiler_startup_example (const char *desc)

Here, the `example` portion of the function name is the name of the profiler module. It must match the shared library name (i.e. `libmono-profiler-example.so`). desc is the set of arguments that were passed from the command line.

For example, a bare bones profiler module might look like this (`example.c`):

    #include <mono/metadata/profiler.h>
    #include <stdio.h>

    struct _MonoProfiler {
    	int dummy;
    }

    static MonoProfiler profiler;

    static void
    runtime_inited (MonoProfiler *prof)
    {
    	printf ("Hello World");
    }

    void
    mono_profiler_init_example (const char *desc)
    {
    	MonoProfilerHandle handle = mono_profiler_create (&profiler);
    	mono_profiler_set_runtime_initialized_callback (handle, runtime_inited);
    }

To compile this module, a C compiler must be invoked in a similar fashion to this, on Linux:

    gcc -fPIC -shared -o libmono-profiler-example.so example.c `pkg-config --cflags mono-2`

Or on OS X:

    gcc -undefined suppress -flat_namespace -o libmono-profiler-example.so example.c `pkg-config --cflags mono-2`

You can then load the module using:

    mono --profile=example hello.exe

(Note that adjusting `LD_LIBRARY_PATH` may be necessary in order for the dynamic linker to find the module.)

## Profiler Functions

These are the functions usable for profiling programs.

Each function has a note indicating whether they're async safe. An async safe function can be invoked in a signal handler or when the world is stopped by the GC. Conversely, a function that is not async safe must not be invoked in such a context or undefined behavior can occur (crashes, deadlocks, etc).

Some functions may only be invoked from a profiler module's init function (or prior to running managed code in the case of embedding). This is noted explicitly only if applicable to a function.

### Basic Functions

These functions are used to load and install profilers.

`mono_profiler_load`
Syntax
void mono_profiler_load (const char *desc)

Description

Loads a profiler module based on the specified description. desc can be of the form `name:args` or just `name`. For example, `log:sample` and `log` will both load `libmono-profiler-log.so`. The description is passed to the module after it has been loaded. If the specified module has already been loaded, this function has no effect.

A module called `foo` should declare an entry point like so:

     void mono_profiler_init_foo (const char *desc)
     {
     }

This function is not async safe.

This function may only be called by embedders prior to running managed code.

`mono_profiler_create`
Syntax
MonoProfilerHandle mono_profiler_create (MonoProfiler *prof)

Description

Installs a profiler and returns a handle for it. The handle is used with the other functions in the profiler API (e.g. for setting up callbacks). The given structure pointer, prof, will be passed to all callbacks from the profiler API. It can be ``NULL``.

Example usage:

     struct _MonoProfiler {
     	int my_stuff;
     	// ...
     };

     MonoProfiler *prof = malloc (sizeof (MonoProfiler));
     prof->my_stuff = 42;
     MonoProfilerHandle handle = mono_profiler_create (prof);
     mono_profiler_set_shutdown_callback (handle, my_shutdown_cb);

This function is not async safe.

This function may only be called from a profiler's init function or prior to running managed code.

`mono_profiler_set_cleanup_callback`
Syntax
void mono_profiler_set_cleanup_callback (MonoProfilerHandle handle, MonoProfilerCleanupCallback cb)

Description

Sets a profiler cleanup function. This function will be invoked at shutdown when the profiler API is cleaning up its internal structures. It's mainly intended for a profiler to free the structure pointer that was passed to `mono_profiler_create`, if necessary.

This function is async safe.

### Code Coverage

These functions provide access to the JIT compiler's code coverage support. This functionality can be used to collect information about how many times certain code paths have been executed.

`mono_profiler_enable_coverage`
Syntax
mono_bool mono_profiler_enable_coverage (void)

Description

Enables support for code coverage instrumentation. At the moment, this means enabling the debug info subsystem. If this function is not called, it will not be possible to use `mono_profiler_get_coverage_data`. Returns ``TRUE`` if code coverage support was enabled, or ``FALSE`` if the function was called too late for this to be possible.

This function is not async safe.

This function may only be called from a profiler's init function or prior to running managed code.

`mono_profiler_set_coverage_filter_callback`
Syntax
void mono_profiler_set_coverage_filter_callback (MonoProfilerHandle handle, MonoProfilerCoverageFilterCallback cb)

Description

Sets a code coverage filter function. The profiler API will invoke filter functions from all installed profilers. If any of them return ``TRUE``, then the given method will be instrumented for coverage analysis. All filters are guaranteed to be called at least once per method, even if an earlier filter has already returned ``TRUE``.

Note that filter functions must be installed before a method is compiled in order to have any effect, i.e. a filter should be registered in a profiler's init function or prior to running managed code (if embedding).

This function is async safe.

`mono_profiler_get_coverage_data`
Syntax
mono_bool mono_profiler_get_coverage_data (MonoProfilerHandle handle, MonoMethod *method, MonoProfilerCoverageCallback cb)

Description

Retrieves all coverage data for method and invokes cb for each entry. Source location information will only be filled out if method has debug info available. Returns ``TRUE`` if method was instrumented for code coverage; otherwise, ``FALSE``.

Please note that the structure passed to cb is only valid for the duration of the callback.

This function is not async safe.

### Statistical Sampling

Statistical sampling can be used to interrupt managed threads based on a certain mode and frequency for the purpose of collecting data about their current work.

One common use case for this functionality, usually referred to as call sampling, is to collect a backtrace from every thread when a sampling hit event arrives. This data can then be compiled into a report indicating where a program spends most of its time.

`mono_profiler_enable_sampling`
Syntax
mono_bool mono_profiler_enable_sampling (MonoProfilerHandle handle)

Description

Enables the sampling thread. Users must call this function if they intend to use statistical sampling; `mono_profiler_set_sample_mode` will have no effect if this function has not been called. The first profiler to call this function will get ownership over sampling settings (mode and frequency) so that no other profiler can change those settings. Returns ``TRUE`` if the sampling thread was enabled, or ``FALSE`` if the function was called too late for this to be possible.

Note that `mono_profiler_set_sample_mode` must still be called with a mode other than `MONO_PROFILER_SAMPLE_MODE_NONE` to actually start sampling.

This function is not async safe.

This function may only be called from a profiler's init function or prior to running managed code.

`mono_profiler_set_sample_mode`
Syntax
mono_bool mono_profiler_set_sample_mode (MonoProfilerHandle handle, MonoProfilerSampleMode mode, uint32_t freq)

Description

Sets the sampling mode and frequency (in Hz). freq must be a positive number. If the calling profiler has ownership over sampling settings, the settings will be changed and this function will return ``TRUE``; otherwise, it returns ``FALSE`` without changing any settings.

This function is async safe.

`mono_profiler_get_sample_mode`
Syntax
mono_bool mono_profiler_get_sample_mode (MonoProfilerHandle handle, MonoProfilerSampleMode *mode, uint32_t *freq)

Description

Retrieves the current sampling mode and/or frequency (in Hz). Returns ``TRUE`` if the calling profiler is allowed to change the sampling settings; otherwise, ``FALSE``.

This function is async safe.

A callback must be registered to receive sample hit events. Please see the Callback Registration section below.

### GC Allocations

Profilers can be notified about all GC allocations performed by a program or the Mono runtime.

`mono_profiler_enable_allocations`
Syntax
mono_bool mono_profiler_enable_allocations (void)

Description

Enables instrumentation of GC allocations. This is necessary so that managed allocators can be instrumented with a call into the profiler API. Allocations will not be reported unless this function is called. Returns ``TRUE`` if allocation instrumentation was enabled, or ``FALSE`` if the function was called too late for this to be possible.

This function is not async safe.

This function may only be called from a profiler's init function or prior to running managed code.

A callback must be registered to receive allocation events. Please see the Callback Registration section below.

### Call Instrumentation

The JIT compiler supports instrumenting managed method entry and exit points so that a profiler callback will be invoked.

While such callbacks by themselves have traditionally only been useful for call count profiling and the like, Mono gives these callbacks access to the arguments, locals, and return value of instrumented methods (together referred to as the 'call context'). This enables many profiling scenarios that would otherwise have required explicit hooks in the base class libraries.

`mono_profiler_set_call_instrumentation_filter_callback`
Syntax
void mono_profiler_set_call_instrumentation_filter_callback (MonoProfilerHandle handle, MonoProfilerCallInstrumentationFilterCallback cb)

Description

Sets a call instrumentation filter function. The profiler API will invoke filter functions from all installed profilers. If any of them return flags other than `MONO_PROFILER_CALL_INSTRUMENTATION_NONE`, then the given method will be instrumented as requested. All filters are guaranteed to be called at least once per method, even if earlier filters have already specified all flags.

Note that filter functions must be installed before a method is compiled in order to have any effect, i.e. a filter should be registered in a profiler's init function or prior to running managed code (if embedding). Also, to instrument a method that's going to be AOT-compiled, a filter must be installed at AOT time. This can be done in exactly the same way as one would normally, i.e. by passing the `--profile` option on the command line, by calling `mono_profiler_load`, or simply by using the profiler API as an embedder.

Indiscriminate method instrumentation is extremely heavy and will slow down most applications to a crawl. Users should consider sampling as a possible alternative to such heavy-handed instrumentation.

This function is async safe.

`mono_profiler_enable_call_context_introspection`
Syntax
mono_bool mono_profiler_enable_call_context_introspection (void)

Description

Enables support for retrieving stack frame data from a call context. At the moment, this means enabling the debug info subsystem. If this function is not called, it will not be possible to use the call context introspection functions (they will simply return ``NULL`)`. Returns ``TRUE`` if call context introspection was enabled, or ``FALSE`` if the function was called too late for this to be possible.

This function is not async safe.

This function may only be called from a profiler's init function or prior to running managed code.

`mono_profiler_call_context_get_this`
Syntax
void* mono_profiler_call_context_get_this (MonoProfilerCallContext *context)

Description

Given a valid call context from an enter/leave event, retrieves a pointer to the `this` reference for the method. Returns ``NULL`` if none exists (i.e. it's a static method) or if call context introspection was not enabled.

The buffer returned by this function must be freed with `mono_profiler_call_context_free_buffer`.

Please note that a call context is only valid for the duration of the enter/leave callback it was passed to.

This function is not async safe.

`mono_profiler_call_context_get_argument`
Syntax
void* mono_profiler_call_context_get_argument (MonoProfilerCallContext *context, uint32_t position)

Description

Given a valid call context from an enter/leave event, retrieves a pointer to the method argument at the given position. Returns ``NULL`` if position is out of bounds or if call context introspection was not enabled.

The buffer returned by this function must be freed with `mono_profiler_call_context_free_buffer`.

Please note that a call context is only valid for the duration of the enter/leave callback it was passed to.

This function is not async safe.

`mono_profiler_call_context_get_local`
Syntax
void* mono_profiler_call_context_get_local (MonoProfilerCallContext *context, uint32_t position)

Description

Given a valid call context from an enter/leave event, retrieves a pointer to the local variable at the given position. Returns ``NULL`` if position is out of bounds or if call context introspection was not enabled.

The buffer returned by this function must be freed with `mono_profiler_call_context_free_buffer`.

Please note that a call context is only valid for the duration of the enter/leave callback it was passed to.

This function is not async safe.

`mono_profiler_call_context_get_result`
Syntax
void* mono_profiler_call_context_get_result (MonoProfilerCallContext *context)

Description

Given a valid call context from an enter/leave event, retrieves a pointer to return value of a method. Returns ``NULL`` if the method has no return value (i.e. it returns `void)`, if the leave event was the result of a tail call, if the function is called on a context from an enter event, or if call context introspection was not enabled.

The buffer returned by this function must be freed with `mono_profiler_call_context_free_buffer`.

Please note that a call context is only valid for the duration of the enter/leave callback it was passed to.

This function is not async safe.

`mono_profiler_call_context_free_buffer`
Syntax
void mono_profiler_call_context_free_buffer (void *buffer)

Description

Frees a buffer returned by one of the call context introspection functions. Passing a ``NULL`` value for buffer is allowed, which makes this function a no-op.

This function is not async safe.

Callbacks must be registered to receive method entry and exit events. Please see the Callback Registration section below.

### Callback Registration

In addition to the above functions, there's a large set of functions for installing generic profiler event callbacks. These are generated from C macros and so are not documented here. Please refer to the `mono/metadata/profiler.h` and `mono/metadata/profiler-events.h` headers for a full listing of these.

Callback registration functions are all async safe and can be safely invoked from multiple threads at the same time, with the caveat that altering a registered callback from one thread will not immediately affect another thread that is already invoking the current callback.

## API Stability

The profiler API does not have the same API stability garantees that the rest of the Mono embedding API does. While a breaking change to the profiler API is extremely rare, it has happened in the past when changing the API in a backwards compatible way was deemed to be too much work for too little gain.

Therefore, developers of profiler modules may rarely need to update their code to work with new versions of the profiler API.

Developers who wish to support older versions of the API can perform a compile time check of the `MONO_PROFILER_API_VERSION` macro and maintain code for both old and new versions.

To aid with transitioning to a new version of the profiler API, the Mono runtime will detect and reject loading profiler