blob: 6e6a641697e9d6b2eb21e051789e0441baec034b [file] [log] [blame]
Avi Drissmane4622aa2022-09-08 20:36:061// Copyright 2012 The Chromium Authors
license.botbf09a502008-08-24 00:55:552// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
[email protected]f1ea2fa2008-08-21 22:26:064
5#ifndef BASE_COMPILER_SPECIFIC_H_
6#define BASE_COMPILER_SPECIFIC_H_
7
8#include "build/build_config.h"
9
Nico Weberfb053cc2020-03-03 13:33:0510#if defined(COMPILER_MSVC) && !defined(__clang__)
Nico Weber59791812019-07-27 04:02:1111#error "Only clang-cl is supported on Windows, see https://crbug.com/988071"
12#endif
13
Peter Kasting67944102024-09-18 00:23:5714// A wrapper around `__has_attribute()`, which is similar to the C++20-standard
15// `__has_cpp_attribute()`, but tests for support for `__attribute__(())`s.
16// Compilers that do not support this (e.g. MSVC) are also assumed not to
17// support `__attribute__`, so this is simply mapped to `0` there.
18//
19// See also:
20// https://clang.llvm.org/docs/LanguageExtensions.html#has-attribute
Peter Kasting64c67dd2022-05-12 18:11:5121#if defined(__has_attribute)
22#define HAS_ATTRIBUTE(x) __has_attribute(x)
23#else
24#define HAS_ATTRIBUTE(x) 0
25#endif
26
Peter Kasting67944102024-09-18 00:23:5727// A wrapper around `__has_builtin`, similar to `HAS_ATTRIBUTE()`.
28//
29// See also:
30// https://clang.llvm.org/docs/LanguageExtensions.html#has-builtin
Jann Horn9e4b48552021-03-04 14:34:2731#if defined(__has_builtin)
32#define HAS_BUILTIN(x) __has_builtin(x)
33#else
34#define HAS_BUILTIN(x) 0
35#endif
36
Peter Kasting67944102024-09-18 00:23:5737// A wrapper around `__has_feature`, similar to `HAS_ATTRIBUTE()`.
38//
39// See also:
40// https://clang.llvm.org/docs/LanguageExtensions.html#has-feature-and-has-extension
41#if defined(__has_feature)
42#define HAS_FEATURE(FEATURE) __has_feature(FEATURE)
43#else
44#define HAS_FEATURE(FEATURE) 0
45#endif
46
47// Annotates a function indicating it should not be inlined.
48//
49// You may also want `NOOPT` if your goal is to preserve a function call even
50// for the most trivial cases; see
51// https://stackoverflow.com/questions/54481855/clang-ignoring-attribute-noinline/54482070#54482070.
52//
53// See also:
54// https://clang.llvm.org/docs/AttributeReference.html#noinline
55//
56// Usage:
57// ```
58// NOINLINE void Func() {
59// // This body will not be inlined into callers.
60// }
61// ```
Tom Sepez7847345e2025-01-14 01:02:0162#if __has_cpp_attribute(clang::noinline)
63#define NOINLINE [[clang::noinline]]
64#elif __has_cpp_attribute(gnu::noinline)
Peter Kastingc3dadb022024-09-17 22:44:5465#define NOINLINE [[gnu::noinline]]
66#elif __has_cpp_attribute(msvc::noinline)
67#define NOINLINE [[msvc::noinline]]
[email protected]2149cc622012-02-14 01:12:1268#else
[email protected]50795a02011-05-09 20:11:0169#define NOINLINE
[email protected]f50595102010-10-08 16:20:3270#endif
71
Tom Sepez7847345e2025-01-14 01:02:0172// Annotates a call site indicating that the callee should not be inlined.
73//
74// See also:
75// https://clang.llvm.org/docs/AttributeReference.html#noinline
76//
77// Usage:
78// ```
79// void Func() {
80// // This specific call to `DoSomething` should not be inlined.
81// NOINLINE_CALL DoSomething();
82// }
83// ```
84#if __has_cpp_attribute(clang::noinline)
85#define NOINLINE_CALL [[clang::noinline]]
86#else
87#define NOINLINE_CALL
88#endif
89
Peter Kasting67944102024-09-18 00:23:5790// Annotates a function indicating it should not be optimized.
91//
92// See also:
93// https://clang.llvm.org/docs/AttributeReference.html#optnone
94// https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html#index-optimize-function-attribute
95//
96// Usage:
97// ```
98// NOOPT void Func() {
99// // This body will not be optimized.
100// }
101// ```
Peter Kastingc3dadb022024-09-17 22:44:54102#if __has_cpp_attribute(clang::optnone)
Jose Dapena Paz7cc1b1d42023-11-08 18:37:28103#define NOOPT [[clang::optnone]]
Peter Kastingc3dadb022024-09-17 22:44:54104#elif __has_cpp_attribute(gnu::optimize)
105#define NOOPT [[gnu::optimize(0)]]
Jose Dapena Paz7cc1b1d42023-11-08 18:37:28106#else
107#define NOOPT
108#endif
109
Peter Kasting67944102024-09-18 00:23:57110// Annotates a function indicating it should always be inlined.
111//
112// See also:
113// https://clang.llvm.org/docs/AttributeReference.html#always-inline-force-inline
114//
115// Usage:
116// ```
117// ALWAYS_INLINE void Func() {
118// // This body will be inlined into callers whenever possible.
119// }
120// ```
121//
122// Since `ALWAYS_INLINE` is performance-oriented but can hamper debugging,
123// ignore it in debug mode.
Peter Kastingc3dadb022024-09-17 22:44:54124#if defined(NDEBUG)
Tom Sepez7847345e2025-01-14 01:02:01125#if __has_cpp_attribute(clang::always_inline)
126#define ALWAYS_INLINE [[clang::always_inline]] inline
127#elif __has_cpp_attribute(gnu::always_inline)
Peter Kastingc3dadb022024-09-17 22:44:54128#define ALWAYS_INLINE [[gnu::always_inline]] inline
129#elif defined(COMPILER_MSVC)
palmer58184a8282016-11-08 19:15:39130#define ALWAYS_INLINE __forceinline
Peter Kastingc3dadb022024-09-17 22:44:54131#endif
132#endif
133#if !defined(ALWAYS_INLINE)
palmer58184a8282016-11-08 19:15:39134#define ALWAYS_INLINE inline
135#endif
136
Tom Sepez7847345e2025-01-14 01:02:01137// Annotates a call site indicating the calee should always be inlined.
138//
139// See also:
140// https://clang.llvm.org/docs/AttributeReference.html#always-inline-force-inline
141//
142// Usage:
143// ```
144// void Func() {
145// // This specific call will be inlined if possible.
146// ALWAYS_INLINE_CALL DoSomething();
147// }
148// ```
149//
150// Since `ALWAYS_INLINE_CALL` is performance-oriented but can hamper debugging,
151// ignore it in debug mode.
152#if defined(NDEBUG)
153#if __has_cpp_attribute(clang::always_inline)
154#define ALWAYS_INLINE_CALL [[clang::always_inline]]
155#endif
156#endif
157#if !defined(ALWAYS_INLINE_CALL)
158#define ALWAYS_INLINE_CALL
159#endif
160
Peter Kasting67944102024-09-18 00:23:57161// Annotates a function indicating it should never be tail called. Useful to
162// make sure callers of the annotated function are never omitted from call
163// stacks. Often useful with `NOINLINE` to make sure the function itself is also
164// not omitted from call stacks. Note: this does not prevent code folding of
165// multiple identical callers into a single signature; to do that, see
166// `NO_CODE_FOLDING()` in base/debug/alias.h.
167//
168// For a caller-side version of this, see `DISABLE_TAIL_CALLS`.
169//
170// See also:
171// https://clang.llvm.org/docs/AttributeReference.html#not-tail-called
172//
173// Usage:
174// ```
175// // Calls to this function will not be tail calls.
176// NOT_TAIL_CALLED void Func();
177// ```
Peter Kastingc3dadb022024-09-17 22:44:54178#if __has_cpp_attribute(clang::not_tail_called)
Peter Kastingf541f7782023-03-10 23:44:46179#define NOT_TAIL_CALLED [[clang::not_tail_called]]
Olivier Li19d89252020-05-13 17:57:55180#else
181#define NOT_TAIL_CALLED
182#endif
183
Peter Kasting67944102024-09-18 00:23:57184// Annotates a return statement indicating the compiler must convert it to a
185// tail call. Can be used only on return statements, even for functions
186// returning void. Caller and callee must have the same number of arguments and
187// the argument types must be "similar". While the compiler may automatically
188// convert compatible calls to tail calls when optimizing, this annotation
189// requires it to occur if doing so is valid, and will not compile otherwise.
190//
191// See also:
192// https://clang.llvm.org/docs/AttributeReference.html#musttail
193//
194// Usage:
195// ```
196// int Func1(double);
197// int Func2(double d) {
198// MUSTTAIL return Func1(d + 1); // `Func1()` will be tail-called.
199// }
200// ```
Peter Kastingc3dadb022024-09-17 22:44:54201#if __has_cpp_attribute(clang::musttail)
mikt2a4fdf02024-07-09 18:47:57202#define MUSTTAIL [[clang::musttail]]
203#else
204#define MUSTTAIL
205#endif
206
Peter Kasting67944102024-09-18 00:23:57207// Annotates a data member indicating it need not have an address distinct from
208// all other non-static data members of the class, and its tail padding may be
209// used for other objects' storage. This can have subtle and dangerous effects,
210// including on containing objects; use with caution.
Jan Wilken Dörrief8d479d2020-11-23 12:21:13211//
Peter Kasting67944102024-09-18 00:23:57212// See also:
213// https://en.cppreference.com/w/cpp/language/attributes/no_unique_address
214// https://wg21.link/dcl.attr.nouniqueaddr
215// Usage:
216// ```
217// // In the following struct, `t` might not have a unique address from `i`,
218// // and `t`'s tail padding (if any) may be reused by subsequent objects.
219// struct S {
220// int i;
221// NO_UNIQUE_ADDRESS T t;
222// };
223// ```
Peter Kastingc3dadb022024-09-17 22:44:54224//
Peter Kasting8bc046d22023-11-14 00:38:03225// Unfortunately MSVC ignores [[no_unique_address]] (see
226// https://devblogs.microsoft.com/cppblog/msvc-cpp20-and-the-std-cpp20-switch/#msvc-extensions-and-abi),
227// and clang-cl matches it for ABI compatibility reasons. We need to prefer
228// [[msvc::no_unique_address]] when available if we actually want any effect.
Peter Kastingc3dadb022024-09-17 22:44:54229#if __has_cpp_attribute(msvc::no_unique_address)
Helmut Januschka13cd38b2023-12-22 03:31:47230#define NO_UNIQUE_ADDRESS [[msvc::no_unique_address]]
Peter Kastingc3dadb022024-09-17 22:44:54231#elif __has_cpp_attribute(no_unique_address)
Jan Wilken Dörrief8d479d2020-11-23 12:21:13232#define NO_UNIQUE_ADDRESS [[no_unique_address]]
233#else
234#define NO_UNIQUE_ADDRESS
235#endif
236
Peter Kasting67944102024-09-18 00:23:57237// Annotates a function indicating it takes a `printf()`-style format string.
238// The compiler will check that the provided arguments match the type specifiers
239// in the format string. Useful to detect mismatched format strings/args.
240//
241// `format_param` is the one-based index of the format string parameter;
242// `dots_param` is the one-based index of the "..." parameter.
243// For `v*printf()` functions (which take a `va_list`), `dots_param` should be
244// 0. For member functions, the implicit `this` parameter is at index 1.
245//
246// See also:
247// https://clang.llvm.org/docs/AttributeReference.html#format
248// https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html#index-format-function-attribute
249//
250// Usage:
251// ```
252// PRINTF_FORMAT(1, 2)
253// void Print(const char* format, ...);
254// void Func() {
255// // The following call will not compile; diagnosed as format and argument
256// // types mismatching.
257// Print("%s", 1);
258// }
259// ```
Peter Kastingc3dadb022024-09-17 22:44:54260#if __has_cpp_attribute(gnu::format)
[email protected]34b2b002009-11-20 06:53:28261#define PRINTF_FORMAT(format_param, dots_param) \
Peter Kastingc3dadb022024-09-17 22:44:54262 [[gnu::format(printf, format_param, dots_param)]]
[email protected]f50595102010-10-08 16:20:32263#else
264#define PRINTF_FORMAT(format_param, dots_param)
265#endif
[email protected]34b2b002009-11-20 06:53:28266
Peter Kasting67944102024-09-18 00:23:57267// Annotates a function disabling the named sanitizer within its body.
268//
269// See also:
270// https://clang.llvm.org/docs/AttributeReference.html#no-sanitize
271// https://clang.llvm.org/docs/UsersManual.html#controlling-code-generation
272//
273// Usage:
274// ```
275// NO_SANITIZE("cfi-icall") void Func() {
276// // CFI indirect call checks will not be performed in this body.
277// }
278// ```
Peter Kastingc3dadb022024-09-17 22:44:54279#if __has_cpp_attribute(clang::no_sanitize)
280#define NO_SANITIZE(sanitizer) [[clang::no_sanitize(sanitizer)]]
281#else
282#define NO_SANITIZE(sanitizer)
etienneb4e9250a2016-11-18 18:47:53283#endif
284
Peter Kasting67944102024-09-18 00:23:57285// Annotates a pointer and size directing MSAN to treat that memory region as
286// fully initialized. Useful for e.g. code that deliberately reads uninitialized
287// data, such as a GC scavenging root set pointers from the stack.
288//
289// See also:
290// https://github.com/google/sanitizers/wiki/MemorySanitizer
291//
292// Usage:
293// ```
294// T* ptr = ...;
295// // After the next statement, MSAN will assume `ptr` points to an
296// // initialized `T`.
297// MSAN_UNPOISON(ptr, sizeof(T));
298// ```
Nico Weber6f2d26d2025-06-27 07:32:08299#if defined(MEMORY_SANITIZER)
[email protected]eb82dfb2014-02-03 19:51:17300#include <sanitizer/msan_interface.h>
Vitaly Buka2b790762019-12-20 21:11:48301#define MSAN_UNPOISON(p, size) __msan_unpoison(p, size)
Peter Kasting67944102024-09-18 00:23:57302#else
303#define MSAN_UNPOISON(p, size)
304#endif
thestig1a42b4072015-03-16 22:36:55305
Peter Kasting67944102024-09-18 00:23:57306// Annotates a pointer and size directing MSAN to check whether that memory
307// region is initialized, as if it was being read from. If any bits are
308// uninitialized, crashes with an MSAN report. Useful for e.g. sanitizing data
309// MSAN won't be able to track, such as data that is about to be passed to
310// another process via shared memory.
311//
312// See also:
313// https://www.chromium.org/developers/testing/memorysanitizer/#debugging-msan-reports
314//
315// Usage:
316// ```
317// T* ptr = ...;
318// // The following line will crash at runtime in MSAN builds if `ptr` does
319// // not point to an initialized `T`.
320// MSAN_CHECK_MEM_IS_INITIALIZED(ptr, sizeof(T));
321// ```
Nico Weber6f2d26d2025-06-27 07:32:08322#if defined(MEMORY_SANITIZER)
thestig1a42b4072015-03-16 22:36:55323#define MSAN_CHECK_MEM_IS_INITIALIZED(p, size) \
Vitaly Buka2b790762019-12-20 21:11:48324 __msan_check_mem_is_initialized(p, size)
Peter Kasting67944102024-09-18 00:23:57325#else
thestig1a42b4072015-03-16 22:36:55326#define MSAN_CHECK_MEM_IS_INITIALIZED(p, size)
Peter Kasting67944102024-09-18 00:23:57327#endif
[email protected]75086be2013-03-20 21:18:22328
Peter Kasting67944102024-09-18 00:23:57329// Annotates a function disabling Control Flow Integrity checks due to perf
330// impact.
331//
332// See also:
333// https://clang.llvm.org/docs/ControlFlowIntegrity.html#performance
334// https://www.chromium.org/developers/testing/control-flow-integrity/#overhead-only-tested-on-x64
335//
336// Usage:
337// ```
338// DISABLE_CFI_PERF void Func() {
339// // CFI checks will not be performed in this body, due to perf reasons.
340// }
341// ```
krasin825ce482016-08-27 11:01:11342#if !defined(DISABLE_CFI_PERF)
krasin40f7c782016-09-22 19:04:27343#if defined(__clang__) && defined(OFFICIAL_BUILD)
Peter Kastingf541f7782023-03-10 23:44:46344#define DISABLE_CFI_PERF NO_SANITIZE("cfi")
krasin825ce482016-08-27 11:01:11345#else
346#define DISABLE_CFI_PERF
347#endif
348#endif
349
Peter Kasting67944102024-09-18 00:23:57350// Annotates a function disabling Control Flow Integrity indirect call checks.
351// NOTE: Prefer `DISABLE_CFI_DLSYM()` if you just need to allow calling of dlsym
352// functions.
353//
354// See also:
355// https://clang.llvm.org/docs/ControlFlowIntegrity.html#available-schemes
356// https://www.chromium.org/developers/testing/control-flow-integrity/#indirect-call-failures
357//
358// Usage:
359// ```
360// DISABLE_CFI_ICALL void Func() {
361// // CFI indirect call checks will not be performed in this body.
362// }
363// ```
Will Harris9a033b02020-07-11 01:26:54364#if !defined(DISABLE_CFI_ICALL)
Xiaohan Wang38e4ebb2022-01-19 06:57:43365#if BUILDFLAG(IS_WIN)
Will Harris9a033b02020-07-11 01:26:54366#define DISABLE_CFI_ICALL NO_SANITIZE("cfi-icall") __declspec(guard(nocf))
367#else
368#define DISABLE_CFI_ICALL NO_SANITIZE("cfi-icall")
369#endif
370#endif
Will Harris9a033b02020-07-11 01:26:54371
Peter Kasting67944102024-09-18 00:23:57372// Annotates a function disabling Control Flow Integrity indirect call checks if
373// doing so is necessary to call dlsym functions. The checks are retained on
374// platforms where loaded modules participate in CFI (viz. Windows).
375//
376// See also:
377// https://www.chromium.org/developers/testing/control-flow-integrity/#indirect-call-failures
378//
379// Usage:
380// ```
381// DISABLE_CFI_DLSYM void Func() {
382// // On non-Windows platforms, CFI indirect call checks will not be
383// // performed in this body.
384// }
385// ```
Alex Gough36579802022-07-25 20:20:46386#if !defined(DISABLE_CFI_DLSYM)
387#if BUILDFLAG(IS_WIN)
Alex Gough36579802022-07-25 20:20:46388#define DISABLE_CFI_DLSYM
389#else
390#define DISABLE_CFI_DLSYM DISABLE_CFI_ICALL
391#endif
392#endif
Alex Gough36579802022-07-25 20:20:46393
Peter Kasting67944102024-09-18 00:23:57394// Evaluates to a string constant containing the function signature.
395//
396// See also:
397// https://clang.llvm.org/docs/LanguageExtensions.html#source-location-builtins
398// https://en.cppreference.com/w/c/language/function_definition#func
399//
400// Usage:
401// ```
402// void Func(int arg) {
403// std::cout << PRETTY_FUNCTION; // Prints `void Func(int)` or similar.
404// }
405// ```
Alex Clarke23c6cf72018-11-21 13:22:27406#if defined(COMPILER_GCC)
407#define PRETTY_FUNCTION __PRETTY_FUNCTION__
408#elif defined(COMPILER_MSVC)
409#define PRETTY_FUNCTION __FUNCSIG__
410#else
Alex Clarke23c6cf72018-11-21 13:22:27411#define PRETTY_FUNCTION __func__
412#endif
413
Peter Kasting67944102024-09-18 00:23:57414// Annotates a variable indicating that its storage should not be filled with a
415// fixed pattern when uninitialized.
Vitaly Buka2b790762019-12-20 21:11:48416//
Peter Kasting67944102024-09-18 00:23:57417// The `init_stack_vars` gn arg (enabled on most build configs) causes the
418// compiler to generate code that writes a fixed pattern into uninitialized
419// parts of all local variables, to mitigate security risks. In most cases, e.g.
420// when such memory is either never accessed or will be initialized later before
421// reading, the compiler is able to remove the additional stores, and any
422// remaining stores are unlikely to affect program performance.
Vitaly Buka2b790762019-12-20 21:11:48423//
Peter Kasting67944102024-09-18 00:23:57424// If hot code suffers unavoidable perf penalties, this can disable the
425// pattern-filling there. This should only be done when necessary, since reads
426// from uninitialized variables are not only UB, they can in practice allow
427// attackers to control logic by pre-filling the variable's memory with a
428// desirable value.
429//
430// NOTE: This behavior also increases the likelihood the compiler will generate
431// `memcpy()`/`memset()` calls to init variables. If this causes link errors for
432// targets that don't link against the CRT, this macro can help; you may instead
433// want 'configs -= [ "//build/config/compiler:default_init_stack_vars" ]' in
434// the relevant .gn file to disable this on the whole target.
435//
436// See also:
437// https://source.chromium.org/chromium/chromium/src/+/main:build/config/compiler/BUILD.gn;l=3088;drc=24ccaf63ff5b1883be1ebe5f979d917ce28b0131
438// https://clang.llvm.org/docs/ClangCommandLineReference.html#cmdoption-clang-ftrivial-auto-var-init
439// https://clang.llvm.org/docs/AttributeReference.html#uninitialized
440//
441// Usage:
442// ```
443// // The following line declares `i` without ensuring it initially contains
444// // any particular pattern.
445// STACK_UNINITIALIZED int i;
446// ```
Peter Kastingc3dadb022024-09-17 22:44:54447#if __has_cpp_attribute(clang::uninitialized)
Peter Kastingf541f7782023-03-10 23:44:46448#define STACK_UNINITIALIZED [[clang::uninitialized]]
Peter Kastingc3dadb022024-09-17 22:44:54449#elif __has_cpp_attribute(gnu::uninitialized)
450#define STACK_UNINITIALIZED [[gnu::uninitialized]]
Vitaly Buka2b790762019-12-20 21:11:48451#else
452#define STACK_UNINITIALIZED
453#endif
454
Peter Kasting67944102024-09-18 00:23:57455// Annotates a function disabling stack canary checks.
Matthew Dentonbb0b03e2021-07-22 16:18:13456//
Peter Kasting67944102024-09-18 00:23:57457// The `-fstack-protector` compiler flag (passed on most non-Windows builds)
458// causes the compiler to extend some function prologues and epilogues to set
459// and check a canary value, to detect stack buffer overflows and crash in
460// response. If hot code suffers unavoidable perf penalties, or intentionally
461// modifies the canary value, this can disable the behavior there.
Matthew Dentonbb0b03e2021-07-22 16:18:13462//
Peter Kasting67944102024-09-18 00:23:57463// See also:
464// https://clang.llvm.org/docs/ClangCommandLineReference.html#cmdoption-clang-fstack-protector
465// https://clang.llvm.org/docs/AttributeReference.html#no-stack-protector-safebuffers
466//
467// Usage:
468// ```
469// NO_STACK_PROTECTOR void Func() {
470// // Stack canary checks will not be performed in this body.
471// }
472// ```
Peter Kastingc3dadb022024-09-17 22:44:54473#if __has_cpp_attribute(gnu::no_stack_protector)
474#define NO_STACK_PROTECTOR [[gnu::no_stack_protector]]
475#elif __has_cpp_attribute(gnu::optimize)
476#define NO_STACK_PROTECTOR [[gnu::optimize("-fno-stack-protector")]]
Matthew Dentonbb0b03e2021-07-22 16:18:13477#else
478#define NO_STACK_PROTECTOR
479#endif
480
Peter Kasting67944102024-09-18 00:23:57481// Annotates a codepath suppressing static analysis along that path. Useful when
482// code is safe in practice for reasons the analyzer can't detect, e.g. because
483// the condition leading to that path guarantees a param is non-null.
484//
485// Usage:
486// ```
487// if (cond) {
488// ANALYZER_SKIP_THIS_PATH();
489// // Static analysis will be disabled for the remainder of this block.
490// delete ptr;
491// }
492// ```
Peter Kastingc3dadb022024-09-17 22:44:54493#if defined(__clang_analyzer__)
494inline constexpr bool AnalyzerNoReturn()
495#if HAS_ATTRIBUTE(analyzer_noreturn)
496 __attribute__((analyzer_noreturn))
497#endif
498{
499 return false;
500}
501#define ANALYZER_SKIP_THIS_PATH() static_cast<void>(::AnalyzerNoReturn())
502#else
503// The above definition would be safe even outside the analyzer, but defining
504// the macro away entirely avoids the need for the optimizer to eliminate it.
505#define ANALYZER_SKIP_THIS_PATH()
506#endif
507
Peter Kasting67944102024-09-18 00:23:57508// Annotates a condition directing static analysis to assume it is always true.
509// Evaluates to the provided `arg` as a `bool`.
510//
511// Usage:
512// ```
513// // Static analysis will assume the following condition always holds.
514// if (ANALYZER_ASSUME_TRUE(cond)) ...
515// ```
Hans Wennborg12aea3e2020-04-14 15:29:00516#if defined(__clang_analyzer__)
Hans Wennborg12aea3e2020-04-14 15:29:00517inline constexpr bool AnalyzerAssumeTrue(bool arg) {
Hans Wennborg12aea3e2020-04-14 15:29:00518 return arg || AnalyzerNoReturn();
519}
George Burgess IVa09d235d2020-04-17 13:32:50520#define ANALYZER_ASSUME_TRUE(arg) ::AnalyzerAssumeTrue(!!(arg))
Peter Kastingc3dadb022024-09-17 22:44:54521#else
522// Again, the above definition is safe, this is just simpler for the optimizer.
Hans Wennborg12aea3e2020-04-14 15:29:00523#define ANALYZER_ASSUME_TRUE(arg) (arg)
Peter Kastingc3dadb022024-09-17 22:44:54524#endif
Hans Wennborg12aea3e2020-04-14 15:29:00525
Peter Kasting67944102024-09-18 00:23:57526// Annotates a function, function pointer, or statement to disallow
527// optimizations that merge calls. Useful to ensure the source locations of such
528// calls are not obscured.
529//
530// See also:
531// https://clang.llvm.org/docs/AttributeReference.html#nomerge
532//
533// Usage:
534// ```
535// NOMERGE void Func(); // No direct calls to `Func()` will be merged.
536//
537// using Ptr = decltype(&Func);
538// NOMERGE Ptr ptr = &Func; // No calls through `ptr` will be merged.
539//
540// NOMERGE if (cond) {
541// // No calls in this block will be merged.
542// }
543// ```
Peter Kastingc3dadb022024-09-17 22:44:54544#if __has_cpp_attribute(clang::nomerge)
Zequan Wu9909f142021-02-10 03:26:00545#define NOMERGE [[clang::nomerge]]
546#else
547#define NOMERGE
548#endif
549
Peter Kasting67944102024-09-18 00:23:57550// Annotates a type as being suitable for passing in registers despite having a
551// non-trivial copy or move constructor or destructor. This requires the type
552// not be concerned about its address remaining constant, be safely usable after
553// copying its memory, and have a destructor that may be safely omitted on
554// moved-from instances; an example is `std::unique_ptr`. Unnecessary if the
555// copy/move constructor(s) and destructor are unconditionally trivial; likely
556// ineffective if the type is too large to be passed in one or two registers
557// with the target ABI. However, annotating a type this way will also cause
558// `IS_TRIVIALLY_RELOCATABLE()` to return true for that type, and so may be
559// desirable even for large types, if they are placed in containers that
560// optimize based on that check.
Jeremy Roman810d98d2021-04-06 16:46:07561//
Peter Kasting67944102024-09-18 00:23:57562// NOTE: Use with caution; this has subtle effects on constructor/destructor
563// ordering. When used with types passed or returned by value, values may be
564// constructed in the source stack frame, passed in a register, and then used
565// and destroyed in the target stack frame.
Jeremy Roman810d98d2021-04-06 16:46:07566//
567// See also:
568// https://clang.llvm.org/docs/AttributeReference.html#trivial-abi
569// https://libcxx.llvm.org/docs/DesignDocs/UniquePtrTrivialAbi.html
Peter Kasting67944102024-09-18 00:23:57570//
571// Usage:
572// ```
573// // Instances of type `S` will be eligible to be passed in registers despite
574// // `S`'s nontrivial destructor.
575// struct TRIVIAL_ABI S { ~S(); }
576// ```
Peter Kastingc3dadb022024-09-17 22:44:54577#if __has_cpp_attribute(clang::trivial_abi)
Jeremy Roman810d98d2021-04-06 16:46:07578#define TRIVIAL_ABI [[clang::trivial_abi]]
579#else
580#define TRIVIAL_ABI
581#endif
582
Peter Kasting67944102024-09-18 00:23:57583// Determines whether a type is trivially relocatable, i.e. a move-and-destroy
584// sequence can safely be replaced with `memcpy()`. This is true of types with
585// trivial copy or move construction plus trivial destruction, as well as types
586// marked `TRIVIAL_ABI`. Useful to optimize container implementations.
Adam Ricefb288d02023-10-13 08:36:21587//
588// See also:
589// https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2023/p1144r8.html
Hans Wennborg4ed2c83b2025-05-12 16:39:35590// https://clang.llvm.org/docs/LanguageExtensions.html#:~:text=__builtin_is_cpp_trivially_relocatable
Peter Kasting67944102024-09-18 00:23:57591//
592// Usage:
593// ```
594// if constexpr (IS_TRIVIALLY_RELOCATABLE(T)) {
595// // This block will only be executed if type `T` is trivially relocatable.
596// }
597// ```
Hans Wennborg4ed2c83b2025-05-12 16:39:35598#if HAS_BUILTIN(__builtin_is_cpp_trivially_relocatable)
599#define IS_TRIVIALLY_RELOCATABLE(t) __builtin_is_cpp_trivially_relocatable(t)
600#elif HAS_BUILTIN(__is_trivially_relocatable)
601// TODO(crbug.com/416394845): This is deprecated. Remove once all toolchains
602// have __builtin_is_cpp_trivially_relocatable.
Adam Ricefb288d02023-10-13 08:36:21603#define IS_TRIVIALLY_RELOCATABLE(t) __is_trivially_relocatable(t)
604#else
605#define IS_TRIVIALLY_RELOCATABLE(t) false
606#endif
607
Peter Kasting67944102024-09-18 00:23:57608// Annotates a member function as safe to call on a moved-from object, which it
609// will reinitialize.
610//
611// See also:
612// https://clang.llvm.org/extra/clang-tidy/checks/bugprone/use-after-move.html#reinitialization
613//
614// Usage:
615// ```
616// struct S {
617// REINITIALIZES_AFTER_MOVE void Reset();
618// };
619// void Func1(const S&);
620// void Func2() {
621// S s1;
622// S s2 = std::move(s1);
623// s1.Reset();
624// // clang-tidy's `bugprone-use-after-move` check will not flag the
625// // following call as a use-after-move, due to the intervening `Reset()`.
626// Func1(s1);
627// }
628// ```
Peter Kastingc3dadb022024-09-17 22:44:54629#if __has_cpp_attribute(clang::reinitializes)
Lukasz Anforowicz3be38fbb2021-04-14 20:29:29630#define REINITIALIZES_AFTER_MOVE [[clang::reinitializes]]
631#else
632#define REINITIALIZES_AFTER_MOVE
633#endif
634
Peter Kasting67944102024-09-18 00:23:57635// Annotates a type as owning an object or memory region whose address may be
636// vended to or stored by other objects. For example, `std::unique_ptr<T>` owns
637// a `T` and vends its address via `.get()`, and `std::string` owns a block of
638// `char` and vends its address via `.data()`. Used to detect lifetime errors in
639// conjunction with `GSL_POINTER`; see documentation there.
640//
641// See also:
642// https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#SS-ownership
643// https://clang.llvm.org/docs/AttributeReference.html#owner
644// https://clang.llvm.org/docs/DiagnosticsReference.html#wdangling-gsl
645//
646// Usage:
647// ```
648// // Marking `S` as `GSL_OWNER` enables `-Wdangling-gsl` to detect misuse by
649// // types annotated as `GSL_POINTER`.
650// struct GSL_OWNER S;
651// ```
Peter Kastingc3dadb022024-09-17 22:44:54652#if __has_cpp_attribute(gsl::Owner)
Daniel Cheng8ac305b2022-02-17 00:05:11653#define GSL_OWNER [[gsl::Owner]]
danakjceb17022022-02-11 23:52:01654#else
Jose Dapena Paz1183b142022-02-18 16:28:25655#define GSL_OWNER
Peter Kastingc3dadb022024-09-17 22:44:54656#endif
657
Peter Kasting67944102024-09-18 00:23:57658// Annotates a type as holding a pointer into an owner object (an appropriate
659// STL or `GSL_OWNER`-annotated type). If an instance of the pointer type is
660// constructed from an instance of the owner type, and the owner instance is
661// destroyed, the pointer instance is considered to be dangling. Useful to
662// diagnose some cases of lifetime errors.
663//
664// See also:
665// https://clang.llvm.org/docs/AttributeReference.html#pointer
666//
667// Usage:
668// ```
669// struct GSL_OWNER T {};
670// struct GSL_POINTER S {
671// S(const T&);
672// };
673// S Func() {
674// // The following return will not compile; diagnosed as returning address
675// // of local temporary.
676// return S(T());
677// }
678// ```
Peter Kastingc3dadb022024-09-17 22:44:54679#if __has_cpp_attribute(gsl::Pointer)
680#define GSL_POINTER [[gsl::Pointer]]
681#else
danakjceb17022022-02-11 23:52:01682#define GSL_POINTER
683#endif
684
Peter Kasting67944102024-09-18 00:23:57685// Annotates a type or variable to add a "logically_const" ABI tag to any
686// corresponding mangled symbol name(s). Useful to suppress warnings from the
687// "Mutable Constants" trybot check [1] when logically const instances are named
688// like `kConstants` but for some reason should not be marked `const`.
Daniel Chengf2c05382022-09-16 02:51:42689//
690// [1]:
Peter Kasting67944102024-09-18 00:23:57691// https://chromium.googlesource.com/chromium/src/+/main/docs/speed/binary_size/android_binary_size_trybot.md#Mutable-Constants
692//
693// Usage:
694// ```
695// struct S {};
696// S kConstS; // Fails on some trybots.
697// LOGICALLY_CONST S kAlsoConstS; // OK
698//
699// struct LOGICALLY_CONST T {};
700// T kConstT; // OK
701// ```
Peter Kastingc3dadb022024-09-17 22:44:54702#if __has_cpp_attribute(gnu::abi_tag)
Anthony Vallee-Dubois9dbbbda32022-08-26 01:25:31703#define LOGICALLY_CONST [[gnu::abi_tag("logically_const")]]
704#else
705#define LOGICALLY_CONST
706#endif
707
Peter Kasting67944102024-09-18 00:23:57708// Annotates a function indicating it is cold, but called from hot functions.
709// Useful when a performance-sensitive function is usually simple, but in edge
710// cases must fall back to a more complex handler.
Peter Kastingc3dadb022024-09-17 22:44:54711//
Peter Kasting67944102024-09-18 00:23:57712// On X86-64 and AArch64, this changes the calling convention so most registers
713// are callee-saved, reducing register spills in the caller. This can improve
714// caller performance in the common case, at the cost of pessimizing the callee.
715// On other platforms, this attribute has no effect as of Clang 20.
Peter Kastingc3dadb022024-09-17 22:44:54716//
Peter Kasting67944102024-09-18 00:23:57717// See also:
718// https://clang.llvm.org/docs/AttributeReference.html#preserve-most
719//
720// Usage:
721// ```
722// // Calls to this function will not require most registers to be saved.
723// PRESERVE_MOST void Func();
724// ```
725//
726// Disable `PRESERVE_MOST` in component builds, since `_dl_runtime_resolve()`
727// clobbers registers on platforms where it's used, and the component build is
728// not perf-critical anyway; see
729// https://github.com/llvm/llvm-project/issues/105588.
730//
731// Also disable for Win ARM64 due to as-yet-uninvestigated crashes.
Peter Kastingc3dadb022024-09-17 22:44:54732// TODO(crbug.com/42204008): Investigate, fix, and re-enable.
733#if __has_cpp_attribute(clang::preserve_most) && \
734 (defined(ARCH_CPU_ARM64) || defined(ARCH_CPU_X86_64)) && \
735 !defined(COMPONENT_BUILD) && \
736 !(BUILDFLAG(IS_WIN) && defined(ARCH_CPU_ARM64))
Peter Kastingc3dadb022024-09-17 22:44:54737#define PRESERVE_MOST [[clang::preserve_most]]
Anton Bikineev4d23e842023-06-14 10:46:19738#else
739#define PRESERVE_MOST
740#endif
741
Peter Kasting67944102024-09-18 00:23:57742// Annotates a pointer or reference parameter or return value for a member
743// function as having lifetime intertwined with the instance on which the
744// function is called. For parameters, the function is assumed to store the
745// value into the called-on object, so if the referred-to object is later
746// destroyed, the called-on object is also considered to be dangling. For return
747// values, the value is assumed to point into the called-on object, so if that
748// object is destroyed, the returned value is also considered to be dangling.
749// Useful to diagnose some cases of lifetime errors.
danakjc077a30e2024-03-22 19:25:36750//
Peter Kasting67944102024-09-18 00:23:57751// See also:
752// https://clang.llvm.org/docs/AttributeReference.html#lifetimebound
danakjc077a30e2024-03-22 19:25:36753//
Peter Kasting67944102024-09-18 00:23:57754// Usage:
danakjc077a30e2024-03-22 19:25:36755// ```
Peter Kasting67944102024-09-18 00:23:57756// struct S {
757// S(int* p LIFETIME_BOUND);
758// int* Get() LIFETIME_BOUND;
759// };
760// S Func1() {
761// int i = 0;
762// // The following return will not compile; diagnosed as returning address
763// // of a stack object.
764// return S(&i);
765// }
766// int* Func2(int* p) {
767// // The following return will not compile; diagnosed as returning address
768// // of a local temporary.
769// return S(p).Get();
770// }
danakjc077a30e2024-03-22 19:25:36771// ```
Peter Kastingc3dadb022024-09-17 22:44:54772#if __has_cpp_attribute(clang::lifetimebound)
danakjc077a30e2024-03-22 19:25:36773#define LIFETIME_BOUND [[clang::lifetimebound]]
774#else
775#define LIFETIME_BOUND
776#endif
777
Peter Kasting4b18d0c2024-09-18 00:56:11778// Annotates a function or variable to indicate that it should have weak
779// linkage. Useful for library code that wants code linking against it to be
780// able to override its functionality; inside a single target, this is better
781// accomplished via virtual methods and other more standard mechanisms.
782//
783// Any weak definition of a symbol will be overridden at link time by a non-weak
784// definition. Marking a `const` or `constexpr` variable weak makes it no longer
785// be considered a compile-time constant, since its value may be different after
786// linking.
787//
788// Multiple weak definitions of a symbol may exist, in which case the linker is
789// free to select any when there are no non-weak definitions. Like with symbols
790// marked `inline`, this can lead to subtle, difficult-to-diagnose bugs if not
791// all definitions are identical.
792//
793// A weak declaration that has no definitions at link time will be linked as if
794// the corresponding address is null. Therefore library code can use weak
795// declarations and conditionals to allow consumers to provide optional
796// customizations.
797//
798// See also:
799// https://clang.llvm.org/docs/AttributeReference.html#weak
800//
801// Usage:
802// ```
803// // The following definition defaults `x` to 10, but allows other object
804// // files to override its value. Thus, despite `constexpr`, `x` is not
805// // considered a compile-time constant (and cannot be used in a `constexpr`
806// // context).
807// extern const int x;
808// WEAK_SYMBOL constexpr int x = 10;
809//
810// // The following declaration allows linking to occur whether a definition
811// // of `Func()` is provided or not; if none is present, `&Func` will
812// // evaluate to `nullptr` at runtime.
813// WEAK_SYMBOL void Func();
814//
815// // The following definition provides a default implementation of `Func2()`,
816// // but allows other object files to override.
817// WEAK_SYMBOL void Func2() { ... }
818// ```
819#if __has_cpp_attribute(gnu::weak)
820#define WEAK_SYMBOL [[gnu::weak]]
821#else
822#define WEAK_SYMBOL
823#endif
824
825// Annotates a function indicating that the compiler should not convert calls
826// within it to tail calls.
827//
828// For a callee-side version of this, see `NOT_TAIL_CALLED`.
829//
830// See also:
831// https://clang.llvm.org/docs/AttributeReference.html#disable-tail-calls
832// Usage:
833// ```
834// DISABLE_TAIL_CALLS void Func() {
835// // Function calls in this body will not be tail calls.
836// }
837// ```
838#if __has_cpp_attribute(clang::disable_tail_calls)
839#define DISABLE_TAIL_CALLS [[clang::disable_tail_calls]]
840#else
841#define DISABLE_TAIL_CALLS
842#endif
843
844// Annotates a type or member indicating the minimum possible alignment (one bit
845// for bitfields, one byte otherwise) should be used. This can be used to
846// eliminate padding inside objects, at the cost of potentially pessimizing
847// code, or even generating invalid code (depending on platform restrictions) if
848// underaligned objects have their addresses taken and passed elsewhere.
849//
850// This is similar to the more-broadly-supported `#pragma pack(1)`.
851//
852// See also:
853// https://gcc.gnu.org/onlinedocs/gcc/Common-Variable-Attributes.html#index-packed-variable-attribute
854//
855// Usage:
856// ```
857// struct PACKED_OBJ S1 {
858// int8_t a; // Alignment 1, offset 0, size 1
859// int32_t b; // Alignment 1, offset 1 (0 bytes padding), size 4
860// }; // Overall alignment 1, 0 bytes trailing padding, overall size 5
861//
862// struct S2 {
863// int8_t a; // Alignment 1, offset 0, size 1
864// int32_t b; // Alignment 4, offset 4 (3 bytes padding), size 4
865// int8_t c; // Alignment 1, offset 8 (0 bytes padding), size 1
866// PACKED_OBJ int32_t d; // Alignment 1, offset 9 (0 bytes padding), size 4
867// }; // Overall alignment 4, 3 bytes trailing padding, overall size 16
868// ```
869#if __has_cpp_attribute(gnu::packed)
870#define PACKED_OBJ [[gnu::packed]]
871#else
872#define PACKED_OBJ
873#endif
874
875// Annotates a function indicating that the returned pointer will never be null.
876// This may allow the compiler to assume null checks on the caller side are
877// unnecessary.
878//
879// In practice, this is usually better-handled by returning a value or
880// reference, which enforce such guarantees at the type level.
881//
882// See also:
883// https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html#index-returns_005fnonnull-function-attribute
884// https://clang.llvm.org/docs/AttributeReference.html#nullability-attributes
885//
886// Usage:
887// ```
888// // The following function will never return `nullptr`.
889// RETURNS_NONNULL int* Func();
890// ```
891#if __has_cpp_attribute(gnu::returns_nonnull)
892#define RETURNS_NONNULL [[gnu::returns_nonnull]]
893#else
894#define RETURNS_NONNULL
895#endif
896
897// Annotates a function indicating it is const, meaning that it has no
898// observable side effects and its return value depends only on its arguments.
899// Const functions may not read external memory other than unchanging objects
900// (e.g. non-volatile constants), and the compiler is free to replace calls to
901// them with the return values of earlier calls with the same arguments no
902// matter what other state might have changed in the meantime.
903//
904// This is a much stronger restriction than `const`-qualified functions, and is
905// rarely appropriate outside small local helpers, which are frequently
906// inlineable anyway and would not really benefit.
907//
908// WARNING: Misusing this attribute can lead to silent miscompilation, UB, and
909// difficult-to-diagnose bugs. For this and the above reason, usage should be
910// very rare.
911//
912// See also:
913// https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html#index-const-function-attribute
914//
915// Usage:
916// ```
917// // The compiler may replace calls to this function with values returned
918// // from earlier calls, assuming the args match.
919// CONST_FUNCTION int Func(int);
920// ```
921#if __has_cpp_attribute(gnu::const)
922#define CONST_FUNCTION [[gnu::const]]
923#else
924#define CONST_FUNCTION
925#endif
926
Peter Kasting67944102024-09-18 00:23:57927// Annotates a function indicating it is pure, meaning that it has no observable
928// side effects. Unlike functions annotated `CONST_FUNCTION`, pure functions may
929// still read external memory, and thus their return values may change between
930// calls. `strlen()` and `memcmp()` are examples of pure functions. Useful to
931// allow folding/reordering calls for optimization purposes.
danakjc077a30e2024-03-22 19:25:36932//
Peter Kasting67944102024-09-18 00:23:57933// WARNING: Misusing this attribute can lead to silent miscompilation, UB, and
934// difficult-to-diagnose bugs. Because apparently-safe invocations can sometimes
935// have side effects (especially when invoking "overridable" functionality like
936// virtual or templated methods), such misuse is far more likely than it seems.
937// Therefore, this macro should generally be used only in key vocabulary types,
938// where the perf and ergonomic benefits of callers not needing to worry about
939// caching results in local variables in hot code outweighs the risks.
danakjc077a30e2024-03-22 19:25:36940//
Peter Kasting67944102024-09-18 00:23:57941// See also:
942// https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html#index-pure-function-attribute
943//
944// Usage:
945// ```
946// // Calls to this function may be subject to more aggressive common
947// // subexpression (CSE) optimization.
948// PURE_FUNCTION int Func(int);
949// ```
Peter Kastingc3dadb022024-09-17 22:44:54950#if __has_cpp_attribute(gnu::pure)
danakjc077a30e2024-03-22 19:25:36951#define PURE_FUNCTION [[gnu::pure]]
952#else
953#define PURE_FUNCTION
954#endif
955
danakj22031fb12024-11-08 14:52:30956// Annotates a function or class data member indicating it can lead to
957// out-of-bounds accesses (OOB) if given incorrect inputs.
danakj59f56d92024-02-01 15:31:35958//
danakj22031fb12024-11-08 14:52:30959// For functions, this commonly includes functions which take pointers, sizes,
960// iterators, sentinels, etc. and cannot fully check their preconditions (e.g.
961// that the provided pointer actually points to an allocation of at least the
962// provided size). Useful to diagnose potential misuse via
963// `-Wunsafe-buffer-usage`, as well as to mark functions potentially in need of
964// safer alternatives.
965//
966// For fields, this would be used to annotate both pointer and size fields that
967// have not yet been converted to a span.
968//
Tom Sepez543e036972025-05-06 00:16:19969// All functions or fields annotated with this macro should come with a
970// `// PRECONDITIONS: ` comment that explains what the caller must guarantee
971// to ensure safe operation. Callers can then write `// SAFETY: ` comments
972// explaining why the specific preconditions have been met.
973//
danakj22031fb12024-11-08 14:52:30974// Ideally, unsafe functions should also be paired with a safer version, e.g.
975// one that replaces pointer parameters with `span`s; otherwise, document safer
976// replacement coding patterns callers can migrate to.
danakj59f56d92024-02-01 15:31:35977//
Peter Kasting67944102024-09-18 00:23:57978// Annotating a function `UNSAFE_BUFFER_USAGE` means all call sites (that do not
979// disable the warning) must wrap calls in `UNSAFE_BUFFERS()`; see documentation
danakj22031fb12024-11-08 14:52:30980// there. Annotating a field `UNSAFE_BUFFER_USAGE` means that `UNSAFE_BUFFERS()`
981// must wrap expressions that mutate of the field.
Peter Kasting67944102024-09-18 00:23:57982//
983// See also:
danakj22031fb12024-11-08 14:52:30984// https://chromium.googlesource.com/chromium/src/+/main/docs/unsafe_buffers.md
985// https://clang.llvm.org/docs/SafeBuffers.html
Peter Kasting67944102024-09-18 00:23:57986// https://clang.llvm.org/docs/DiagnosticsReference.html#wunsafe-buffer-usage
987//
988// Usage:
danakj59f56d92024-02-01 15:31:35989// ```
Peter Kasting67944102024-09-18 00:23:57990// // Calls to this function must be wrapped in `UNSAFE_BUFFERS()`.
991// UNSAFE_BUFFER_USAGE void Func(T* input, T* end);
danakj22031fb12024-11-08 14:52:30992//
993// struct S {
994// // Changing this pointer requires `UNSAFE_BUFFERS()`.
995// UNSAFE_BUFFER_USAGE int* p;
996// };
danakj59f56d92024-02-01 15:31:35997// ```
Peter Kastingc3dadb022024-09-17 22:44:54998#if __has_cpp_attribute(clang::unsafe_buffer_usage)
danakj59f56d92024-02-01 15:31:35999#define UNSAFE_BUFFER_USAGE [[clang::unsafe_buffer_usage]]
1000#else
1001#define UNSAFE_BUFFER_USAGE
1002#endif
1003
Peter Kasting67944102024-09-18 00:23:571004// Annotates code indicating that it should be permanently exempted from
1005// `-Wunsafe-buffer-usage`. For temporary cases such as migrating callers to
1006// safer patterns, use `UNSAFE_TODO()` instead; see documentation there.
1007//
1008// All calls to functions annotated with `UNSAFE_BUFFER_USAGE` must be marked
1009// with one of these two macros; they can also be used around pointer
1010// arithmetic, pointer subscripting, and the like.
1011//
1012// ** USE OF THIS MACRO SHOULD BE VERY RARE.** Using this macro indicates that
1013// the compiler cannot verify that the code avoids OOB, and manual review is
1014// required. Even with manual review, it's easy for assumptions to change and
1015// security bugs to creep in over time. Prefer safer patterns instead.
1016//
1017// Usage should wrap the minimum necessary code, and *must* include a
1018// `// SAFETY: ...` comment that explains how the code guarantees safety or
1019// meets the requirements of called `UNSAFE_BUFFER_USAGE` functions. Guarantees
1020// must be manually verifiable by the Chrome security team using only local
1021// invariants; contact [email protected] to schedule such a review. Valid
1022// invariants include:
1023// - Runtime conditions or `CHECK()`s nearby
1024// - Invariants guaranteed by types in the surrounding code
1025// - Invariants guaranteed by function calls in the surrounding code
1026// - Caller requirements, if the containing function is itself annotated with
1027// `UNSAFE_BUFFER_USAGE`; this is less safe and should be a last resort
1028//
danakj22031fb12024-11-08 14:52:301029// See also:
1030// https://chromium.googlesource.com/chromium/src/+/main/docs/unsafe_buffers.md
1031// https://clang.llvm.org/docs/SafeBuffers.html
1032// https://clang.llvm.org/docs/DiagnosticsReference.html#wunsafe-buffer-usage
1033//
Peter Kasting67944102024-09-18 00:23:571034// Usage:
1035// ```
1036// // The following call will not trigger a compiler warning even if `Func()`
1037// // is annotated `UNSAFE_BUFFER_USAGE`.
1038// return UNSAFE_BUFFERS(Func(input, end));
1039// ```
1040//
Peter Kastingc3dadb022024-09-17 22:44:541041// Test for `__clang__` directly, as there's no `__has_pragma` or similar (see
1042// https://github.com/llvm/llvm-project/issues/51887).
1043#if defined(__clang__)
Peter Kasting67944102024-09-18 00:23:571044// Disabling `clang-format` allows each `_Pragma` to be on its own line, as
1045// recommended by https://gcc.gnu.org/onlinedocs/cpp/Pragmas.html.
Peter Kastingc3dadb022024-09-17 22:44:541046// clang-format off
danakj59f56d92024-02-01 15:31:351047#define UNSAFE_BUFFERS(...) \
1048 _Pragma("clang unsafe_buffer_usage begin") \
1049 __VA_ARGS__ \
1050 _Pragma("clang unsafe_buffer_usage end")
1051// clang-format on
1052#else
1053#define UNSAFE_BUFFERS(...) __VA_ARGS__
1054#endif
1055
Peter Kasting67944102024-09-18 00:23:571056// Annotates code indicating that it should be temporarily exempted from
1057// `-Wunsafe-buffer-usage`. While this is functionally the same as
1058// `UNSAFE_BUFFERS()`, semantically it indicates that this is for migration
1059// purposes, and should be cleaned up as soon as possible.
1060//
1061// Usage:
1062// ```
1063// // The following call will not trigger a compiler warning even if `Func()`
1064// // is annotated `UNSAFE_BUFFER_USAGE`.
1065// return UNSAFE_TODO(Func(input, end));
1066// ```
Tom Sepezea67b6e2024-08-08 18:17:271067#define UNSAFE_TODO(...) UNSAFE_BUFFERS(__VA_ARGS__)
1068
Peter Kasting67944102024-09-18 00:23:571069// Annotates a function restricting its availability based on compile-time
1070// information in the evaluated context. Useful to convert runtime errors to
1071// compile-time errors if functions' arguments are always known at compile time.
danakjc077a30e2024-03-22 19:25:361072//
Peter Kasting67944102024-09-18 00:23:571073// SFINAE and `requires` clauses can restrict function availability based on the
1074// unevaluated context (type information and syntactic correctness). This
1075// provides a similar capability based on the evaluated context (variable
1076// values). If the condition fails, or cannot be determined at compile time, the
1077// function is excluded from the overload set.
danakjc077a30e2024-03-22 19:25:361078//
Peter Kasting67944102024-09-18 00:23:571079// Some use cases could be satisfied without this by marking the function
1080// `consteval` and breaking compile when the condition fails (e.g. via
1081// `CHECK()`/`assert()`). However, `ENABLE_IF_ATTR()` is generally superior:
1082// - Not all desired functions can be made `consteval`; e.g. most
1083// constructors.
1084// - The error message in the macro case is clearer and more actionable.
1085// - `ENABLE_IF_ATTR()` interacts better with template metaprogramming.
1086//
1087// See also:
1088// https://clang.llvm.org/docs/AttributeReference.html#enable-if
1089// https://github.com/chromium/subspace/issues/266
1090//
1091// Usage:
danakjc077a30e2024-03-22 19:25:361092// ```
Peter Kasting67944102024-09-18 00:23:571093// void NotConsteval(int a) {
1094// assert(a > 0);
1095// }
1096// consteval void WithoutEnableIf(int a) {
1097// assert(a > 0);
1098// }
1099// void WithEnableIf(int a) ENABLE_IF_ATTR(a > 0, "arg must be positive") {}
1100// void Func(int i) {
1101// // Compiles; assertion fails at runtime.
1102// NotConsteval(-1);
danakjc077a30e2024-03-22 19:25:361103//
Peter Kasting67944102024-09-18 00:23:571104// // Will not compile; diagnosed as not a constant expression.
1105// WithoutEnableIf(-1);
1106//
1107// // Will not compile; diagnosed as no matching function call with
1108// // "note: candidate disabled: arg must be positive".
1109// WithEnableIf(-1);
1110//
1111// // Will not compile (same reason). Marking `Func()` as
1112// // `ENABLE_IF_ATTR(i > 0, ...)` will not help; the compiler's analysis is
1113// // not sufficiently sophisticated to propagate this constraint.
1114// WithEnableIf(i);
1115// }
1116// ```
Peter Kastingc3dadb022024-09-17 22:44:541117#if HAS_ATTRIBUTE(enable_if)
danakjc077a30e2024-03-22 19:25:361118#define ENABLE_IF_ATTR(cond, msg) __attribute__((enable_if(cond, msg)))
1119#else
1120#define ENABLE_IF_ATTR(cond, msg)
1121#endif
1122
[email protected]dd9afc0b2008-11-21 23:58:091123#endif // BASE_COMPILER_SPECIFIC_H_