blob: 0f6a42a2113f5e9748149c9e263a311fd63e1540 [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
Sylvestre Ledrubc5c3f52018-11-04 17:02:00 +000028Build LLVM/Clang with `CMake <https://llvm.org/docs/CMake.html>`_.
Alexey Samsonov778fc722015-12-04 17:30:29 +000029
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
Roman Lebedevbd1c0872019-01-15 09:44:25 +000075 of a misaligned reference. Also sanitizes assume_aligned-like attributes.
Alexey Samsonov778fc722015-12-04 17:30:29 +000076 - ``-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
Richard Smith9e52c432019-07-06 21:05:52 +000086 destination. Because the range of representable values for all
87 floating-point types supported by Clang is [-inf, +inf], the only
88 cases detected are conversions from floating point to integer types.
Alexey Samsonov778fc722015-12-04 17:30:29 +000089 - ``-fsanitize=float-divide-by-zero``: Floating point division by
Richard Smith9e52c432019-07-06 21:05:52 +000090 zero. This is undefined per the C and C++ standards, but is defined
91 by Clang (and by ISO/IEC/IEEE 60559 / IEEE 754) as producing either an
92 infinity or NaN value, so is not included in ``-fsanitize=undefined``.
Alexey Samsonov778fc722015-12-04 17:30:29 +000093 - ``-fsanitize=function``: Indirect call of a function through a
Vedant Kumard8ab8c22017-09-13 00:04:36 +000094 function pointer of the wrong type (Darwin/Linux, C++ and x86/x86_64
95 only).
Roman Lebedevdd403572018-10-11 09:09:50 +000096 - ``-fsanitize=implicit-unsigned-integer-truncation``,
97 ``-fsanitize=implicit-signed-integer-truncation``: Implicit conversion from
Roman Lebedevb69ba222018-07-30 18:58:30 +000098 integer of larger bit width to smaller bit width, if that results in data
99 loss. That is, if the demoted value, after casting back to the original
100 width, is not equal to the original value before the downcast.
Roman Lebedevdd403572018-10-11 09:09:50 +0000101 The ``-fsanitize=implicit-unsigned-integer-truncation`` handles conversions
102 between two ``unsigned`` types, while
103 ``-fsanitize=implicit-signed-integer-truncation`` handles the rest of the
104 conversions - when either one, or both of the types are signed.
105 Issues caught by these sanitizers are not undefined behavior,
Roman Lebedevb69ba222018-07-30 18:58:30 +0000106 but are often unintentional.
Roman Lebedev62debd802018-10-30 21:58:56 +0000107 - ``-fsanitize=implicit-integer-sign-change``: Implicit conversion between
108 integer types, if that changes the sign of the value. That is, if the the
109 original value was negative and the new value is positive (or zero),
110 or the original value was positive, and the new value is negative.
111 Issues caught by this sanitizer are not undefined behavior,
112 but are often unintentional.
Alexey Samsonov778fc722015-12-04 17:30:29 +0000113 - ``-fsanitize=integer-divide-by-zero``: Integer division by zero.
114 - ``-fsanitize=nonnull-attribute``: Passing null pointer as a function
115 parameter which is declared to never be null.
116 - ``-fsanitize=null``: Use of a null pointer or creation of a null
117 reference.
Vedant Kumar42c17ec2017-03-14 01:56:34 +0000118 - ``-fsanitize=nullability-arg``: Passing null as a function parameter
119 which is annotated with ``_Nonnull``.
120 - ``-fsanitize=nullability-assign``: Assigning null to an lvalue which
121 is annotated with ``_Nonnull``.
122 - ``-fsanitize=nullability-return``: Returning null from a function with
123 a return type annotated with ``_Nonnull``.
George Burgess IV58ebc662016-04-25 19:21:45 +0000124 - ``-fsanitize=object-size``: An attempt to potentially use bytes which
George Burgess IVa17674b2016-04-26 00:31:29 +0000125 the optimizer can determine are not part of the object being accessed.
126 This will also detect some types of undefined behavior that may not
127 directly access memory, but are provably incorrect given the size of
128 the objects involved, such as invalid downcasts and calling methods on
129 invalid pointers. These checks are made in terms of
130 ``__builtin_object_size``, and consequently may be able to detect more
131 problems at higher optimization levels.
Vedant Kumara125eb52017-06-01 19:22:18 +0000132 - ``-fsanitize=pointer-overflow``: Performing pointer arithmetic which
Roman Lebedev536b0ee2019-10-10 09:25:02 +0000133 overflows, or where either the old or new pointer value is a null pointer
134 (or in C, when they both are).
Alexey Samsonov778fc722015-12-04 17:30:29 +0000135 - ``-fsanitize=return``: In C++, reaching the end of a
136 value-returning function without returning a value.
137 - ``-fsanitize=returns-nonnull-attribute``: Returning null pointer
138 from a function which is declared to never return null.
139 - ``-fsanitize=shift``: Shift operators where the amount shifted is
140 greater or equal to the promoted bit-width of the left hand side
141 or less than zero, or where the left hand side is negative. For a
142 signed left shift, also checks for signed overflow in C, and for
143 unsigned overflow in C++. You can use ``-fsanitize=shift-base`` or
144 ``-fsanitize=shift-exponent`` to check only left-hand side or
145 right-hand side of shift operation, respectively.
Roman Lebedevb69ba222018-07-30 18:58:30 +0000146 - ``-fsanitize=signed-integer-overflow``: Signed integer overflow, where the
147 result of a signed integer computation cannot be represented in its type.
148 This includes all the checks covered by ``-ftrapv``, as well as checks for
149 signed division overflow (``INT_MIN/-1``), but not checks for
Roman Lebedev3a5d3562018-07-30 21:11:32 +0000150 lossy implicit conversions performed before the computation
Roman Lebedevb69ba222018-07-30 18:58:30 +0000151 (see ``-fsanitize=implicit-conversion``). Both of these two issues are
152 handled by ``-fsanitize=implicit-conversion`` group of checks.
Vedant Kumar09b5bfd2017-12-21 00:10:25 +0000153 - ``-fsanitize=unreachable``: If control flow reaches an unreachable
154 program point.
Roman Lebedevb69ba222018-07-30 18:58:30 +0000155 - ``-fsanitize=unsigned-integer-overflow``: Unsigned integer overflow, where
156 the result of an unsigned integer computation cannot be represented in its
157 type. Unlike signed integer overflow, this is not undefined behavior, but
158 it is often unintentional. This sanitizer does not check for lossy implicit
Roman Lebedev3a5d3562018-07-30 21:11:32 +0000159 conversions performed before such a computation
Roman Lebedevb69ba222018-07-30 18:58:30 +0000160 (see ``-fsanitize=implicit-conversion``).
Alexey Samsonov778fc722015-12-04 17:30:29 +0000161 - ``-fsanitize=vla-bound``: A variable-length array whose bound
162 does not evaluate to a positive value.
Vedant Kumarbbc953f2017-07-25 19:34:23 +0000163 - ``-fsanitize=vptr``: Use of an object whose vptr indicates that it is of
Vedant Kumarbbfdb7d2017-08-02 18:24:12 +0000164 the wrong dynamic type, or that its lifetime has not begun or has ended.
165 Incompatible with ``-fno-rtti``. Link must be performed by ``clang++``, not
166 ``clang``, to make sure C++-specific parts of the runtime library and C++
167 standard libraries are present.
Alexey Samsonov778fc722015-12-04 17:30:29 +0000168
169You can also use the following check groups:
170 - ``-fsanitize=undefined``: All of the checks listed above other than
Richard Smith9e52c432019-07-06 21:05:52 +0000171 ``float-divide-by-zero``, ``unsigned-integer-overflow``,
172 ``implicit-conversion``, and the ``nullability-*`` group of checks.
Alexey Samsonov778fc722015-12-04 17:30:29 +0000173 - ``-fsanitize=undefined-trap``: Deprecated alias of
174 ``-fsanitize=undefined``.
Roman Lebedev62debd802018-10-30 21:58:56 +0000175 - ``-fsanitize=implicit-integer-truncation``: Catches lossy integral
176 conversions. Enables ``implicit-signed-integer-truncation`` and
177 ``implicit-unsigned-integer-truncation``.
178 - ``-fsanitize=implicit-integer-arithmetic-value-change``: Catches implicit
179 conversions that change the arithmetic value of the integer. Enables
180 ``implicit-signed-integer-truncation`` and ``implicit-integer-sign-change``.
181 - ``-fsanitize=implicit-conversion``: Checks for suspicious
Richard Smith9e52c432019-07-06 21:05:52 +0000182 behavior of implicit conversions. Enables
Roman Lebedev62debd802018-10-30 21:58:56 +0000183 ``implicit-unsigned-integer-truncation``,
Richard Smith9e52c432019-07-06 21:05:52 +0000184 ``implicit-signed-integer-truncation``, and
Roman Lebedev62debd802018-10-30 21:58:56 +0000185 ``implicit-integer-sign-change``.
Alexey Samsonov778fc722015-12-04 17:30:29 +0000186 - ``-fsanitize=integer``: Checks for undefined or suspicious integer
187 behavior (e.g. unsigned integer overflow).
Roman Lebedevb69ba222018-07-30 18:58:30 +0000188 Enables ``signed-integer-overflow``, ``unsigned-integer-overflow``,
Roman Lebedev62debd802018-10-30 21:58:56 +0000189 ``shift``, ``integer-divide-by-zero``,
190 ``implicit-unsigned-integer-truncation``,
Richard Smith9e52c432019-07-06 21:05:52 +0000191 ``implicit-signed-integer-truncation``, and
Roman Lebedev62debd802018-10-30 21:58:56 +0000192 ``implicit-integer-sign-change``.
Vedant Kumar42c17ec2017-03-14 01:56:34 +0000193 - ``-fsanitize=nullability``: Enables ``nullability-arg``,
194 ``nullability-assign``, and ``nullability-return``. While violating
195 nullability does not have undefined behavior, it is often unintentional,
196 so UBSan offers to catch it.
Alexey Samsonov778fc722015-12-04 17:30:29 +0000197
Vedant Kumare42e5cf2017-06-16 18:38:43 +0000198Volatile
199--------
200
201The ``null``, ``alignment``, ``object-size``, and ``vptr`` checks do not apply
202to pointers to types with the ``volatile`` qualifier.
203
Vedant Kumar90c80a32017-09-11 21:37:05 +0000204Minimal Runtime
205===============
206
207There is a minimal UBSan runtime available suitable for use in production
208environments. This runtime has a small attack surface. It only provides very
Stephan Bergmanne2159962019-07-16 06:23:27 +0000209basic issue logging and deduplication, and does not support
210``-fsanitize=function`` and ``-fsanitize=vptr`` checking.
Vedant Kumar90c80a32017-09-11 21:37:05 +0000211
212To use the minimal runtime, add ``-fsanitize-minimal-runtime`` to the clang
213command line options. For example, if you're used to compiling with
214``-fsanitize=undefined``, you could enable the minimal runtime with
215``-fsanitize=undefined -fsanitize-minimal-runtime``.
216
Alexey Samsonov778fc722015-12-04 17:30:29 +0000217Stack traces and report symbolization
218=====================================
219If you want UBSan to print symbolized stack trace for each error report, you
220will need to:
221
222#. Compile with ``-g`` and ``-fno-omit-frame-pointer`` to get proper debug
223 information in your binary.
224#. Run your program with environment variable
225 ``UBSAN_OPTIONS=print_stacktrace=1``.
226#. Make sure ``llvm-symbolizer`` binary is in ``PATH``.
227
Vedant Kumar00d186a2019-07-29 22:54:43 +0000228Logging
229=======
230
231The default log file for diagnostics is "stderr". To log diagnostics to another
232file, you can set ``UBSAN_OPTIONS=log_path=...``.
233
Matt Morehouse520748f2018-06-27 18:24:46 +0000234Silencing Unsigned Integer Overflow
235===================================
236To silence reports from unsigned integer overflow, you can set
237``UBSAN_OPTIONS=silence_unsigned_overflow=1``. This feature, combined with
238``-fsanitize-recover=unsigned-integer-overflow``, is particularly useful for
239providing fuzzing signal without blowing up logs.
240
Alexey Samsonov778fc722015-12-04 17:30:29 +0000241Issue Suppression
242=================
243
244UndefinedBehaviorSanitizer is not expected to produce false positives.
245If you see one, look again; most likely it is a true positive!
246
247Disabling Instrumentation with ``__attribute__((no_sanitize("undefined")))``
248----------------------------------------------------------------------------
249
250You disable UBSan checks for particular functions with
251``__attribute__((no_sanitize("undefined")))``. You can use all values of
252``-fsanitize=`` flag in this attribute, e.g. if your function deliberately
253contains possible signed integer overflow, you can use
254``__attribute__((no_sanitize("signed-integer-overflow")))``.
255
256This attribute may not be
257supported by other compilers, so consider using it together with
258``#if defined(__clang__)``.
259
260Suppressing Errors in Recompiled Code (Blacklist)
261-------------------------------------------------
262
263UndefinedBehaviorSanitizer supports ``src`` and ``fun`` entity types in
264:doc:`SanitizerSpecialCaseList`, that can be used to suppress error reports
265in the specified source files or functions.
266
Alexey Samsonov7f5b2d02016-01-29 23:07:14 +0000267Runtime suppressions
268--------------------
269
270Sometimes you can suppress UBSan error reports for specific files, functions,
271or libraries without recompiling the code. You need to pass a path to
272suppression file in a ``UBSAN_OPTIONS`` environment variable.
273
274.. code-block:: bash
275
276 UBSAN_OPTIONS=suppressions=MyUBSan.supp
277
278You need to specify a :ref:`check <ubsan-checks>` you are suppressing and the
279bug location. For example:
280
281.. code-block:: bash
282
283 signed-integer-overflow:file-with-known-overflow.cpp
284 alignment:function_doing_unaligned_access
285 vptr:shared_object_with_vptr_failures.so
286
287There are several limitations:
288
289* Sometimes your binary must have enough debug info and/or symbol table, so
290 that the runtime could figure out source file or function name to match
291 against the suppression.
292* It is only possible to suppress recoverable checks. For the example above,
293 you can additionally pass
294 ``-fsanitize-recover=signed-integer-overflow,alignment,vptr``, although
295 most of UBSan checks are recoverable by default.
296* Check groups (like ``undefined``) can't be used in suppressions file, only
297 fine-grained checks are supported.
298
Alexey Samsonov778fc722015-12-04 17:30:29 +0000299Supported Platforms
300===================
301
Reid Kleckner0bbbc552018-11-27 03:55:15 +0000302UndefinedBehaviorSanitizer is supported on the following operating systems:
Alexey Samsonov778fc722015-12-04 17:30:29 +0000303
304* Android
305* Linux
David Carlier59a339ab2018-07-25 13:55:06 +0000306* NetBSD
Alexey Samsonov778fc722015-12-04 17:30:29 +0000307* FreeBSD
David Carlier59a339ab2018-07-25 13:55:06 +0000308* OpenBSD
J. Ryan Stinnettd45eaf92019-05-30 16:46:22 +0000309* macOS
Reid Kleckner0bbbc552018-11-27 03:55:15 +0000310* Windows
311
312The runtime library is relatively portable and platform independent. If the OS
313you need is not listed above, UndefinedBehaviorSanitizer may already work for
314it, or could be made to work with a minor porting effort.
Alexey Samsonov778fc722015-12-04 17:30:29 +0000315
Alexey Samsonov778fc722015-12-04 17:30:29 +0000316Current Status
317==============
318
319UndefinedBehaviorSanitizer is available on selected platforms starting from LLVM
3203.3. The test suite is integrated into the CMake build and can be run with
321``check-ubsan`` command.
322
Filipe Cabecinhasab731f72016-05-12 16:51:36 +0000323Additional Configuration
324========================
325
326UndefinedBehaviorSanitizer adds static check data for each check unless it is
327in trap mode. This check data includes the full file name. The option
328``-fsanitize-undefined-strip-path-components=N`` can be used to trim this
329information. If ``N`` is positive, file information emitted by
330UndefinedBehaviorSanitizer will drop the first ``N`` components from the file
331path. If ``N`` is negative, the last ``N`` components will be kept.
332
333Example
334-------
335
336For a file called ``/code/library/file.cpp``, here is what would be emitted:
Reid Kleckner0bbbc552018-11-27 03:55:15 +0000337
Filipe Cabecinhasab731f72016-05-12 16:51:36 +0000338* Default (No flag, or ``-fsanitize-undefined-strip-path-components=0``): ``/code/library/file.cpp``
339* ``-fsanitize-undefined-strip-path-components=1``: ``code/library/file.cpp``
340* ``-fsanitize-undefined-strip-path-components=2``: ``library/file.cpp``
341* ``-fsanitize-undefined-strip-path-components=-1``: ``file.cpp``
342* ``-fsanitize-undefined-strip-path-components=-2``: ``library/file.cpp``
343
Alexey Samsonov778fc722015-12-04 17:30:29 +0000344More Information
345================
346
347* From LLVM project blog:
348 `What Every C Programmer Should Know About Undefined Behavior
349 <http://blog.llvm.org/2011/05/what-every-c-programmer-should-know.html>`_
350* From John Regehr's *Embedded in Academia* blog:
351 `A Guide to Undefined Behavior in C and C++
Eugene Zelenkoadcb3f52019-01-23 20:39:07 +0000352 <https://blog.regehr.org/archives/213>`_