UndefinedBehaviorSanitizer.rst 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  1. ==========================
  2. UndefinedBehaviorSanitizer
  3. ==========================
  4. .. contents::
  5. :local:
  6. Introduction
  7. ============
  8. UndefinedBehaviorSanitizer (UBSan) is a fast undefined behavior detector.
  9. UBSan modifies the program at compile-time to catch various kinds of undefined
  10. behavior during program execution, for example:
  11. * Using misaligned or null pointer
  12. * Signed integer overflow
  13. * Conversion to, from, or between floating-point types which would
  14. overflow the destination
  15. See the full list of available :ref:`checks <ubsan-checks>` below.
  16. UBSan has an optional run-time library which provides better error reporting.
  17. The checks have small runtime cost and no impact on address space layout or ABI.
  18. How to build
  19. ============
  20. Build LLVM/Clang with `CMake <https://llvm.org/docs/CMake.html>`_.
  21. Usage
  22. =====
  23. Use ``clang++`` to compile and link your program with ``-fsanitize=undefined``
  24. flag. Make sure to use ``clang++`` (not ``ld``) as a linker, so that your
  25. executable is linked with proper UBSan runtime libraries. You can use ``clang``
  26. instead of ``clang++`` if you're compiling/linking C code.
  27. .. code-block:: console
  28. % cat test.cc
  29. int main(int argc, char **argv) {
  30. int k = 0x7fffffff;
  31. k += argc;
  32. return 0;
  33. }
  34. % clang++ -fsanitize=undefined test.cc
  35. % ./a.out
  36. test.cc:3:5: runtime error: signed integer overflow: 2147483647 + 1 cannot be represented in type 'int'
  37. You can enable only a subset of :ref:`checks <ubsan-checks>` offered by UBSan,
  38. and define the desired behavior for each kind of check:
  39. * ``-fsanitize=...``: print a verbose error report and continue execution (default);
  40. * ``-fno-sanitize-recover=...``: print a verbose error report and exit the program;
  41. * ``-fsanitize-trap=...``: execute a trap instruction (doesn't require UBSan run-time support).
  42. For example if you compile/link your program as:
  43. .. code-block:: console
  44. % clang++ -fsanitize=signed-integer-overflow,null,alignment -fno-sanitize-recover=null -fsanitize-trap=alignment
  45. the program will continue execution after signed integer overflows, exit after
  46. the first invalid use of a null pointer, and trap after the first use of misaligned
  47. pointer.
  48. .. _ubsan-checks:
  49. Available checks
  50. ================
  51. Available checks are:
  52. - ``-fsanitize=alignment``: Use of a misaligned pointer or creation
  53. of a misaligned reference. Also sanitizes assume_aligned-like attributes.
  54. - ``-fsanitize=bool``: Load of a ``bool`` value which is neither
  55. ``true`` nor ``false``.
  56. - ``-fsanitize=builtin``: Passing invalid values to compiler builtins.
  57. - ``-fsanitize=bounds``: Out of bounds array indexing, in cases
  58. where the array bound can be statically determined.
  59. - ``-fsanitize=enum``: Load of a value of an enumerated type which
  60. is not in the range of representable values for that enumerated
  61. type.
  62. - ``-fsanitize=float-cast-overflow``: Conversion to, from, or
  63. between floating-point types which would overflow the
  64. destination. Because the range of representable values for all
  65. floating-point types supported by Clang is [-inf, +inf], the only
  66. cases detected are conversions from floating point to integer types.
  67. - ``-fsanitize=float-divide-by-zero``: Floating point division by
  68. zero. This is undefined per the C and C++ standards, but is defined
  69. by Clang (and by ISO/IEC/IEEE 60559 / IEEE 754) as producing either an
  70. infinity or NaN value, so is not included in ``-fsanitize=undefined``.
  71. - ``-fsanitize=function``: Indirect call of a function through a
  72. function pointer of the wrong type (Darwin/Linux, C++ and x86/x86_64
  73. only).
  74. - ``-fsanitize=implicit-unsigned-integer-truncation``,
  75. ``-fsanitize=implicit-signed-integer-truncation``: Implicit conversion from
  76. integer of larger bit width to smaller bit width, if that results in data
  77. loss. That is, if the demoted value, after casting back to the original
  78. width, is not equal to the original value before the downcast.
  79. The ``-fsanitize=implicit-unsigned-integer-truncation`` handles conversions
  80. between two ``unsigned`` types, while
  81. ``-fsanitize=implicit-signed-integer-truncation`` handles the rest of the
  82. conversions - when either one, or both of the types are signed.
  83. Issues caught by these sanitizers are not undefined behavior,
  84. but are often unintentional.
  85. - ``-fsanitize=implicit-integer-sign-change``: Implicit conversion between
  86. integer types, if that changes the sign of the value. That is, if the the
  87. original value was negative and the new value is positive (or zero),
  88. or the original value was positive, and the new value is negative.
  89. Issues caught by this sanitizer are not undefined behavior,
  90. but are often unintentional.
  91. - ``-fsanitize=integer-divide-by-zero``: Integer division by zero.
  92. - ``-fsanitize=nonnull-attribute``: Passing null pointer as a function
  93. parameter which is declared to never be null.
  94. - ``-fsanitize=null``: Use of a null pointer or creation of a null
  95. reference.
  96. - ``-fsanitize=nullability-arg``: Passing null as a function parameter
  97. which is annotated with ``_Nonnull``.
  98. - ``-fsanitize=nullability-assign``: Assigning null to an lvalue which
  99. is annotated with ``_Nonnull``.
  100. - ``-fsanitize=nullability-return``: Returning null from a function with
  101. a return type annotated with ``_Nonnull``.
  102. - ``-fsanitize=object-size``: An attempt to potentially use bytes which
  103. the optimizer can determine are not part of the object being accessed.
  104. This will also detect some types of undefined behavior that may not
  105. directly access memory, but are provably incorrect given the size of
  106. the objects involved, such as invalid downcasts and calling methods on
  107. invalid pointers. These checks are made in terms of
  108. ``__builtin_object_size``, and consequently may be able to detect more
  109. problems at higher optimization levels.
  110. - ``-fsanitize=pointer-overflow``: Performing pointer arithmetic which
  111. overflows, or where either the old or new pointer value is a null pointer
  112. (or in C, when they both are).
  113. - ``-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, where the
  125. result of a signed integer computation cannot be represented in its type.
  126. This includes all the checks covered by ``-ftrapv``, as well as checks for
  127. signed division overflow (``INT_MIN/-1``), but not checks for
  128. lossy implicit conversions performed before the computation
  129. (see ``-fsanitize=implicit-conversion``). Both of these two issues are
  130. handled by ``-fsanitize=implicit-conversion`` group of checks.
  131. - ``-fsanitize=unreachable``: If control flow reaches an unreachable
  132. program point.
  133. - ``-fsanitize=unsigned-integer-overflow``: Unsigned integer overflow, where
  134. the result of an unsigned integer computation cannot be represented in its
  135. type. Unlike signed integer overflow, this is not undefined behavior, but
  136. it is often unintentional. This sanitizer does not check for lossy implicit
  137. conversions performed before such a computation
  138. (see ``-fsanitize=implicit-conversion``).
  139. - ``-fsanitize=vla-bound``: A variable-length array whose bound
  140. does not evaluate to a positive value.
  141. - ``-fsanitize=vptr``: Use of an object whose vptr indicates that it is of
  142. the wrong dynamic type, or that its lifetime has not begun or has ended.
  143. Incompatible with ``-fno-rtti``. Link must be performed by ``clang++``, not
  144. ``clang``, to make sure C++-specific parts of the runtime library and C++
  145. standard libraries are present.
  146. You can also use the following check groups:
  147. - ``-fsanitize=undefined``: All of the checks listed above other than
  148. ``float-divide-by-zero``, ``unsigned-integer-overflow``,
  149. ``implicit-conversion``, and the ``nullability-*`` group of checks.
  150. - ``-fsanitize=undefined-trap``: Deprecated alias of
  151. ``-fsanitize=undefined``.
  152. - ``-fsanitize=implicit-integer-truncation``: Catches lossy integral
  153. conversions. Enables ``implicit-signed-integer-truncation`` and
  154. ``implicit-unsigned-integer-truncation``.
  155. - ``-fsanitize=implicit-integer-arithmetic-value-change``: Catches implicit
  156. conversions that change the arithmetic value of the integer. Enables
  157. ``implicit-signed-integer-truncation`` and ``implicit-integer-sign-change``.
  158. - ``-fsanitize=implicit-conversion``: Checks for suspicious
  159. behavior of implicit conversions. Enables
  160. ``implicit-unsigned-integer-truncation``,
  161. ``implicit-signed-integer-truncation``, and
  162. ``implicit-integer-sign-change``.
  163. - ``-fsanitize=integer``: Checks for undefined or suspicious integer
  164. behavior (e.g. unsigned integer overflow).
  165. Enables ``signed-integer-overflow``, ``unsigned-integer-overflow``,
  166. ``shift``, ``integer-divide-by-zero``,
  167. ``implicit-unsigned-integer-truncation``,
  168. ``implicit-signed-integer-truncation``, and
  169. ``implicit-integer-sign-change``.
  170. - ``-fsanitize=nullability``: Enables ``nullability-arg``,
  171. ``nullability-assign``, and ``nullability-return``. While violating
  172. nullability does not have undefined behavior, it is often unintentional,
  173. so UBSan offers to catch it.
  174. Volatile
  175. --------
  176. The ``null``, ``alignment``, ``object-size``, and ``vptr`` checks do not apply
  177. to pointers to types with the ``volatile`` qualifier.
  178. Minimal Runtime
  179. ===============
  180. There is a minimal UBSan runtime available suitable for use in production
  181. environments. This runtime has a small attack surface. It only provides very
  182. basic issue logging and deduplication, and does not support
  183. ``-fsanitize=function`` and ``-fsanitize=vptr`` checking.
  184. To use the minimal runtime, add ``-fsanitize-minimal-runtime`` to the clang
  185. command line options. For example, if you're used to compiling with
  186. ``-fsanitize=undefined``, you could enable the minimal runtime with
  187. ``-fsanitize=undefined -fsanitize-minimal-runtime``.
  188. Stack traces and report symbolization
  189. =====================================
  190. If you want UBSan to print symbolized stack trace for each error report, you
  191. will need to:
  192. #. Compile with ``-g`` and ``-fno-omit-frame-pointer`` to get proper debug
  193. information in your binary.
  194. #. Run your program with environment variable
  195. ``UBSAN_OPTIONS=print_stacktrace=1``.
  196. #. Make sure ``llvm-symbolizer`` binary is in ``PATH``.
  197. Logging
  198. =======
  199. The default log file for diagnostics is "stderr". To log diagnostics to another
  200. file, you can set ``UBSAN_OPTIONS=log_path=...``.
  201. Silencing Unsigned Integer Overflow
  202. ===================================
  203. To silence reports from unsigned integer overflow, you can set
  204. ``UBSAN_OPTIONS=silence_unsigned_overflow=1``. This feature, combined with
  205. ``-fsanitize-recover=unsigned-integer-overflow``, is particularly useful for
  206. providing fuzzing signal without blowing up logs.
  207. Issue Suppression
  208. =================
  209. UndefinedBehaviorSanitizer is not expected to produce false positives.
  210. If you see one, look again; most likely it is a true positive!
  211. Disabling Instrumentation with ``__attribute__((no_sanitize("undefined")))``
  212. ----------------------------------------------------------------------------
  213. You disable UBSan checks for particular functions with
  214. ``__attribute__((no_sanitize("undefined")))``. You can use all values of
  215. ``-fsanitize=`` flag in this attribute, e.g. if your function deliberately
  216. contains possible signed integer overflow, you can use
  217. ``__attribute__((no_sanitize("signed-integer-overflow")))``.
  218. This attribute may not be
  219. supported by other compilers, so consider using it together with
  220. ``#if defined(__clang__)``.
  221. Suppressing Errors in Recompiled Code (Blacklist)
  222. -------------------------------------------------
  223. UndefinedBehaviorSanitizer supports ``src`` and ``fun`` entity types in
  224. :doc:`SanitizerSpecialCaseList`, that can be used to suppress error reports
  225. in the specified source files or functions.
  226. Runtime suppressions
  227. --------------------
  228. Sometimes you can suppress UBSan error reports for specific files, functions,
  229. or libraries without recompiling the code. You need to pass a path to
  230. suppression file in a ``UBSAN_OPTIONS`` environment variable.
  231. .. code-block:: bash
  232. UBSAN_OPTIONS=suppressions=MyUBSan.supp
  233. You need to specify a :ref:`check <ubsan-checks>` you are suppressing and the
  234. bug location. For example:
  235. .. code-block:: bash
  236. signed-integer-overflow:file-with-known-overflow.cpp
  237. alignment:function_doing_unaligned_access
  238. vptr:shared_object_with_vptr_failures.so
  239. There are several limitations:
  240. * Sometimes your binary must have enough debug info and/or symbol table, so
  241. that the runtime could figure out source file or function name to match
  242. against the suppression.
  243. * It is only possible to suppress recoverable checks. For the example above,
  244. you can additionally pass
  245. ``-fsanitize-recover=signed-integer-overflow,alignment,vptr``, although
  246. most of UBSan checks are recoverable by default.
  247. * Check groups (like ``undefined``) can't be used in suppressions file, only
  248. fine-grained checks are supported.
  249. Supported Platforms
  250. ===================
  251. UndefinedBehaviorSanitizer is supported on the following operating systems:
  252. * Android
  253. * Linux
  254. * NetBSD
  255. * FreeBSD
  256. * OpenBSD
  257. * macOS
  258. * Windows
  259. The runtime library is relatively portable and platform independent. If the OS
  260. you need is not listed above, UndefinedBehaviorSanitizer may already work for
  261. it, or could be made to work with a minor porting effort.
  262. Current Status
  263. ==============
  264. UndefinedBehaviorSanitizer is available on selected platforms starting from LLVM
  265. 3.3. The test suite is integrated into the CMake build and can be run with
  266. ``check-ubsan`` command.
  267. Additional Configuration
  268. ========================
  269. UndefinedBehaviorSanitizer adds static check data for each check unless it is
  270. in trap mode. This check data includes the full file name. The option
  271. ``-fsanitize-undefined-strip-path-components=N`` can be used to trim this
  272. information. If ``N`` is positive, file information emitted by
  273. UndefinedBehaviorSanitizer will drop the first ``N`` components from the file
  274. path. If ``N`` is negative, the last ``N`` components will be kept.
  275. Example
  276. -------
  277. For a file called ``/code/library/file.cpp``, here is what would be emitted:
  278. * Default (No flag, or ``-fsanitize-undefined-strip-path-components=0``): ``/code/library/file.cpp``
  279. * ``-fsanitize-undefined-strip-path-components=1``: ``code/library/file.cpp``
  280. * ``-fsanitize-undefined-strip-path-components=2``: ``library/file.cpp``
  281. * ``-fsanitize-undefined-strip-path-components=-1``: ``file.cpp``
  282. * ``-fsanitize-undefined-strip-path-components=-2``: ``library/file.cpp``
  283. More Information
  284. ================
  285. * From LLVM project blog:
  286. `What Every C Programmer Should Know About Undefined Behavior
  287. <http://blog.llvm.org/2011/05/what-every-c-programmer-should-know.html>`_
  288. * From John Regehr's *Embedded in Academia* blog:
  289. `A Guide to Undefined Behavior in C and C++
  290. <https://blog.regehr.org/archives/213>`_