Debian Codegraph @

clang/docs/UndefinedBehaviorSanitizer.rst

raw
1 ==========================
2 UndefinedBehaviorSanitizer
3 ==========================
4
5 .. contents::
6 :local:
7
8 Introduction
9 ============
10
11 UndefinedBehaviorSanitizer (UBSan) is a fast undefined behavior detector.
12 UBSan modifies the program at compile-time to catch various kinds of undefined
13 behavior during program execution, for example:
14
15 * Array subscript out of bounds, where the bounds can be statically determined
16 * Bitwise shifts that are out of bounds for their data type
17 * Dereferencing misaligned or null pointers
18 * Signed integer overflow
19 * Conversion to, from, or between floating-point types which would
20 overflow the destination
21
22 See the full list of available :ref:`checks <ubsan-checks>` below.
23
24 UBSan has an optional run-time library which provides better error reporting.
25 The checks have small runtime cost and no impact on address space layout or ABI.
26
27 How to build
28 ============
29
30 Build LLVM/Clang with `CMake <https://llvm.org/docs/CMake.html>`_.
31
32 Usage
33 =====
34
35 Use ``clang++`` to compile and link your program with the ``-fsanitize=undefined``
36 option. Make sure to use ``clang++`` (not ``ld``) as a linker, so that your
37 executable is linked with proper UBSan runtime libraries, unless all enabled
38 checks use trap mode. You can use ``clang`` instead of ``clang++`` if you're
39 compiling/linking C code.
40
41 .. code-block:: console
42
43 % cat test.cc
44 int main(int argc, char **argv) {
45 int k = 0x7fffffff;
46 k += argc;
47 return 0;
48 }
49 % clang++ -fsanitize=undefined test.cc
50 % ./a.out
51 test.cc:3:5: runtime error: signed integer overflow: 2147483647 + 1 cannot be represented in type 'int'
52
53 You can use ``-fsanitize=...`` and ``-fno-sanitize=`` to enable and disable one
54 check or one check group. For an individual check, the last option that enabling
55 or disabling it wins.
56
57 .. code-block:: console
58
59 # Enable all checks in the "undefined" group, but disable "alignment".
60 % clang -fsanitize=undefined -fno-sanitize=alignment a.c
61
62 # Enable just "alignment".
63 % clang -fsanitize=alignment a.c
64
65 # The same. -fno-sanitize=undefined nullifies the previous -fsanitize=undefined.
66 % clang -fsanitize=undefined -fno-sanitize=undefined -fsanitize=alignment a.c
67
68 For most checks (:ref:`checks <ubsan-checks>`), the instrumented program prints
69 a verbose error report and continues execution upon a failed check.
70 You can use the following options to change the error reporting behavior:
71
72 * ``-fno-sanitize-recover=...``: print a verbose error report and exit the program;
73 * ``-fsanitize-trap=...``: execute a trap instruction (doesn't require UBSan
74 run-time support). If the signal is not caught, the program will typically
75 terminate due to a ``SIGILL`` or ``SIGTRAP`` signal.
76
77 For example:
78
79 .. code-block:: console
80
81 % clang++ -fsanitize=signed-integer-overflow,null,alignment -fno-sanitize-recover=null -fsanitize-trap=alignment a.cc
82
83 The program will continue execution after signed integer overflows, exit after
84 the first invalid use of a null pointer, and trap after the first use of misaligned
85 pointer.
86
87 .. code-block:: console
88
89 % clang++ -fsanitize=undefined -fsanitize-trap=all a.cc
90
91 All checks in the "undefined" group are put into trap mode. Since no check
92 needs run-time support, the UBSan run-time library it not linked. Note that
93 some other sanitizers also support trap mode and ``-fsanitize-trap=all``
94 enables trap mode for them.
95
96 .. code-block:: console
97
98 % clang -fsanitize-trap=undefined -fsanitize-recover=all a.c
99
100 ``-fsanitize-trap=`` and ``-fsanitize-recover=`` are a no-op in the absence of
101 a ``-fsanitize=`` option. There is no unused command line option warning.
102
103 .. _ubsan-checks:
104
105 Available checks
106 ================
107
108 Available checks are:
109
110 - ``-fsanitize=alignment``: Use of a misaligned pointer or creation
111 of a misaligned reference. Also sanitizes assume_aligned-like attributes.
112 - ``-fsanitize=bool``: Load of a ``bool`` value which is neither
113 ``true`` nor ``false``.
114 - ``-fsanitize=builtin``: Passing invalid values to compiler builtins.
115 - ``-fsanitize=bounds``: Out of bounds array indexing, in cases
116 where the array bound can be statically determined. The check includes
117 ``-fsanitize=array-bounds`` and ``-fsanitize=local-bounds``. Note that
118 ``-fsanitize=local-bounds`` is not included in ``-fsanitize=undefined``.
119 - ``-fsanitize=enum``: Load of a value of an enumerated type which
120 is not in the range of representable values for that enumerated
121 type.
122 - ``-fsanitize=float-cast-overflow``: Conversion to, from, or
123 between floating-point types which would overflow the
124 destination. Because the range of representable values for all
125 floating-point types supported by Clang is [-inf, +inf], the only
126 cases detected are conversions from floating point to integer types.
127 - ``-fsanitize=float-divide-by-zero``: Floating point division by
128 zero. This is undefined per the C and C++ standards, but is defined
129 by Clang (and by ISO/IEC/IEEE 60559 / IEEE 754) as producing either an
130 infinity or NaN value, so is not included in ``-fsanitize=undefined``.
131 - ``-fsanitize=function``: Indirect call of a function through a
132 function pointer of the wrong type.
133 - ``-fsanitize=implicit-unsigned-integer-truncation``,
134 ``-fsanitize=implicit-signed-integer-truncation``: Implicit conversion from
135 integer of larger bit width to smaller bit width, if that results in data
136 loss. That is, if the demoted value, after casting back to the original
137 width, is not equal to the original value before the downcast.
138 The ``-fsanitize=implicit-unsigned-integer-truncation`` handles conversions
139 between two ``unsigned`` types, while
140 ``-fsanitize=implicit-signed-integer-truncation`` handles the rest of the
141 conversions - when either one, or both of the types are signed.
142 Issues caught by these sanitizers are not undefined behavior,
143 but are often unintentional.
144 - ``-fsanitize=implicit-integer-sign-change``: Implicit conversion between
145 integer types, if that changes the sign of the value. That is, if the
146 original value was negative and the new value is positive (or zero),
147 or the original value was positive, and the new value is negative.
148 Issues caught by this sanitizer are not undefined behavior,
149 but are often unintentional.
150 - ``-fsanitize=integer-divide-by-zero``: Integer division by zero.
151 - ``-fsanitize=implicit-bitfield-conversion``: Implicit conversion from
152 integer of larger bit width to smaller bitfield, if that results in data
153 loss. This includes unsigned/signed truncations and sign changes, similarly
154 to how the ``-fsanitize=implicit-integer-conversion`` group works, but
155 explicitly for bitfields.
156 - ``-fsanitize=nonnull-attribute``: Passing null pointer as a function
157 parameter which is declared to never be null.
158 - ``-fsanitize=null``: Use of a null pointer or creation of a null
159 reference.
160 - ``-fsanitize=nullability-arg``: Passing null as a function parameter
161 which is annotated with ``_Nonnull``.
162 - ``-fsanitize=nullability-assign``: Assigning null to an lvalue which
163 is annotated with ``_Nonnull``.
164 - ``-fsanitize=nullability-return``: Returning null from a function with
165 a return type annotated with ``_Nonnull``.
166 - ``-fsanitize=objc-cast``: Invalid implicit cast of an ObjC object pointer
167 to an incompatible type. This is often unintentional, but is not undefined
168 behavior, therefore the check is not a part of the ``undefined`` group.
169 Currently only supported on Darwin.
170 - ``-fsanitize=object-size``: An attempt to potentially use bytes which
171 the optimizer can determine are not part of the object being accessed.
172 This will also detect some types of undefined behavior that may not
173 directly access memory, but are provably incorrect given the size of
174 the objects involved, such as invalid downcasts and calling methods on
175 invalid pointers. These checks are made in terms of
176 ``__builtin_object_size``, and consequently may be able to detect more
177 problems at higher optimization levels.
178 - ``-fsanitize=pointer-overflow``: Performing pointer arithmetic which
179 overflows, or where either the old or new pointer value is a null pointer
180 (excluding the case where both are null pointers).
181 - ``-fsanitize=return``: In C++, reaching the end of a
182 value-returning function without returning a value.
183 - ``-fsanitize=returns-nonnull-attribute``: Returning null pointer
184 from a function which is declared to never return null.
185 - ``-fsanitize=shift``: Shift operators where the amount shifted is
186 greater or equal to the promoted bit-width of the left hand side
187 or less than zero, or where the left hand side is negative. For a
188 signed left shift, also checks for signed overflow in C, and for
189 unsigned overflow in C++. You can use ``-fsanitize=shift-base`` or
190 ``-fsanitize=shift-exponent`` to check only left-hand side or
191 right-hand side of shift operation, respectively.
192 - ``-fsanitize=unsigned-shift-base``: check that an unsigned left-hand side of
193 a left shift operation doesn't overflow. Issues caught by this sanitizer are
194 not undefined behavior, but are often unintentional.
195 - ``-fsanitize=signed-integer-overflow``: Signed integer overflow, where the
196 result of a signed integer computation cannot be represented in its type.
197 This includes all the checks covered by ``-ftrapv``, as well as checks for
198 signed division overflow (``INT_MIN/-1``). Note that checks are still
199 added even when ``-fwrapv`` is enabled. This sanitizer does not check for
200 lossy implicit conversions performed before the computation (see
201 ``-fsanitize=implicit-integer-conversion``). Both of these two issues are handled
202 by ``-fsanitize=implicit-integer-conversion`` group of checks.
203 - ``-fsanitize=unreachable``: If control flow reaches an unreachable
204 program point.
205 - ``-fsanitize=unsigned-integer-overflow``: Unsigned integer overflow, where
206 the result of an unsigned integer computation cannot be represented in its
207 type. Unlike signed integer overflow, this is not undefined behavior, but
208 it is often unintentional. This sanitizer does not check for lossy implicit
209 conversions performed before such a computation
210 (see ``-fsanitize=implicit-integer-conversion``).
211 - ``-fsanitize=vla-bound``: A variable-length array whose bound
212 does not evaluate to a positive value.
213 - ``-fsanitize=vptr``: Use of an object whose vptr indicates that it is of
214 the wrong dynamic type, or that its lifetime has not begun or has ended.
215 Incompatible with ``-fno-rtti``. Link must be performed by ``clang++``, not
216 ``clang``, to make sure C++-specific parts of the runtime library and C++
217 standard libraries are present. The check is not a part of the ``undefined``
218 group. Also it does not support ``-fsanitize-trap=vptr``.
219
220 You can also use the following check groups:
221 - ``-fsanitize=undefined``: All of the checks listed above other than
222 ``float-divide-by-zero``, ``unsigned-integer-overflow``,
223 ``implicit-conversion``, ``local-bounds``, ``vptr`` and the
224 ``nullability-*`` group of checks.
225 - ``-fsanitize=undefined-trap``: Deprecated alias of
226 ``-fsanitize=undefined``.
227 - ``-fsanitize=implicit-integer-truncation``: Catches lossy integral
228 conversions. Enables ``implicit-signed-integer-truncation`` and
229 ``implicit-unsigned-integer-truncation``.
230 - ``-fsanitize=implicit-integer-arithmetic-value-change``: Catches implicit
231 conversions that change the arithmetic value of the integer. Enables
232 ``implicit-signed-integer-truncation`` and ``implicit-integer-sign-change``.
233 - ``-fsanitize=implicit-integer-conversion``: Checks for suspicious
234 behavior of implicit integer conversions. Enables
235 ``implicit-unsigned-integer-truncation``,
236 ``implicit-signed-integer-truncation``, and
237 ``implicit-integer-sign-change``.
238 - ``-fsanitize=implicit-conversion``: Checks for suspicious
239 behavior of implicit conversions. Enables
240 ``implicit-integer-conversion``, and
241 ``implicit-bitfield-conversion``.
242 - ``-fsanitize=integer``: Checks for undefined or suspicious integer
243 behavior (e.g. unsigned integer overflow).
244 Enables ``signed-integer-overflow``, ``unsigned-integer-overflow``,
245 ``shift``, ``integer-divide-by-zero``,
246 ``implicit-unsigned-integer-truncation``,
247 ``implicit-signed-integer-truncation``, and
248 ``implicit-integer-sign-change``.
249 - ``-fsanitize=nullability``: Enables ``nullability-arg``,
250 ``nullability-assign``, and ``nullability-return``. While violating
251 nullability does not have undefined behavior, it is often unintentional,
252 so UBSan offers to catch it.
253
254 Volatile
255 --------
256
257 The ``null``, ``alignment``, ``object-size``, ``local-bounds``, and ``vptr`` checks do not apply
258 to pointers to types with the ``volatile`` qualifier.
259
260 .. _minimal-runtime:
261
262 Minimal Runtime
263 ===============
264
265 There is a minimal UBSan runtime available suitable for use in production
266 environments. This runtime has a small attack surface. It only provides very
267 basic issue logging and deduplication, and does not support ``-fsanitize=vptr``
268 checking.
269
270 To use the minimal runtime, add ``-fsanitize-minimal-runtime`` to the clang
271 command line options. For example, if you're used to compiling with
272 ``-fsanitize=undefined``, you could enable the minimal runtime with
273 ``-fsanitize=undefined -fsanitize-minimal-runtime``.
274
275 Stack traces and report symbolization
276 =====================================
277 If you want UBSan to print symbolized stack trace for each error report, you
278 will need to:
279
280 #. Compile with ``-g``, ``-fno-sanitize-merge`` and ``-fno-omit-frame-pointer``
281 to get proper debug information in your binary.
282 #. Run your program with environment variable
283 ``UBSAN_OPTIONS=print_stacktrace=1``.
284 #. Make sure ``llvm-symbolizer`` binary is in ``PATH``.
285
286 Logging
287 =======
288
289 The default log file for diagnostics is "stderr". To log diagnostics to another
290 file, you can set ``UBSAN_OPTIONS=log_path=...``.
291
292 Silencing Unsigned Integer Overflow
293 ===================================
294 To silence reports from unsigned integer overflow, you can set
295 ``UBSAN_OPTIONS=silence_unsigned_overflow=1``. This feature, combined with
296 ``-fsanitize-recover=unsigned-integer-overflow``, is particularly useful for
297 providing fuzzing signal without blowing up logs.
298
299 Disabling instrumentation for common overflow patterns
300 ------------------------------------------------------
301
302 There are certain overflow-dependent or overflow-prone code patterns which
303 produce a lot of noise for integer overflow/truncation sanitizers. Negated
304 unsigned constants, post-decrements in a while loop condition and simple
305 overflow checks are accepted and pervasive code patterns. However, the signal
306 received from sanitizers instrumenting these code patterns may be too noisy for
307 some projects. To disable instrumentation for these common patterns one should
308 use ``-fsanitize-undefined-ignore-overflow-pattern=``.
309
310 Currently, this option supports three overflow-dependent code idioms:
311
312 ``negated-unsigned-const``
313
314 .. code-block:: c++
315
316 /// -fsanitize-undefined-ignore-overflow-pattern=negated-unsigned-const
317 unsigned long foo = -1UL; // No longer causes a negation overflow warning
318 unsigned long bar = -2UL; // and so on...
319
320 ``unsigned-post-decr-while``
321
322 .. code-block:: c++
323
324 /// -fsanitize-undefined-ignore-overflow-pattern=unsigned-post-decr-while
325 unsigned char count = 16;
326 while (count--) { /* ... */ } // No longer causes unsigned-integer-overflow sanitizer to trip
327
328 ``add-signed-overflow-test,add-unsigned-overflow-test``
329
330 .. code-block:: c++
331
332 /// -fsanitize-undefined-ignore-overflow-pattern=add-(signed|unsigned)-overflow-test
333 if (base + offset < base) { /* ... */ } // The pattern of `a + b < a`, and other re-orderings,
334 // won't be instrumented (signed or unsigned types)
335
336 .. list-table:: Overflow Pattern Types
337 :widths: 30 50
338 :header-rows: 1
339
340 * - Pattern
341 - Sanitizer
342 * - negated-unsigned-const
343 - unsigned-integer-overflow
344 * - unsigned-post-decr-while
345 - unsigned-integer-overflow
346 * - add-unsigned-overflow-test
347 - unsigned-integer-overflow
348 * - add-signed-overflow-test
349 - signed-integer-overflow
350
351
352
353 Note: ``add-signed-overflow-test`` suppresses only the check for Undefined
354 Behavior. Eager Undefined Behavior optimizations are still possible. One may
355 remedy this with ``-fwrapv`` or ``-fno-strict-overflow``.
356
357 You can enable all exclusions with
358 ``-fsanitize-undefined-ignore-overflow-pattern=all`` or disable all exclusions
359 with ``-fsanitize-undefined-ignore-overflow-pattern=none``. If
360 ``-fsanitize-undefined-ignore-overflow-pattern`` is not specified ``none`` is
361 implied. Specifying ``none`` alongside other values also implies ``none`` as
362 ``none`` has precedence over other values -- including ``all``.
363
364 Issue Suppression
365 =================
366
367 UndefinedBehaviorSanitizer is not expected to produce false positives.
368 If you see one, look again; most likely it is a true positive!
369
370 Disabling Instrumentation with ``__attribute__((no_sanitize("undefined")))``
371 ----------------------------------------------------------------------------
372
373 You disable UBSan checks for particular functions with
374 ``__attribute__((no_sanitize("undefined")))``. You can use all values of
375 ``-fsanitize=`` flag in this attribute, e.g. if your function deliberately
376 contains possible signed integer overflow, you can use
377 ``__attribute__((no_sanitize("signed-integer-overflow")))``.
378
379 This attribute may not be
380 supported by other compilers, so consider using it together with
381 ``#if defined(__clang__)``.
382
383 Suppressing Errors in Recompiled Code (Ignorelist)
384 --------------------------------------------------
385
386 UndefinedBehaviorSanitizer supports ``src`` and ``fun`` entity types in
387 :doc:`SanitizerSpecialCaseList`, that can be used to suppress error reports
388 in the specified source files or functions.
389
390 Runtime suppressions
391 --------------------
392
393 Sometimes you can suppress UBSan error reports for specific files, functions,
394 or libraries without recompiling the code. You need to pass a path to
395 suppression file in a ``UBSAN_OPTIONS`` environment variable.
396
397 .. code-block:: bash
398
399 UBSAN_OPTIONS=suppressions=MyUBSan.supp
400
401 You need to specify a :ref:`check <ubsan-checks>` you are suppressing and the
402 bug location. For example:
403
404 .. code-block:: bash
405
406 signed-integer-overflow:file-with-known-overflow.cpp
407 alignment:function_doing_unaligned_access
408 vptr:shared_object_with_vptr_failures.so
409
410 There are several limitations:
411
412 * Sometimes your binary must have enough debug info and/or symbol table, so
413 that the runtime could figure out source file or function name to match
414 against the suppression.
415 * It is only possible to suppress recoverable checks. For the example above,
416 you can additionally pass
417 ``-fsanitize-recover=signed-integer-overflow,alignment,vptr``, although
418 most of UBSan checks are recoverable by default.
419 * Check groups (like ``undefined``) can't be used in suppressions file, only
420 fine-grained checks are supported.
421
422 Security Considerations
423 =======================
424
425 UndefinedBehaviorSanitizer's runtime is meant for testing purposes and its usage
426 in production environment should be carefully considered from security
427 perspective as it may compromise the security of the resulting executable.
428 For security-sensitive applications consider using :ref:`Minimal Runtime
429 <minimal-runtime>` or trap mode for all checks.
430
431 Supported Platforms
432 ===================
433
434 UndefinedBehaviorSanitizer is supported on the following operating systems:
435
436 * Android
437 * Linux
438 * NetBSD
439 * FreeBSD
440 * OpenBSD
441 * macOS
442 * Windows
443
444 The runtime library is relatively portable and platform independent. If the OS
445 you need is not listed above, UndefinedBehaviorSanitizer may already work for
446 it, or could be made to work with a minor porting effort.
447
448 Current Status
449 ==============
450
451 UndefinedBehaviorSanitizer is available on selected platforms starting from LLVM
452 3.3. The test suite is integrated into the CMake build and can be run with
453 ``check-ubsan`` command.
454
455 Additional Configuration
456 ========================
457
458 UndefinedBehaviorSanitizer adds static check data for each check unless it is
459 in trap mode. This check data includes the full file name. The option
460 ``-fsanitize-undefined-strip-path-components=N`` can be used to trim this
461 information. If ``N`` is positive, file information emitted by
462 UndefinedBehaviorSanitizer will drop the first ``N`` components from the file
463 path. If ``N`` is negative, the last ``N`` components will be kept.
464
465 Example
466 -------
467
468 For a file called ``/code/library/file.cpp``, here is what would be emitted:
469
470 * Default (No flag, or ``-fsanitize-undefined-strip-path-components=0``): ``/code/library/file.cpp``
471 * ``-fsanitize-undefined-strip-path-components=1``: ``code/library/file.cpp``
472 * ``-fsanitize-undefined-strip-path-components=2``: ``library/file.cpp``
473 * ``-fsanitize-undefined-strip-path-components=-1``: ``file.cpp``
474 * ``-fsanitize-undefined-strip-path-components=-2``: ``library/file.cpp``
475
476 More Information
477 ================
478
479 * From Oracle blog, including a discussion of error messages:
480 `Improving Application Security with UndefinedBehaviorSanitizer (UBSan) and GCC
481 <https://blogs.oracle.com/linux/improving-application-security-with-undefinedbehaviorsanitizer-ubsan-and-gcc>`_
482 * From LLVM project blog:
483 `What Every C Programmer Should Know About Undefined Behavior
484 <http://blog.llvm.org/2011/05/what-every-c-programmer-should-know.html>`_
485 * From John Regehr's *Embedded in Academia* blog:
486 `A Guide to Undefined Behavior in C and C++
487 <https://blog.regehr.org/archives/213>`_