1 // Copyright 2012 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #ifndef BASE_COMPILER_SPECIFIC_H_
6 #define BASE_COMPILER_SPECIFIC_H_
7
8 #include "build/build_config.h"
9
10 #if defined(COMPILER_MSVC) && !defined(__clang__)
11 #error "Only clang-cl is supported on Windows, see https://crbug.com/988071"
12 #endif
13
14 // This is a wrapper around `__has_cpp_attribute`, which can be used to test for
15 // the presence of an attribute. In case the compiler does not support this
16 // macro it will simply evaluate to 0.
17 //
18 // References:
19 // https://wg21.link/sd6#testing-for-the-presence-of-an-attribute-__has_cpp_attribute
20 // https://wg21.link/cpp.cond#:__has_cpp_attribute
21 #if defined(__has_cpp_attribute)
22 #define HAS_CPP_ATTRIBUTE(x) __has_cpp_attribute(x)
23 #else
24 #define HAS_CPP_ATTRIBUTE(x) 0
25 #endif
26
27 // A wrapper around `__has_attribute`, similar to HAS_CPP_ATTRIBUTE.
28 #if defined(__has_attribute)
29 #define HAS_ATTRIBUTE(x) __has_attribute(x)
30 #else
31 #define HAS_ATTRIBUTE(x) 0
32 #endif
33
34 // A wrapper around `__has_builtin`, similar to HAS_CPP_ATTRIBUTE.
35 #if defined(__has_builtin)
36 #define HAS_BUILTIN(x) __has_builtin(x)
37 #else
38 #define HAS_BUILTIN(x) 0
39 #endif
40
41 // Annotate a function indicating it should not be inlined.
42 // Use like:
43 // NOINLINE void DoStuff() { ... }
44 #if defined(__clang__) && HAS_ATTRIBUTE(noinline)
45 #define NOINLINE [[clang::noinline]]
46 #elif defined(COMPILER_GCC) && HAS_ATTRIBUTE(noinline)
47 #define NOINLINE __attribute__((noinline))
48 #elif defined(COMPILER_MSVC)
49 #define NOINLINE __declspec(noinline)
50 #else
51 #define NOINLINE
52 #endif
53
54 // Annotate a function indicating it should not be optimized.
55 #if defined(__clang__) && HAS_ATTRIBUTE(optnone)
56 #define NOOPT [[clang::optnone]]
57 #elif defined(COMPILER_GCC) && HAS_ATTRIBUTE(optimize)
58 #define NOOPT __attribute__((optimize(0)))
59 #else
60 #define NOOPT
61 #endif
62
63 #if defined(__clang__) && defined(NDEBUG) && HAS_ATTRIBUTE(always_inline)
64 #define ALWAYS_INLINE [[clang::always_inline]] inline
65 #elif defined(COMPILER_GCC) && defined(NDEBUG) && HAS_ATTRIBUTE(always_inline)
66 #define ALWAYS_INLINE inline __attribute__((__always_inline__))
67 #elif defined(COMPILER_MSVC) && defined(NDEBUG)
68 #define ALWAYS_INLINE __forceinline
69 #else
70 #define ALWAYS_INLINE inline
71 #endif
72
73 // Annotate a function indicating it should never be tail called. Useful to make
74 // sure callers of the annotated function are never omitted from call-stacks.
75 // To provide the complementary behavior (prevent the annotated function from
76 // being omitted) look at NOINLINE. Also note that this doesn't prevent code
77 // folding of multiple identical caller functions into a single signature. To
78 // prevent code folding, see NO_CODE_FOLDING() in base/debug/alias.h.
79 // Use like:
80 // NOT_TAIL_CALLED void FooBar();
81 #if defined(__clang__) && HAS_ATTRIBUTE(not_tail_called)
82 #define NOT_TAIL_CALLED [[clang::not_tail_called]]
83 #else
84 #define NOT_TAIL_CALLED
85 #endif
86
87 // Specify memory alignment for structs, classes, etc.
88 // Use like:
89 // class ALIGNAS(16) MyClass { ... }
90 // ALIGNAS(16) int array[4];
91 //
92 // In most places you can use the C++11 keyword "alignas", which is preferred.
93 //
94 // Historically, compilers had trouble mixing __attribute__((...)) syntax with
95 // alignas(...) syntax. However, at least Clang is very accepting nowadays. It
96 // may be that this macro can be removed entirely.
97 #if defined(__clang__)
98 #define ALIGNAS(byte_alignment) alignas(byte_alignment)
99 #elif defined(COMPILER_MSVC)
100 #define ALIGNAS(byte_alignment) __declspec(align(byte_alignment))
101 #elif defined(COMPILER_GCC) && HAS_ATTRIBUTE(aligned)
102 #define ALIGNAS(byte_alignment) __attribute__((aligned(byte_alignment)))
103 #endif
104
105 // In case the compiler supports it NO_UNIQUE_ADDRESS evaluates to the C++20
106 // attribute [[no_unique_address]]. This allows annotating data members so that
107 // they need not have an address distinct from all other non-static data members
108 // of its class.
109 //
110 // References:
111 // * https://en.cppreference.com/w/cpp/language/attributes/no_unique_address
112 // * https://wg21.link/dcl.attr.nouniqueaddr
113 #if defined(COMPILER_MSVC) && HAS_CPP_ATTRIBUTE(msvc::no_unique_address)
114 // Unfortunately MSVC ignores [[no_unique_address]] (see
115 // https://devblogs.microsoft.com/cppblog/msvc-cpp20-and-the-std-cpp20-switch/#msvc-extensions-and-abi),
116 // and clang-cl matches it for ABI compatibility reasons. We need to prefer
117 // [[msvc::no_unique_address]] when available if we actually want any effect.
118 #define NO_UNIQUE_ADDRESS [[msvc::no_unique_address]]
119 #elif HAS_CPP_ATTRIBUTE(no_unique_address)
120 #define NO_UNIQUE_ADDRESS [[no_unique_address]]
121 #else
122 #define NO_UNIQUE_ADDRESS
123 #endif
124
125 // Tells the compiler a function is using a printf-style format string.
126 // |format_param| is the one-based index of the format string parameter;
127 // |dots_param| is the one-based index of the "..." parameter.
128 // For v*printf functions (which take a va_list), pass 0 for dots_param.
129 // (This is undocumented but matches what the system C headers do.)
130 // For member functions, the implicit this parameter counts as index 1.
131 #if (defined(COMPILER_GCC) || defined(__clang__)) && HAS_ATTRIBUTE(format)
132 #define PRINTF_FORMAT(format_param, dots_param) \
133 __attribute__((format(printf, format_param, dots_param)))
134 #else
135 #define PRINTF_FORMAT(format_param, dots_param)
136 #endif
137
138 // WPRINTF_FORMAT is the same, but for wide format strings.
139 // This doesn't appear to yet be implemented in any compiler.
140 // See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=38308 .
141 #define WPRINTF_FORMAT(format_param, dots_param)
142 // If available, it would look like:
143 // __attribute__((format(wprintf, format_param, dots_param)))
144
145 // Sanitizers annotations.
146 #if HAS_ATTRIBUTE(no_sanitize)
147 #define NO_SANITIZE(what) __attribute__((no_sanitize(what)))
148 #endif
149 #if !defined(NO_SANITIZE)
150 #define NO_SANITIZE(what)
151 #endif
152
153 // MemorySanitizer annotations.
154 #if defined(MEMORY_SANITIZER) && !BUILDFLAG(IS_NACL)
155 #include <sanitizer/msan_interface.h>
156
157 // Mark a memory region fully initialized.
158 // Use this to annotate code that deliberately reads uninitialized data, for
159 // example a GC scavenging root set pointers from the stack.
160 #define MSAN_UNPOISON(p, size) __msan_unpoison(p, size)
161
162 // Check a memory region for initializedness, as if it was being used here.
163 // If any bits are uninitialized, crash with an MSan report.
164 // Use this to sanitize data which MSan won't be able to track, e.g. before
165 // passing data to another process via shared memory.
166 #define MSAN_CHECK_MEM_IS_INITIALIZED(p, size) \
167 __msan_check_mem_is_initialized(p, size)
168 #else // MEMORY_SANITIZER
169 #define MSAN_UNPOISON(p, size)
170 #define MSAN_CHECK_MEM_IS_INITIALIZED(p, size)
171 #endif // MEMORY_SANITIZER
172
173 // DISABLE_CFI_PERF -- Disable Control Flow Integrity for perf reasons.
174 #if !defined(DISABLE_CFI_PERF)
175 #if defined(__clang__) && defined(OFFICIAL_BUILD)
176 #define DISABLE_CFI_PERF NO_SANITIZE("cfi")
177 #else
178 #define DISABLE_CFI_PERF
179 #endif
180 #endif
181
182 // DISABLE_CFI_ICALL -- Disable Control Flow Integrity indirect call checks.
183 // Security Note: if you just need to allow calling of dlsym functions use
184 // DISABLE_CFI_DLSYM.
185 #if !defined(DISABLE_CFI_ICALL)
186 #if BUILDFLAG(IS_WIN)
187 // Windows also needs __declspec(guard(nocf)).
188 #define DISABLE_CFI_ICALL NO_SANITIZE("cfi-icall") __declspec(guard(nocf))
189 #else
190 #define DISABLE_CFI_ICALL NO_SANITIZE("cfi-icall")
191 #endif
192 #endif
193 #if !defined(DISABLE_CFI_ICALL)
194 #define DISABLE_CFI_ICALL
195 #endif
196
197 // DISABLE_CFI_DLSYM -- applies DISABLE_CFI_ICALL on platforms where dlsym
198 // functions must be called. Retains CFI checks on platforms where loaded
199 // modules participate in CFI (e.g. Windows).
200 #if !defined(DISABLE_CFI_DLSYM)
201 #if BUILDFLAG(IS_WIN)
202 // Windows modules register functions when loaded so can be checked by CFG.
203 #define DISABLE_CFI_DLSYM
204 #else
205 #define DISABLE_CFI_DLSYM DISABLE_CFI_ICALL
206 #endif
207 #endif
208 #if !defined(DISABLE_CFI_DLSYM)
209 #define DISABLE_CFI_DLSYM
210 #endif
211
212 // Macro useful for writing cross-platform function pointers.
213 #if !defined(CDECL)
214 #if BUILDFLAG(IS_WIN)
215 #define CDECL __cdecl
216 #else // BUILDFLAG(IS_WIN)
217 #define CDECL
218 #endif // BUILDFLAG(IS_WIN)
219 #endif // !defined(CDECL)
220
221 // Macro for hinting that an expression is likely to be false.
222 #if !defined(UNLIKELY)
223 #if defined(COMPILER_GCC) || defined(__clang__)
224 #define UNLIKELY(x) __builtin_expect(!!(x), 0)
225 #else
226 #define UNLIKELY(x) (x)
227 #endif // defined(COMPILER_GCC)
228 #endif // !defined(UNLIKELY)
229
230 #if !defined(LIKELY)
231 #if defined(COMPILER_GCC) || defined(__clang__)
232 #define LIKELY(x) __builtin_expect(!!(x), 1)
233 #else
234 #define LIKELY(x) (x)
235 #endif // defined(COMPILER_GCC)
236 #endif // !defined(LIKELY)
237
238 // Compiler feature-detection.
239 // clang.llvm.org/docs/LanguageExtensions.html#has-feature-and-has-extension
240 #if defined(__has_feature)
241 #define HAS_FEATURE(FEATURE) __has_feature(FEATURE)
242 #else
243 #define HAS_FEATURE(FEATURE) 0
244 #endif
245
246 #if defined(COMPILER_GCC)
247 #define PRETTY_FUNCTION __PRETTY_FUNCTION__
248 #elif defined(COMPILER_MSVC)
249 #define PRETTY_FUNCTION __FUNCSIG__
250 #else
251 // See https://en.cppreference.com/w/c/language/function_definition#func
252 #define PRETTY_FUNCTION __func__
253 #endif
254
255 #if !defined(CPU_ARM_NEON)
256 #if defined(__arm__)
257 #if !defined(__ARMEB__) && !defined(__ARM_EABI__) && !defined(__EABI__) && \
258 !defined(__VFP_FP__) && !defined(_WIN32_WCE) && !defined(ANDROID)
259 #error Chromium does not support middle endian architecture
260 #endif
261 #if defined(__ARM_NEON__)
262 #define CPU_ARM_NEON 1
263 #endif
264 #endif // defined(__arm__)
265 #endif // !defined(CPU_ARM_NEON)
266
267 #if !defined(HAVE_MIPS_MSA_INTRINSICS)
268 #if defined(__mips_msa) && defined(__mips_isa_rev) && (__mips_isa_rev >= 5)
269 #define HAVE_MIPS_MSA_INTRINSICS 1
270 #endif
271 #endif
272
273 #if defined(__clang__) && HAS_ATTRIBUTE(uninitialized)
274 // Attribute "uninitialized" disables -ftrivial-auto-var-init=pattern for
275 // the specified variable.
276 // Library-wide alternative is
277 // 'configs -= [ "//build/config/compiler:default_init_stack_vars" ]' in .gn
278 // file.
279 //
280 // See "init_stack_vars" in build/config/compiler/BUILD.gn and
281 // http://crbug.com/977230
282 // "init_stack_vars" is enabled for non-official builds and we hope to enable it
283 // in official build in 2020 as well. The flag writes fixed pattern into
284 // uninitialized parts of all local variables. In rare cases such initialization
285 // is undesirable and attribute can be used:
286 // 1. Degraded performance
287 // In most cases compiler is able to remove additional stores. E.g. if memory is
288 // never accessed or properly initialized later. Preserved stores mostly will
289 // not affect program performance. However if compiler failed on some
290 // performance critical code we can get a visible regression in a benchmark.
291 // 2. memset, memcpy calls
292 // Compiler may replaces some memory writes with memset or memcpy calls. This is
293 // not -ftrivial-auto-var-init specific, but it can happen more likely with the
294 // flag. It can be a problem if code is not linked with C run-time library.
295 //
296 // Note: The flag is security risk mitigation feature. So in future the
297 // attribute uses should be avoided when possible. However to enable this
298 // mitigation on the most of the code we need to be less strict now and minimize
299 // number of exceptions later. So if in doubt feel free to use attribute, but
300 // please document the problem for someone who is going to cleanup it later.
301 // E.g. platform, bot, benchmark or test name in patch description or next to
302 // the attribute.
303 #define STACK_UNINITIALIZED [[clang::uninitialized]]
304 #else
305 #define STACK_UNINITIALIZED
306 #endif
307
308 // Attribute "no_stack_protector" disables -fstack-protector for the specified
309 // function.
310 //
311 // "stack_protector" is enabled on most POSIX builds. The flag adds a canary
312 // to each stack frame, which on function return is checked against a reference
313 // canary. If the canaries do not match, it's likely that a stack buffer
314 // overflow has occurred, so immediately crashing will prevent exploitation in
315 // many cases.
316 //
317 // In some cases it's desirable to remove this, e.g. on hot functions, or if
318 // we have purposely changed the reference canary.
319 #if defined(COMPILER_GCC) || defined(__clang__)
320 #if HAS_ATTRIBUTE(__no_stack_protector__)
321 #define NO_STACK_PROTECTOR __attribute__((__no_stack_protector__))
322 #else
323 #define NO_STACK_PROTECTOR __attribute__((__optimize__("-fno-stack-protector")))
324 #endif
325 #else
326 #define NO_STACK_PROTECTOR
327 #endif
328
329 // The ANALYZER_ASSUME_TRUE(bool arg) macro adds compiler-specific hints
330 // to Clang which control what code paths are statically analyzed,
331 // and is meant to be used in conjunction with assert & assert-like functions.
332 // The expression is passed straight through if analysis isn't enabled.
333 //
334 // ANALYZER_SKIP_THIS_PATH() suppresses static analysis for the current
335 // codepath and any other branching codepaths that might follow.
336 #if defined(__clang_analyzer__)
337
AnalyzerNoReturn()338 inline constexpr bool AnalyzerNoReturn() __attribute__((analyzer_noreturn)) {
339 return false;
340 }
341
AnalyzerAssumeTrue(bool arg)342 inline constexpr bool AnalyzerAssumeTrue(bool arg) {
343 // AnalyzerNoReturn() is invoked and analysis is terminated if |arg| is
344 // false.
345 return arg || AnalyzerNoReturn();
346 }
347
348 #define ANALYZER_ASSUME_TRUE(arg) ::AnalyzerAssumeTrue(!!(arg))
349 #define ANALYZER_SKIP_THIS_PATH() static_cast<void>(::AnalyzerNoReturn())
350
351 #else // !defined(__clang_analyzer__)
352
353 #define ANALYZER_ASSUME_TRUE(arg) (arg)
354 #define ANALYZER_SKIP_THIS_PATH()
355
356 #endif // defined(__clang_analyzer__)
357
358 // Use nomerge attribute to disable optimization of merging multiple same calls.
359 #if defined(__clang__) && HAS_ATTRIBUTE(nomerge)
360 #define NOMERGE [[clang::nomerge]]
361 #else
362 #define NOMERGE
363 #endif
364
365 // Marks a type as being eligible for the "trivial" ABI despite having a
366 // non-trivial destructor or copy/move constructor. Such types can be relocated
367 // after construction by simply copying their memory, which makes them eligible
368 // to be passed in registers. The canonical example is std::unique_ptr.
369 //
370 // Use with caution; this has some subtle effects on constructor/destructor
371 // ordering and will be very incorrect if the type relies on its address
372 // remaining constant. When used as a function argument (by value), the value
373 // may be constructed in the caller's stack frame, passed in a register, and
374 // then used and destructed in the callee's stack frame. A similar thing can
375 // occur when values are returned.
376 //
377 // TRIVIAL_ABI is not needed for types which have a trivial destructor and
378 // copy/move constructors, such as base::TimeTicks and other POD.
379 //
380 // It is also not likely to be effective on types too large to be passed in one
381 // or two registers on typical target ABIs.
382 //
383 // See also:
384 // https://clang.llvm.org/docs/AttributeReference.html#trivial-abi
385 // https://libcxx.llvm.org/docs/DesignDocs/UniquePtrTrivialAbi.html
386 #if defined(__clang__) && HAS_ATTRIBUTE(trivial_abi)
387 #define TRIVIAL_ABI [[clang::trivial_abi]]
388 #else
389 #define TRIVIAL_ABI
390 #endif
391
392 // Detect whether a type is trivially relocatable, ie. a move-and-destroy
393 // sequence can replaced with memmove(). This can be used to optimise the
394 // implementation of containers. This is automatically true for types that were
395 // defined with TRIVIAL_ABI such as scoped_refptr.
396 //
397 // See also:
398 // https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2023/p1144r8.html
399 // https://clang.llvm.org/docs/LanguageExtensions.html#:~:text=__is_trivially_relocatable
400 #if defined(__clang__) && HAS_BUILTIN(__is_trivially_relocatable)
401 #define IS_TRIVIALLY_RELOCATABLE(t) __is_trivially_relocatable(t)
402 #else
403 #define IS_TRIVIALLY_RELOCATABLE(t) false
404 #endif
405
406 // Marks a member function as reinitializing a moved-from variable.
407 // See also
408 // https://clang.llvm.org/extra/clang-tidy/checks/bugprone/use-after-move.html#reinitialization
409 #if defined(__clang__) && HAS_ATTRIBUTE(reinitializes)
410 #define REINITIALIZES_AFTER_MOVE [[clang::reinitializes]]
411 #else
412 #define REINITIALIZES_AFTER_MOVE
413 #endif
414
415 #if defined(__clang__)
416 #define GSL_OWNER [[gsl::Owner]]
417 #define GSL_POINTER [[gsl::Pointer]]
418 #else
419 #define GSL_OWNER
420 #define GSL_POINTER
421 #endif
422
423 // Adds the "logically_const" tag to a symbol's mangled name. The "Mutable
424 // Constants" check [1] detects instances of constants that aren't in .rodata,
425 // e.g. due to a missing `const`. Using this tag suppresses the check for this
426 // symbol, allowing it to live outside .rodata without a warning.
427 //
428 // [1]:
429 // https://crsrc.org/c/docs/speed/binary_size/android_binary_size_trybot.md#Mutable-Constants
430 #if defined(COMPILER_GCC) || defined(__clang__)
431 #define LOGICALLY_CONST [[gnu::abi_tag("logically_const")]]
432 #else
433 #define LOGICALLY_CONST
434 #endif
435
436 // preserve_most clang's calling convention. Reduces register pressure for the
437 // caller and as such can be used for cold calls. Support for the
438 // "preserve_most" attribute is limited:
439 // - 32-bit platforms do not implement it,
440 // - component builds fail because _dl_runtime_resolve() clobbers registers,
441 // - there are crashes on arm64 on Windows (https://crbug.com/v8/14065), which
442 // can hopefully be fixed in the future.
443 // Additionally, the initial implementation in clang <= 16 overwrote the return
444 // register(s) in the epilogue of a preserve_most function, so we only use
445 // preserve_most in clang >= 17 (see https://reviews.llvm.org/D143425).
446 // Clang only supports preserve_most on X86-64 and AArch64 for now.
447 // See https://clang.llvm.org/docs/AttributeReference.html#preserve-most for
448 // more details.
449 #if (defined(ARCH_CPU_ARM64) || defined(ARCH_CPU_X86_64)) && \
450 !(BUILDFLAG(IS_WIN) && defined(ARCH_CPU_ARM64)) && \
451 !defined(COMPONENT_BUILD) && defined(__clang__) && \
452 __clang_major__ >= 17 && HAS_ATTRIBUTE(preserve_most)
453 #define PRESERVE_MOST __attribute__((preserve_most))
454 #else
455 #define PRESERVE_MOST
456 #endif
457
458 // Mark parameters or return types as having a lifetime attached to the class.
459 //
460 // When used to mark a method's pointer/reference parameter, the compiler is
461 // made aware that it will be stored internally in the class and the pointee
462 // must outlive the class. Typically used on constructor arguments. It should
463 // appear to the right of the parameter's variable name.
464 //
465 // Example:
466 // ```
467 // struct S {
468 // S(int* p LIFETIME_BOUND) : ptr_(p) {}
469 //
470 // int* ptr_;
471 // };
472 // ```
473 //
474 // When used on a method with a return value, the compiler is made aware that
475 // the returned type is/has a pointer to the internals of the class, and must
476 // not outlive the class object. It should appear after any method qualifiers.
477 //
478 // Example:
479 // ```
480 // struct S {
481 // int* GetPtr() const LIFETIME_BOUND { return i_; };
482 //
483 // int i_;
484 // };
485 // ```
486 //
487 // This allows the compiler to warn in (a limited set of) cases where the
488 // pointer would otherwise be left dangling, especially in cases where the
489 // pointee would be a destroyed temporary.
490 //
491 // Docs: https://clang.llvm.org/docs/AttributeReference.html#lifetimebound
492 #if defined(__clang__)
493 #define LIFETIME_BOUND [[clang::lifetimebound]]
494 #else
495 #define LIFETIME_BOUND
496 #endif
497
498 // Mark a function as pure, meaning that it does not have side effects, meaning
499 // that it does not write anything external to the function's local variables
500 // and return value.
501 //
502 // WARNING: If this attribute is mis-used it will result in UB and
503 // miscompilation, as the optimizator may fold multiple calls into one and
504 // reorder them inappropriately. This shouldn't appear outside of key vocabulary
505 // types. It allows callers to work with the vocab type directly, and call its
506 // methods without having to worry about caching things into local variables in
507 // hot code.
508 //
509 // This attribute must not appear on functions that make use of function
510 // pointers, virtual methods, or methods of templates (including operators like
511 // comparison), as the "pure" function can not know what those functions do and
512 // can not guarantee there will never be sideeffects.
513 #if defined(COMPILER_GCC) || defined(__clang__)
514 #define PURE_FUNCTION [[gnu::pure]]
515 #else
516 #define PURE_FUNCTION
517 #endif
518
519 // Functions should be marked with UNSAFE_BUFFER_USAGE when they lead to
520 // out-of-bounds bugs when called with incorrect inputs.
521 //
522 // Ideally such functions should be paired with a safer version that works with
523 // safe primitives like `base::span`. Otherwise, another safer coding pattern
524 // should be documented along side the use of `UNSAFE_BUFFER_USAGE`.
525 //
526 // All functions marked with UNSAFE_BUFFER_USAGE should come with a safety
527 // comment that explains the requirements of the function to prevent an
528 // out-of-bounds bug. For example:
529 // ```
530 // // Function to do things between `input` and `end`.
531 // //
532 // // # Safety
533 // // The `input` must point to an array with size at least 5. The `end` must
534 // // point within the same allocation of `input` and not come before `input`.
535 // ```
536 //
537 // The requirements described in the safety comment must be sufficient to
538 // guarantee that the function never goes out of bounds. Annotating a function
539 // in this way means that all callers will be required to wrap the call in an
540 // `UNSAFE_BUFFERS()` macro (see below), with a comment justifying how it meets
541 // the requirements.
542 #if defined(__clang__) && HAS_ATTRIBUTE(unsafe_buffer_usage)
543 #define UNSAFE_BUFFER_USAGE [[clang::unsafe_buffer_usage]]
544 #else
545 #define UNSAFE_BUFFER_USAGE
546 #endif
547
548 // UNSAFE_BUFFERS() wraps code that violates the -Wunsafe-buffer-usage warning,
549 // such as:
550 // - pointer arithmetic,
551 // - pointer subscripting, and
552 // - calls to functions annotated with UNSAFE_BUFFER_USAGE.
553 //
554 // This indicates code whose bounds correctness cannot be ensured
555 // systematically, and thus requires manual review.
556 //
557 // ** USE OF THIS MACRO SHOULD BE VERY RARE.** This should only be used when
558 // strictly necessary. Prefer to use `base::span` instead of pointers, or other
559 // safer coding patterns (like std containers) that avoid the opportunity for
560 // out-of-bounds bugs to creep into the code. Any use of UNSAFE_BUFFERS() can
561 // lead to a critical security bug if any assumptions are wrong, or ever become
562 // wrong in the future.
563 //
564 // The macro should be used to wrap the minimum necessary code, to make it clear
565 // what is unsafe, and prevent accidentally opting extra things out of the
566 // warning.
567 //
568 // All usage of UNSAFE_BUFFERS() should come with a `// SAFETY: ...` comment
569 // that explains how we have guaranteed that the pointer usage can never go
570 // out-of-bounds, or that the requirements of the UNSAFE_BUFFER_USAGE function
571 // are met. The safety comment should allow a reader to check that all
572 // requirements have been met, using only local invariants. Examples of local
573 // invariants include:
574 // - Runtime conditions or CHECKs near the UNSAFE_BUFFERS macros
575 // - Invariants guaranteed by types in the surrounding code
576 // - Invariants guaranteed by function calls in the surrounding code
577 // - Caller requirements, if the containing function is itself marked with
578 // UNSAFE_BUFFER_USAGE
579 //
580 // The last case should be an option of last resort. It is less safe and will
581 // require the caller also use the UNSAFE_BUFFERS() macro. Prefer directly
582 // capturing such invariants in types like `base::span`.
583 //
584 // Safety explanations may not rely on invariants that are not fully
585 // encapsulated close to the UNSAFE_BUFFERS() usage. Instead, use safer coding
586 // patterns or stronger invariants.
587 #if defined(__clang__)
588 // clang-format off
589 // Formatting is off so that we can put each _Pragma on its own line, as
590 // recommended by the gcc docs.
591 #define UNSAFE_BUFFERS(...) \
592 _Pragma("clang unsafe_buffer_usage begin") \
593 __VA_ARGS__ \
594 _Pragma("clang unsafe_buffer_usage end")
595 // clang-format on
596 #else
597 #define UNSAFE_BUFFERS(...) __VA_ARGS__
598 #endif
599
600 // Defines a condition for a function to be checked at compile time if the
601 // parameter's value is known at compile time. If the condition is failed, the
602 // function is omitted from the overload set resolution, much like `requires`.
603 //
604 // If the parameter is a runtime value, then the condition is unable to be
605 // checked and the function will be omitted from the overload set resolution.
606 // This ensures the function can only be called with values known at compile
607 // time. This is a clang extension.
608 //
609 // Example:
610 // ```
611 // void f(int a) ENABLE_IF_ATTR(a > 0) {}
612 // f(1); // Ok.
613 // f(0); // Error: no valid f() found.
614 // ```
615 //
616 // The `ENABLE_IF_ATTR` annotation is preferred over `consteval` with a check
617 // that breaks compile because metaprogramming does not observe such checks. So
618 // with `consteval`, the function looks callable to concepts/type_traits but is
619 // not and will fail to compile even though it reports it's usable. Whereas
620 // `ENABLE_IF_ATTR` interacts correctly with metaprogramming. This is especially
621 // painful for constructors. See also
622 // https://github.com/chromium/subspace/issues/266.
623 #if defined(__clang__)
624 #define ENABLE_IF_ATTR(cond, msg) __attribute__((enable_if(cond, msg)))
625 #else
626 #define ENABLE_IF_ATTR(cond, msg)
627 #endif
628
629 #endif // BASE_COMPILER_SPECIFIC_H_
630