OSDN Git Service

[docs] Scudo documentation minor update
[android-x86/external-llvm.git] / docs / XRay.rst
1 ====================
2 XRay Instrumentation
3 ====================
4
5 :Version: 1 as of 2016-11-08
6
7 .. contents::
8    :local:
9
10
11 Introduction
12 ============
13
14 XRay is a function call tracing system which combines compiler-inserted
15 instrumentation points and a runtime library that can dynamically enable and
16 disable the instrumentation.
17
18 More high level information about XRay can be found in the `XRay whitepaper`_.
19
20 This document describes how to use XRay as implemented in LLVM.
21
22 XRay in LLVM
23 ============
24
25 XRay consists of three main parts:
26
27 - Compiler-inserted instrumentation points.
28 - A runtime library for enabling/disabling tracing at runtime.
29 - A suite of tools for analysing the traces.
30
31   **NOTE:** As of February 27, 2017 , XRay is only available for the following
32   architectures running Linux: x86_64, arm7 (no thumb), aarch64, powerpc64le,
33   mips, mipsel, mips64, mips64el.
34
35 The compiler-inserted instrumentation points come in the form of nop-sleds in
36 the final generated binary, and an ELF section named ``xray_instr_map`` which
37 contains entries pointing to these instrumentation points. The runtime library
38 relies on being able to access the entries of the ``xray_instr_map``, and
39 overwrite the instrumentation points at runtime.
40
41 Using XRay
42 ==========
43
44 You can use XRay in a couple of ways:
45
46 - Instrumenting your C/C++/Objective-C/Objective-C++ application.
47 - Generating LLVM IR with the correct function attributes.
48
49 The rest of this section covers these main ways and later on how to customise
50 what XRay does in an XRay-instrumented binary.
51
52 Instrumenting your C/C++/Objective-C Application
53 ------------------------------------------------
54
55 The easiest way of getting XRay instrumentation for your application is by
56 enabling the ``-fxray-instrument`` flag in your clang invocation.
57
58 For example:
59
60 ::
61
62   clang -fxray-instrument ...
63
64 By default, functions that have at least 200 instructions will get XRay
65 instrumentation points. You can tweak that number through the
66 ``-fxray-instruction-threshold=`` flag:
67
68 ::
69
70   clang -fxray-instrument -fxray-instruction-threshold=1 ...
71
72 You can also specifically instrument functions in your binary to either always
73 or never be instrumented using source-level attributes. You can do it using the
74 GCC-style attributes or C++11-style attributes.
75
76 .. code-block:: c++
77
78     [[clang::xray_always_instrument]] void always_instrumented();
79
80     [[clang::xray_never_instrument]] void never_instrumented();
81
82     void alt_always_instrumented() __attribute__((xray_always_instrument));
83
84     void alt_never_instrumented() __attribute__((xray_never_instrument));
85
86 When linking a binary, you can either manually link in the `XRay Runtime
87 Library`_ or use ``clang`` to link it in automatically with the
88 ``-fxray-instrument`` flag. Alternatively, you can statically link-in the XRay
89 runtime library from compiler-rt -- those archive files will take the name of
90 `libclang_rt.xray-{arch}` where `{arch}` is the mnemonic supported by clang
91 (x86_64, arm7, etc.).
92
93 LLVM Function Attribute
94 -----------------------
95
96 If you're using LLVM IR directly, you can add the ``function-instrument``
97 string attribute to your functions, to get the similar effect that the
98 C/C++/Objective-C source-level attributes would get:
99
100 .. code-block:: llvm
101
102     define i32 @always_instrument() uwtable "function-instrument"="xray-always" {
103       ; ...
104     }
105
106     define i32 @never_instrument() uwtable "function-instrument"="xray-never" {
107       ; ...
108     }
109
110 You can also set the ``xray-instruction-threshold`` attribute and provide a
111 numeric string value for how many instructions should be in the function before
112 it gets instrumented.
113
114 .. code-block:: llvm
115
116     define i32 @maybe_instrument() uwtable "xray-instruction-threshold"="2" {
117       ; ...
118     }
119
120 Special Case File
121 -----------------
122
123 Attributes can be imbued through the use of special case files instead of
124 adding them to the original source files. You can use this to mark certain
125 functions and classes to be never, always, or instrumented with first-argument
126 logging from a file. The file's format is described below:
127
128 .. code-block:: bash
129
130     # Comments are supported
131     [always]
132     fun:always_instrument
133     fun:log_arg1=arg1 # Log the first argument for the function
134
135     [never]
136     fun:never_instrument
137
138 These files can be provided through the ``-fxray-attr-list=`` flag to clang.
139 You may have multiple files loaded through multiple instances of the flag.
140
141 XRay Runtime Library
142 --------------------
143
144 The XRay Runtime Library is part of the compiler-rt project, which implements
145 the runtime components that perform the patching and unpatching of inserted
146 instrumentation points. When you use ``clang`` to link your binaries and the
147 ``-fxray-instrument`` flag, it will automatically link in the XRay runtime.
148
149 The default implementation of the XRay runtime will enable XRay instrumentation
150 before ``main`` starts, which works for applications that have a short
151 lifetime. This implementation also records all function entry and exit events
152 which may result in a lot of records in the resulting trace.
153
154 Also by default the filename of the XRay trace is ``xray-log.XXXXXX`` where the
155 ``XXXXXX`` part is randomly generated.
156
157 These options can be controlled through the ``XRAY_OPTIONS`` environment
158 variable, where we list down the options and their defaults below.
159
160 +-------------------+-----------------+---------------+------------------------+
161 | Option            | Type            | Default       | Description            |
162 +===================+=================+===============+========================+
163 | patch_premain     | ``bool``        | ``false``     | Whether to patch       |
164 |                   |                 |               | instrumentation points |
165 |                   |                 |               | before main.           |
166 +-------------------+-----------------+---------------+------------------------+
167 | xray_mode         | ``const char*`` | ``""``        | Default mode to        |
168 |                   |                 |               | install and initialize |
169 |                   |                 |               | before ``main``.       |
170 +-------------------+-----------------+---------------+------------------------+
171 | xray_logfile_base | ``const char*`` | ``xray-log.`` | Filename base for the  |
172 |                   |                 |               | XRay logfile.          |
173 +-------------------+-----------------+---------------+------------------------+
174 | verbosity         | ``int``         | ``0``         | Runtime verbosity      |
175 |                   |                 |               | level.                 |
176 +-------------------+-----------------+---------------+------------------------+
177
178
179 If you choose to not use the default logging implementation that comes with the
180 XRay runtime and/or control when/how the XRay instrumentation runs, you may use
181 the XRay APIs directly for doing so. To do this, you'll need to include the
182 ``xray_log_interface.h`` from the compiler-rt ``xray`` directory. The important API
183 functions we list below:
184
185 - ``__xray_log_register_mode(...)``: Register a logging implementation against
186   a string Mode identifier. The implementation is an instance of
187   ``XRayLogImpl`` defined in ``xray/xray_log_interface.h``.
188 - ``__xray_log_select_mode(...)``: Select the mode to install, associated with
189   a string Mode identifier. Only implementations registered with
190   ``__xray_log_register_mode(...)`` can be chosen with this function.
191 - ``__xray_log_init_mode(...)``: This function allows for initializing and
192   re-initializing an installed logging implementation. See
193   ``xray/xray_log_interface.h`` for details, part of the XRay compiler-rt
194   installation.
195
196 Once a logging implementation has been initialized, it can be "stopped" by
197 finalizing the implementation through the ``__xray_log_finalize()`` function.
198 The finalization routine is the opposite of the initialization. When finalized,
199 an implementation's data can be cleared out through the
200 ``__xray_log_flushLog()`` function. For implementations that support in-memory
201 processing, these should register an iterator function to provide access to the
202 data via the ``__xray_log_set_buffer_iterator(...)`` which allows code calling
203 the ``__xray_log_process_buffers(...)`` function to deal with the data in
204 memory.
205
206 All of this is better explained in the ``xray/xray_log_interface.h`` header.
207
208 Basic Mode
209 ----------
210
211 XRay supports a basic logging mode which will trace the application's
212 execution, and periodically append to a single log. This mode can be
213 installed/enabled by setting ``xray_mode=xray-basic`` in the ``XRAY_OPTIONS``
214 environment variable. Combined with ``patch_premain=true`` this can allow for
215 tracing applications from start to end.
216
217 Like all the other modes installed through ``__xray_log_select_mode(...)``, the
218 implementation can be configured through the ``__xray_log_init_mode(...)``
219 function, providing the mode string and the flag options. Basic-mode specific
220 defaults can be provided in the ``XRAY_BASIC_OPTIONS`` environment variable.
221
222 Flight Data Recorder Mode
223 -------------------------
224
225 XRay supports a logging mode which allows the application to only capture a
226 fixed amount of memory's worth of events. Flight Data Recorder (FDR) mode works
227 very much like a plane's "black box" which keeps recording data to memory in a
228 fixed-size circular queue of buffers, and have the data available
229 programmatically until the buffers are finalized and flushed. To use FDR mode
230 on your application, you may set the ``xray_mode`` variable to ``xray-fdr`` in
231 the ``XRAY_OPTIONS`` environment variable. Additional options to the FDR mode
232 implementation can be provided in the ``XRAY_FDR_OPTIONS`` environment
233 variable. Programmatic configuration can be done by calling
234 ``__xray_log_init_mode("xray-fdr", <configuration string>)`` once it has been
235 selected/installed.
236
237 When the buffers are flushed to disk, the result is a binary trace format
238 described by `XRay FDR format <XRayFDRFormat.html>`_
239
240 When FDR mode is on, it will keep writing and recycling memory buffers until
241 the logging implementation is finalized -- at which point it can be flushed and
242 re-initialised later. To do this programmatically, we follow the workflow
243 provided below:
244
245 .. code-block:: c++
246
247   // Patch the sleds, if we haven't yet.
248   auto patch_status = __xray_patch();
249
250   // Maybe handle the patch_status errors.
251
252   // When we want to flush the log, we need to finalize it first, to give
253   // threads a chance to return buffers to the queue.
254   auto finalize_status = __xray_log_finalize();
255   if (finalize_status != XRAY_LOG_FINALIZED) {
256     // maybe retry, or bail out.
257   }
258
259   // At this point, we are sure that the log is finalized, so we may try
260   // flushing the log.
261   auto flush_status = __xray_log_flushLog();
262   if (flush_status != XRAY_LOG_FLUSHED) {
263     // maybe retry, or bail out.
264   }
265
266 The default settings for the FDR mode implementation will create logs named
267 similarly to the basic log implementation, but will have a different log
268 format. All the trace analysis tools (and the trace reading library) will
269 support all versions of the FDR mode format as we add more functionality and
270 record types in the future.
271
272   **NOTE:** We do not promise perpetual support for when we update the log
273   versions we support going forward. Deprecation of the formats will be
274   announced and discussed on the developers mailing list.
275
276 Trace Analysis Tools
277 --------------------
278
279 We currently have the beginnings of a trace analysis tool in LLVM, which can be
280 found in the ``tools/llvm-xray`` directory. The ``llvm-xray`` tool currently
281 supports the following subcommands:
282
283 - ``extract``: Extract the instrumentation map from a binary, and return it as
284   YAML.
285 - ``account``: Performs basic function call accounting statistics with various
286   options for sorting, and output formats (supports CSV, YAML, and
287   console-friendly TEXT).
288 - ``convert``: Converts an XRay log file from one format to another. We can
289   convert from binary XRay traces (both basic and FDR mode) to YAML,
290   `flame-graph <https://github.com/brendangregg/FlameGraph>`_ friendly text
291   formats, as well as `Chrome Trace Viewer (catapult)
292   <https://github.com/catapult-project/catapult>` formats.
293 - ``graph``: Generates a DOT graph of the function call relationships between
294   functions found in an XRay trace.
295 - ``stack``: Reconstructs function call stacks from a timeline of function
296   calls in an XRay trace.
297
298 These subcommands use various library components found as part of the XRay
299 libraries, distributed with the LLVM distribution. These are:
300
301 - ``llvm/XRay/Trace.h`` : A trace reading library for conveniently loading
302   an XRay trace of supported forms, into a convenient in-memory representation.
303   All the analysis tools that deal with traces use this implementation.
304 - ``llvm/XRay/Graph.h`` : A semi-generic graph type used by the graph
305   subcommand to conveniently represent a function call graph with statistics
306   associated with edges and vertices.
307 - ``llvm/XRay/InstrumentationMap.h``: A convenient tool for analyzing the
308   instrumentation map in XRay-instrumented object files and binaries. The
309   ``extract`` and ``stack`` subcommands uses this particular library.
310
311 Future Work
312 ===========
313
314 There are a number of ongoing efforts for expanding the toolset building around
315 the XRay instrumentation system.
316
317 Trace Analysis Tools
318 --------------------
319
320 - Work is in progress to integrate with or develop tools to visualize findings
321   from an XRay trace. Particularly, the ``stack`` tool is being expanded to
322   output formats that allow graphing and exploring the duration of time in each
323   call stack.
324 - With a large instrumented binary, the size of generated XRay traces can
325   quickly become unwieldy. We are working on integrating pruning techniques and
326   heuristics for the analysis tools to sift through the traces and surface only
327   relevant information.
328
329 More Platforms
330 --------------
331
332 We're looking forward to contributions to port XRay to more architectures and
333 operating systems.
334
335 .. References...
336
337 .. _`XRay whitepaper`: http://research.google.com/pubs/pub45287.html
338