blob: 8dd9157e81fbb8aee19d3ac43538619065a7bd61 [file] [log] [blame]
Alexey Samsonov778fc722015-12-04 17:30:29 +00001==========================
2UndefinedBehaviorSanitizer
3==========================
4
5.. contents::
6 :local:
7
8Introduction
9============
10
11UndefinedBehaviorSanitizer (UBSan) is a fast undefined behavior detector.
12UBSan modifies the program at compile-time to catch various kinds of undefined
13behavior during program execution, for example:
14
15* Using misaligned or null pointer
16* Signed integer overflow
17* Conversion to, from, or between floating-point types which would
18 overflow the destination
19
20See the full list of available :ref:`checks <ubsan-checks>` below.
21
22UBSan has an optional run-time library which provides better error reporting.
23The checks have small runtime cost and no impact on address space layout or ABI.
24
25How to build
26============
27
28Build LLVM/Clang with `CMake <http://llvm.org/docs/CMake.html>`_.
29
30Usage
31=====
32
33Use ``clang++`` to compile and link your program with ``-fsanitize=undefined``
34flag. Make sure to use ``clang++`` (not ``ld``) as a linker, so that your
35executable is linked with proper UBSan runtime libraries. You can use ``clang``
36instead of ``clang++`` if you're compiling/linking C code.
37
38.. code-block:: console
39
40 % cat test.cc
41 int main(int argc, char **argv) {
42 int k = 0x7fffffff;
43 k += argc;
44 return 0;
45 }
46 % clang++ -fsanitize=undefined test.cc
47 % ./a.out
48 test.cc:3:5: runtime error: signed integer overflow: 2147483647 + 1 cannot be represented in type 'int'
49
50You can enable only a subset of :ref:`checks <ubsan-checks>` offered by UBSan,
51and define the desired behavior for each kind of check:
52
Vedant Kumar3cbce5d2017-03-20 21:40:58 +000053* ``-fsanitize=...``: print a verbose error report and continue execution (default);
54* ``-fno-sanitize-recover=...``: print a verbose error report and exit the program;
55* ``-fsanitize-trap=...``: execute a trap instruction (doesn't require UBSan run-time support).
Alexey Samsonov778fc722015-12-04 17:30:29 +000056
57For example if you compile/link your program as:
58
59.. code-block:: console
60
61 % clang++ -fsanitize=signed-integer-overflow,null,alignment -fno-sanitize-recover=null -fsanitize-trap=alignment
62
63the program will continue execution after signed integer overflows, exit after
64the first invalid use of a null pointer, and trap after the first use of misaligned
65pointer.
66
67.. _ubsan-checks:
68
Nick Lewyckyd8d49862016-09-20 18:37:25 +000069Available checks
70================
Alexey Samsonov778fc722015-12-04 17:30:29 +000071
72Available checks are:
73
74 - ``-fsanitize=alignment``: Use of a misaligned pointer or creation
75 of a misaligned reference.
76 - ``-fsanitize=bool``: Load of a ``bool`` value which is neither
77 ``true`` nor ``false``.
Vedant Kumar10c31022017-07-29 00:19:51 +000078 - ``-fsanitize=builtin``: Passing invalid values to compiler builtins.
Alexey Samsonov778fc722015-12-04 17:30:29 +000079 - ``-fsanitize=bounds``: Out of bounds array indexing, in cases
80 where the array bound can be statically determined.
81 - ``-fsanitize=enum``: Load of a value of an enumerated type which
82 is not in the range of representable values for that enumerated
83 type.
84 - ``-fsanitize=float-cast-overflow``: Conversion to, from, or
85 between floating-point types which would overflow the
86 destination.
87 - ``-fsanitize=float-divide-by-zero``: Floating point division by
88 zero.
89 - ``-fsanitize=function``: Indirect call of a function through a
Vedant Kumard8ab8c22017-09-13 00:04:36 +000090 function pointer of the wrong type (Darwin/Linux, C++ and x86/x86_64
91 only).
Alexey Samsonov778fc722015-12-04 17:30:29 +000092 - ``-fsanitize=integer-divide-by-zero``: Integer division by zero.
93 - ``-fsanitize=nonnull-attribute``: Passing null pointer as a function
94 parameter which is declared to never be null.
95 - ``-fsanitize=null``: Use of a null pointer or creation of a null
96 reference.
Vedant Kumar42c17ec2017-03-14 01:56:34 +000097 - ``-fsanitize=nullability-arg``: Passing null as a function parameter
98 which is annotated with ``_Nonnull``.
99 - ``-fsanitize=nullability-assign``: Assigning null to an lvalue which
100 is annotated with ``_Nonnull``.
101 - ``-fsanitize=nullability-return``: Returning null from a function with
102 a return type annotated with ``_Nonnull``.
George Burgess IV58ebc662016-04-25 19:21:45 +0000103 - ``-fsanitize=object-size``: An attempt to potentially use bytes which
George Burgess IVa17674b2016-04-26 00:31:29 +0000104 the optimizer can determine are not part of the object being accessed.
105 This will also detect some types of undefined behavior that may not
106 directly access memory, but are provably incorrect given the size of
107 the objects involved, such as invalid downcasts and calling methods on
108 invalid pointers. These checks are made in terms of
109 ``__builtin_object_size``, and consequently may be able to detect more
110 problems at higher optimization levels.
Vedant Kumara125eb52017-06-01 19:22:18 +0000111 - ``-fsanitize=pointer-overflow``: Performing pointer arithmetic which
112 overflows.
Alexey Samsonov778fc722015-12-04 17:30:29 +0000113 - ``-fsanitize=return``: In C++, reaching the end of a
114 value-returning function without returning a value.
115 - ``-fsanitize=returns-nonnull-attribute``: Returning null pointer
116 from a function which is declared to never return null.
117 - ``-fsanitize=shift``: Shift operators where the amount shifted is
118 greater or equal to the promoted bit-width of the left hand side
119 or less than zero, or where the left hand side is negative. For a
120 signed left shift, also checks for signed overflow in C, and for
121 unsigned overflow in C++. You can use ``-fsanitize=shift-base`` or
122 ``-fsanitize=shift-exponent`` to check only left-hand side or
123 right-hand side of shift operation, respectively.
124 - ``-fsanitize=signed-integer-overflow``: Signed integer overflow,
125 including all the checks added by ``-ftrapv``, and checking for
126 overflow in signed division (``INT_MIN / -1``).
Vedant Kumar09b5bfd2017-12-21 00:10:25 +0000127 - ``-fsanitize=unreachable``: If control flow reaches an unreachable
128 program point.
Alexey Samsonov778fc722015-12-04 17:30:29 +0000129 - ``-fsanitize=unsigned-integer-overflow``: Unsigned integer
Nico Weber614e60d2017-02-27 21:27:07 +0000130 overflows. Note that unlike signed integer overflow, unsigned integer
131 is not undefined behavior. However, while it has well-defined semantics,
132 it is often unintentional, so UBSan offers to catch it.
Alexey Samsonov778fc722015-12-04 17:30:29 +0000133 - ``-fsanitize=vla-bound``: A variable-length array whose bound
134 does not evaluate to a positive value.
Vedant Kumarbbc953f2017-07-25 19:34:23 +0000135 - ``-fsanitize=vptr``: Use of an object whose vptr indicates that it is of
Vedant Kumarbbfdb7d2017-08-02 18:24:12 +0000136 the wrong dynamic type, or that its lifetime has not begun or has ended.
137 Incompatible with ``-fno-rtti``. Link must be performed by ``clang++``, not
138 ``clang``, to make sure C++-specific parts of the runtime library and C++
139 standard libraries are present.
Alexey Samsonov778fc722015-12-04 17:30:29 +0000140
141You can also use the following check groups:
142 - ``-fsanitize=undefined``: All of the checks listed above other than
Vedant Kumar42c17ec2017-03-14 01:56:34 +0000143 ``unsigned-integer-overflow`` and the ``nullability-*`` checks.
Alexey Samsonov778fc722015-12-04 17:30:29 +0000144 - ``-fsanitize=undefined-trap``: Deprecated alias of
145 ``-fsanitize=undefined``.
146 - ``-fsanitize=integer``: Checks for undefined or suspicious integer
147 behavior (e.g. unsigned integer overflow).
Vedant Kumar42c17ec2017-03-14 01:56:34 +0000148 - ``-fsanitize=nullability``: Enables ``nullability-arg``,
149 ``nullability-assign``, and ``nullability-return``. While violating
150 nullability does not have undefined behavior, it is often unintentional,
151 so UBSan offers to catch it.
Alexey Samsonov778fc722015-12-04 17:30:29 +0000152
Vedant Kumare42e5cf2017-06-16 18:38:43 +0000153Volatile
154--------
155
156The ``null``, ``alignment``, ``object-size``, and ``vptr`` checks do not apply
157to pointers to types with the ``volatile`` qualifier.
158
Vedant Kumar90c80a32017-09-11 21:37:05 +0000159Minimal Runtime
160===============
161
162There is a minimal UBSan runtime available suitable for use in production
163environments. This runtime has a small attack surface. It only provides very
164basic issue logging and deduplication, and does not support ``-fsanitize=vptr``
165checking.
166
167To use the minimal runtime, add ``-fsanitize-minimal-runtime`` to the clang
168command line options. For example, if you're used to compiling with
169``-fsanitize=undefined``, you could enable the minimal runtime with
170``-fsanitize=undefined -fsanitize-minimal-runtime``.
171
Alexey Samsonov778fc722015-12-04 17:30:29 +0000172Stack traces and report symbolization
173=====================================
174If you want UBSan to print symbolized stack trace for each error report, you
175will need to:
176
177#. Compile with ``-g`` and ``-fno-omit-frame-pointer`` to get proper debug
178 information in your binary.
179#. Run your program with environment variable
180 ``UBSAN_OPTIONS=print_stacktrace=1``.
181#. Make sure ``llvm-symbolizer`` binary is in ``PATH``.
182
Matt Morehouse520748f2018-06-27 18:24:46 +0000183Silencing Unsigned Integer Overflow
184===================================
185To silence reports from unsigned integer overflow, you can set
186``UBSAN_OPTIONS=silence_unsigned_overflow=1``. This feature, combined with
187``-fsanitize-recover=unsigned-integer-overflow``, is particularly useful for
188providing fuzzing signal without blowing up logs.
189
Alexey Samsonov778fc722015-12-04 17:30:29 +0000190Issue Suppression
191=================
192
193UndefinedBehaviorSanitizer is not expected to produce false positives.
194If you see one, look again; most likely it is a true positive!
195
196Disabling Instrumentation with ``__attribute__((no_sanitize("undefined")))``
197----------------------------------------------------------------------------
198
199You disable UBSan checks for particular functions with
200``__attribute__((no_sanitize("undefined")))``. You can use all values of
201``-fsanitize=`` flag in this attribute, e.g. if your function deliberately
202contains possible signed integer overflow, you can use
203``__attribute__((no_sanitize("signed-integer-overflow")))``.
204
205This attribute may not be
206supported by other compilers, so consider using it together with
207``#if defined(__clang__)``.
208
209Suppressing Errors in Recompiled Code (Blacklist)
210-------------------------------------------------
211
212UndefinedBehaviorSanitizer supports ``src`` and ``fun`` entity types in
213:doc:`SanitizerSpecialCaseList`, that can be used to suppress error reports
214in the specified source files or functions.
215
Alexey Samsonov7f5b2d02016-01-29 23:07:14 +0000216Runtime suppressions
217--------------------
218
219Sometimes you can suppress UBSan error reports for specific files, functions,
220or libraries without recompiling the code. You need to pass a path to
221suppression file in a ``UBSAN_OPTIONS`` environment variable.
222
223.. code-block:: bash
224
225 UBSAN_OPTIONS=suppressions=MyUBSan.supp
226
227You need to specify a :ref:`check <ubsan-checks>` you are suppressing and the
228bug location. For example:
229
230.. code-block:: bash
231
232 signed-integer-overflow:file-with-known-overflow.cpp
233 alignment:function_doing_unaligned_access
234 vptr:shared_object_with_vptr_failures.so
235
236There are several limitations:
237
238* Sometimes your binary must have enough debug info and/or symbol table, so
239 that the runtime could figure out source file or function name to match
240 against the suppression.
241* It is only possible to suppress recoverable checks. For the example above,
242 you can additionally pass
243 ``-fsanitize-recover=signed-integer-overflow,alignment,vptr``, although
244 most of UBSan checks are recoverable by default.
245* Check groups (like ``undefined``) can't be used in suppressions file, only
246 fine-grained checks are supported.
247
Alexey Samsonov778fc722015-12-04 17:30:29 +0000248Supported Platforms
249===================
250
251UndefinedBehaviorSanitizer is supported on the following OS:
252
253* Android
254* Linux
255* FreeBSD
256* OS X 10.6 onwards
257
258and for the following architectures:
259
260* i386/x86\_64
261* ARM
262* AArch64
263* PowerPC64
264* MIPS/MIPS64
265
266Current Status
267==============
268
269UndefinedBehaviorSanitizer is available on selected platforms starting from LLVM
2703.3. The test suite is integrated into the CMake build and can be run with
271``check-ubsan`` command.
272
Filipe Cabecinhasab731f72016-05-12 16:51:36 +0000273Additional Configuration
274========================
275
276UndefinedBehaviorSanitizer adds static check data for each check unless it is
277in trap mode. This check data includes the full file name. The option
278``-fsanitize-undefined-strip-path-components=N`` can be used to trim this
279information. If ``N`` is positive, file information emitted by
280UndefinedBehaviorSanitizer will drop the first ``N`` components from the file
281path. If ``N`` is negative, the last ``N`` components will be kept.
282
283Example
284-------
285
286For a file called ``/code/library/file.cpp``, here is what would be emitted:
287* Default (No flag, or ``-fsanitize-undefined-strip-path-components=0``): ``/code/library/file.cpp``
288* ``-fsanitize-undefined-strip-path-components=1``: ``code/library/file.cpp``
289* ``-fsanitize-undefined-strip-path-components=2``: ``library/file.cpp``
290* ``-fsanitize-undefined-strip-path-components=-1``: ``file.cpp``
291* ``-fsanitize-undefined-strip-path-components=-2``: ``library/file.cpp``
292
Alexey Samsonov778fc722015-12-04 17:30:29 +0000293More Information
294================
295
296* From LLVM project blog:
297 `What Every C Programmer Should Know About Undefined Behavior
298 <http://blog.llvm.org/2011/05/what-every-c-programmer-should-know.html>`_
299* From John Regehr's *Embedded in Academia* blog:
300 `A Guide to Undefined Behavior in C and C++
301 <http://blog.regehr.org/archives/213>`_