• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1.. highlight:: c
2
3.. _perfmaps:
4
5Support for Perf Maps
6----------------------
7
8On supported platforms (as of this writing, only Linux), the runtime can take
9advantage of *perf map files* to make Python functions visible to an external
10profiling tool (such as `perf <https://perf.wiki.kernel.org/index.php/Main_Page>`_).
11A running process may create a file in the ``/tmp`` directory, which contains entries
12that can map a section of executable code to a name. This interface is described in the
13`documentation of the Linux Perf tool <https://git.kernel.org/pub/scm/linux/
14kernel/git/torvalds/linux.git/tree/tools/perf/Documentation/jit-interface.txt>`_.
15
16In Python, these helper APIs can be used by libraries and features that rely
17on generating machine code on the fly.
18
19Note that holding the Global Interpreter Lock (GIL) is not required for these APIs.
20
21.. c:function:: int PyUnstable_PerfMapState_Init(void)
22
23   Open the ``/tmp/perf-$pid.map`` file, unless it's already opened, and create
24   a lock to ensure thread-safe writes to the file (provided the writes are
25   done through :c:func:`PyUnstable_WritePerfMapEntry`). Normally, there's no need
26   to call this explicitly; just use :c:func:`PyUnstable_WritePerfMapEntry`
27   and it will initialize the state on first call.
28
29   Returns ``0`` on success, ``-1`` on failure to create/open the perf map file,
30   or ``-2`` on failure to create a lock. Check ``errno`` for more information
31   about the cause of a failure.
32
33.. c:function:: int PyUnstable_WritePerfMapEntry(const void *code_addr, unsigned int code_size, const char *entry_name)
34
35   Write one single entry to the ``/tmp/perf-$pid.map`` file. This function is
36   thread safe. Here is what an example entry looks like::
37
38      # address      size  name
39      7f3529fcf759 b     py::bar:/run/t.py
40
41   Will call :c:func:`PyUnstable_PerfMapState_Init` before writing the entry, if
42   the perf map file is not already opened. Returns ``0`` on success, or the
43   same error codes as :c:func:`PyUnstable_PerfMapState_Init` on failure.
44
45.. c:function:: void PyUnstable_PerfMapState_Fini(void)
46
47   Close the perf map file opened by :c:func:`PyUnstable_PerfMapState_Init`.
48   This is called by the runtime itself during interpreter shut-down. In
49   general, there shouldn't be a reason to explicitly call this, except to
50   handle specific scenarios such as forking.
51