• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 // 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
21 #if defined(__has_attribute)
22 #define HAS_ATTRIBUTE(x) __has_attribute(x)
23 #else
24 #define HAS_ATTRIBUTE(x) 0
25 #endif
26 
27 // A wrapper around `__has_builtin`, similar to `HAS_ATTRIBUTE()`.
28 //
29 // See also:
30 //   https://clang.llvm.org/docs/LanguageExtensions.html#has-builtin
31 #if defined(__has_builtin)
32 #define HAS_BUILTIN(x) __has_builtin(x)
33 #else
34 #define HAS_BUILTIN(x) 0
35 #endif
36 
37 // 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 // ```
62 #if __has_cpp_attribute(gnu::noinline)
63 #define NOINLINE [[gnu::noinline]]
64 #elif __has_cpp_attribute(msvc::noinline)
65 #define NOINLINE [[msvc::noinline]]
66 #else
67 #define NOINLINE
68 #endif
69 
70 // Annotates a function indicating it should not be optimized.
71 //
72 // See also:
73 //   https://clang.llvm.org/docs/AttributeReference.html#optnone
74 //   https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html#index-optimize-function-attribute
75 //
76 // Usage:
77 // ```
78 //   NOOPT void Func() {
79 //     // This body will not be optimized.
80 //   }
81 // ```
82 #if __has_cpp_attribute(clang::optnone)
83 #define NOOPT [[clang::optnone]]
84 #elif __has_cpp_attribute(gnu::optimize)
85 #define NOOPT [[gnu::optimize(0)]]
86 #else
87 #define NOOPT
88 #endif
89 
90 // Annotates a function indicating it should always be inlined.
91 //
92 // See also:
93 //   https://clang.llvm.org/docs/AttributeReference.html#always-inline-force-inline
94 //
95 // Usage:
96 // ```
97 //   ALWAYS_INLINE void Func() {
98 //     // This body will be inlined into callers whenever possible.
99 //   }
100 // ```
101 //
102 // Since `ALWAYS_INLINE` is performance-oriented but can hamper debugging,
103 // ignore it in debug mode.
104 #if defined(NDEBUG)
105 #if __has_cpp_attribute(gnu::always_inline)
106 #define ALWAYS_INLINE [[gnu::always_inline]] inline
107 #elif defined(COMPILER_MSVC)
108 #define ALWAYS_INLINE __forceinline
109 #endif
110 #endif
111 #if !defined(ALWAYS_INLINE)
112 #define ALWAYS_INLINE inline
113 #endif
114 
115 // Annotates a function indicating it should never be tail called. Useful to
116 // make sure callers of the annotated function are never omitted from call
117 // stacks. Often useful with `NOINLINE` to make sure the function itself is also
118 // not omitted from call stacks. Note: this does not prevent code folding of
119 // multiple identical callers into a single signature; to do that, see
120 // `NO_CODE_FOLDING()` in base/debug/alias.h.
121 //
122 // For a caller-side version of this, see `DISABLE_TAIL_CALLS`.
123 //
124 // See also:
125 //   https://clang.llvm.org/docs/AttributeReference.html#not-tail-called
126 //
127 // Usage:
128 // ```
129 //   // Calls to this function will not be tail calls.
130 //   NOT_TAIL_CALLED void Func();
131 // ```
132 #if __has_cpp_attribute(clang::not_tail_called)
133 #define NOT_TAIL_CALLED [[clang::not_tail_called]]
134 #else
135 #define NOT_TAIL_CALLED
136 #endif
137 
138 // Annotates a return statement indicating the compiler must convert it to a
139 // tail call. Can be used only on return statements, even for functions
140 // returning void. Caller and callee must have the same number of arguments and
141 // the argument types must be "similar". While the compiler may automatically
142 // convert compatible calls to tail calls when optimizing, this annotation
143 // requires it to occur if doing so is valid, and will not compile otherwise.
144 //
145 // See also:
146 //   https://clang.llvm.org/docs/AttributeReference.html#musttail
147 //
148 // Usage:
149 // ```
150 //   int Func1(double);
151 //   int Func2(double d) {
152 //     MUSTTAIL return Func1(d + 1);  // `Func1()` will be tail-called.
153 //   }
154 // ```
155 #if __has_cpp_attribute(clang::musttail)
156 #define MUSTTAIL [[clang::musttail]]
157 #else
158 #define MUSTTAIL
159 #endif
160 
161 // Annotates a data member indicating it need not have an address distinct from
162 // all other non-static data members of the class, and its tail padding may be
163 // used for other objects' storage. This can have subtle and dangerous effects,
164 // including on containing objects; use with caution.
165 //
166 // See also:
167 //   https://en.cppreference.com/w/cpp/language/attributes/no_unique_address
168 //   https://wg21.link/dcl.attr.nouniqueaddr
169 // Usage:
170 // ```
171 //   // In the following struct, `t` might not have a unique address from `i`,
172 //   // and `t`'s tail padding (if any) may be reused by subsequent objects.
173 //   struct S {
174 //     int i;
175 //     NO_UNIQUE_ADDRESS T t;
176 //   };
177 // ```
178 //
179 // Unfortunately MSVC ignores [[no_unique_address]] (see
180 // https://devblogs.microsoft.com/cppblog/msvc-cpp20-and-the-std-cpp20-switch/#msvc-extensions-and-abi),
181 // and clang-cl matches it for ABI compatibility reasons. We need to prefer
182 // [[msvc::no_unique_address]] when available if we actually want any effect.
183 #if __has_cpp_attribute(msvc::no_unique_address)
184 #define NO_UNIQUE_ADDRESS [[msvc::no_unique_address]]
185 #elif __has_cpp_attribute(no_unique_address)
186 #define NO_UNIQUE_ADDRESS [[no_unique_address]]
187 #else
188 #define NO_UNIQUE_ADDRESS
189 #endif
190 
191 // Annotates a function indicating it takes a `printf()`-style format string.
192 // The compiler will check that the provided arguments match the type specifiers
193 // in the format string. Useful to detect mismatched format strings/args.
194 //
195 // `format_param` is the one-based index of the format string parameter;
196 // `dots_param` is the one-based index of the "..." parameter.
197 // For `v*printf()` functions (which take a `va_list`), `dots_param` should be
198 // 0. For member functions, the implicit `this` parameter is at index 1.
199 //
200 // See also:
201 //   https://clang.llvm.org/docs/AttributeReference.html#format
202 //   https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html#index-format-function-attribute
203 //
204 // Usage:
205 // ```
206 //   PRINTF_FORMAT(1, 2)
207 //   void Print(const char* format, ...);
208 //   void Func() {
209 //     // The following call will not compile; diagnosed as format and argument
210 //     // types mismatching.
211 //     Print("%s", 1);
212 //   }
213 // ```
214 #if __has_cpp_attribute(gnu::format)
215 #define PRINTF_FORMAT(format_param, dots_param) \
216   [[gnu::format(printf, format_param, dots_param)]]
217 #else
218 #define PRINTF_FORMAT(format_param, dots_param)
219 #endif
220 
221 // Annotates a function disabling the named sanitizer within its body.
222 //
223 // See also:
224 //   https://clang.llvm.org/docs/AttributeReference.html#no-sanitize
225 //   https://clang.llvm.org/docs/UsersManual.html#controlling-code-generation
226 //
227 // Usage:
228 // ```
229 //   NO_SANITIZE("cfi-icall") void Func() {
230 //     // CFI indirect call checks will not be performed in this body.
231 //   }
232 // ```
233 #if __has_cpp_attribute(clang::no_sanitize)
234 #define NO_SANITIZE(sanitizer) [[clang::no_sanitize(sanitizer)]]
235 #else
236 #define NO_SANITIZE(sanitizer)
237 #endif
238 
239 // Annotates a pointer and size directing MSAN to treat that memory region as
240 // fully initialized. Useful for e.g. code that deliberately reads uninitialized
241 // data, such as a GC scavenging root set pointers from the stack.
242 //
243 // See also:
244 //   https://github.com/google/sanitizers/wiki/MemorySanitizer
245 //
246 // Usage:
247 // ```
248 //   T* ptr = ...;
249 //   // After the next statement, MSAN will assume `ptr` points to an
250 //   // initialized `T`.
251 //   MSAN_UNPOISON(ptr, sizeof(T));
252 // ```
253 #if defined(MEMORY_SANITIZER) && !BUILDFLAG(IS_NACL)
254 #include <sanitizer/msan_interface.h>
255 #define MSAN_UNPOISON(p, size) __msan_unpoison(p, size)
256 #else
257 #define MSAN_UNPOISON(p, size)
258 #endif
259 
260 // Annotates a pointer and size directing MSAN to check whether that memory
261 // region is initialized, as if it was being read from. If any bits are
262 // uninitialized, crashes with an MSAN report. Useful for e.g. sanitizing data
263 // MSAN won't be able to track, such as data that is about to be passed to
264 // another process via shared memory.
265 //
266 // See also:
267 //   https://www.chromium.org/developers/testing/memorysanitizer/#debugging-msan-reports
268 //
269 // Usage:
270 // ```
271 //   T* ptr = ...;
272 //   // The following line will crash at runtime in MSAN builds if `ptr` does
273 //   // not point to an initialized `T`.
274 //   MSAN_CHECK_MEM_IS_INITIALIZED(ptr, sizeof(T));
275 // ```
276 #if defined(MEMORY_SANITIZER) && !BUILDFLAG(IS_NACL)
277 #define MSAN_CHECK_MEM_IS_INITIALIZED(p, size) \
278   __msan_check_mem_is_initialized(p, size)
279 #else
280 #define MSAN_CHECK_MEM_IS_INITIALIZED(p, size)
281 #endif
282 
283 // Annotates a function disabling Control Flow Integrity checks due to perf
284 // impact.
285 //
286 // See also:
287 //   https://clang.llvm.org/docs/ControlFlowIntegrity.html#performance
288 //   https://www.chromium.org/developers/testing/control-flow-integrity/#overhead-only-tested-on-x64
289 //
290 // Usage:
291 // ```
292 //   DISABLE_CFI_PERF void Func() {
293 //     // CFI checks will not be performed in this body, due to perf reasons.
294 //   }
295 // ```
296 #if !defined(DISABLE_CFI_PERF)
297 #if defined(__clang__) && defined(OFFICIAL_BUILD)
298 #define DISABLE_CFI_PERF NO_SANITIZE("cfi")
299 #else
300 #define DISABLE_CFI_PERF
301 #endif
302 #endif
303 
304 // Annotates a function disabling Control Flow Integrity indirect call checks.
305 // NOTE: Prefer `DISABLE_CFI_DLSYM()` if you just need to allow calling of dlsym
306 // functions.
307 //
308 // See also:
309 //   https://clang.llvm.org/docs/ControlFlowIntegrity.html#available-schemes
310 //   https://www.chromium.org/developers/testing/control-flow-integrity/#indirect-call-failures
311 //
312 // Usage:
313 // ```
314 //   DISABLE_CFI_ICALL void Func() {
315 //     // CFI indirect call checks will not be performed in this body.
316 //   }
317 // ```
318 #if !defined(DISABLE_CFI_ICALL)
319 #if BUILDFLAG(IS_WIN)
320 #define DISABLE_CFI_ICALL NO_SANITIZE("cfi-icall") __declspec(guard(nocf))
321 #else
322 #define DISABLE_CFI_ICALL NO_SANITIZE("cfi-icall")
323 #endif
324 #endif
325 
326 // Annotates a function disabling Control Flow Integrity indirect call checks if
327 // doing so is necessary to call dlsym functions. The checks are retained on
328 // platforms where loaded modules participate in CFI (viz. Windows).
329 //
330 // See also:
331 //   https://www.chromium.org/developers/testing/control-flow-integrity/#indirect-call-failures
332 //
333 // Usage:
334 // ```
335 //   DISABLE_CFI_DLSYM void Func() {
336 //     // On non-Windows platforms, CFI indirect call checks will not be
337 //     // performed in this body.
338 //   }
339 // ```
340 #if !defined(DISABLE_CFI_DLSYM)
341 #if BUILDFLAG(IS_WIN)
342 #define DISABLE_CFI_DLSYM
343 #else
344 #define DISABLE_CFI_DLSYM DISABLE_CFI_ICALL
345 #endif
346 #endif
347 
348 // Evaluates to a string constant containing the function signature.
349 //
350 // See also:
351 //   https://clang.llvm.org/docs/LanguageExtensions.html#source-location-builtins
352 //   https://en.cppreference.com/w/c/language/function_definition#func
353 //
354 // Usage:
355 // ```
356 //   void Func(int arg) {
357 //     std::cout << PRETTY_FUNCTION;  // Prints `void Func(int)` or similar.
358 //   }
359 // ```
360 #if defined(COMPILER_GCC)
361 #define PRETTY_FUNCTION __PRETTY_FUNCTION__
362 #elif defined(COMPILER_MSVC)
363 #define PRETTY_FUNCTION __FUNCSIG__
364 #else
365 #define PRETTY_FUNCTION __func__
366 #endif
367 
368 // Annotates a variable indicating that its storage should not be filled with a
369 // fixed pattern when uninitialized.
370 //
371 // The `init_stack_vars` gn arg (enabled on most build configs) causes the
372 // compiler to generate code that writes a fixed pattern into uninitialized
373 // parts of all local variables, to mitigate security risks. In most cases, e.g.
374 // when such memory is either never accessed or will be initialized later before
375 // reading, the compiler is able to remove the additional stores, and any
376 // remaining stores are unlikely to affect program performance.
377 //
378 // If hot code suffers unavoidable perf penalties, this can disable the
379 // pattern-filling there. This should only be done when necessary, since reads
380 // from uninitialized variables are not only UB, they can in practice allow
381 // attackers to control logic by pre-filling the variable's memory with a
382 // desirable value.
383 //
384 // NOTE: This behavior also increases the likelihood the compiler will generate
385 // `memcpy()`/`memset()` calls to init variables. If this causes link errors for
386 // targets that don't link against the CRT, this macro can help; you may instead
387 // want 'configs -= [ "//build/config/compiler:default_init_stack_vars" ]' in
388 // the relevant .gn file to disable this on the whole target.
389 //
390 // See also:
391 //   https://source.chromium.org/chromium/chromium/src/+/main:build/config/compiler/BUILD.gn;l=3088;drc=24ccaf63ff5b1883be1ebe5f979d917ce28b0131
392 //   https://clang.llvm.org/docs/ClangCommandLineReference.html#cmdoption-clang-ftrivial-auto-var-init
393 //   https://clang.llvm.org/docs/AttributeReference.html#uninitialized
394 //
395 // Usage:
396 // ```
397 //   // The following line declares `i` without ensuring it initially contains
398 //   // any particular pattern.
399 //   STACK_UNINITIALIZED int i;
400 // ```
401 #if __has_cpp_attribute(clang::uninitialized)
402 #define STACK_UNINITIALIZED [[clang::uninitialized]]
403 #elif __has_cpp_attribute(gnu::uninitialized)
404 #define STACK_UNINITIALIZED [[gnu::uninitialized]]
405 #else
406 #define STACK_UNINITIALIZED
407 #endif
408 
409 // Annotates a function disabling stack canary checks.
410 //
411 // The `-fstack-protector` compiler flag (passed on most non-Windows builds)
412 // causes the compiler to extend some function prologues and epilogues to set
413 // and check a canary value, to detect stack buffer overflows and crash in
414 // response. If hot code suffers unavoidable perf penalties, or intentionally
415 // modifies the canary value, this can disable the behavior there.
416 //
417 // See also:
418 //   https://clang.llvm.org/docs/ClangCommandLineReference.html#cmdoption-clang-fstack-protector
419 //   https://clang.llvm.org/docs/AttributeReference.html#no-stack-protector-safebuffers
420 //
421 // Usage:
422 // ```
423 //   NO_STACK_PROTECTOR void Func() {
424 //     // Stack canary checks will not be performed in this body.
425 //   }
426 // ```
427 #if __has_cpp_attribute(gnu::no_stack_protector)
428 #define NO_STACK_PROTECTOR [[gnu::no_stack_protector]]
429 #elif __has_cpp_attribute(gnu::optimize)
430 #define NO_STACK_PROTECTOR [[gnu::optimize("-fno-stack-protector")]]
431 #else
432 #define NO_STACK_PROTECTOR
433 #endif
434 
435 // Annotates a codepath suppressing static analysis along that path. Useful when
436 // code is safe in practice for reasons the analyzer can't detect, e.g. because
437 // the condition leading to that path guarantees a param is non-null.
438 //
439 // Usage:
440 // ```
441 //   if (cond) {
442 //     ANALYZER_SKIP_THIS_PATH();
443 //     // Static analysis will be disabled for the remainder of this block.
444 //     delete ptr;
445 //   }
446 // ```
447 #if defined(__clang_analyzer__)
AnalyzerNoReturn()448 inline constexpr bool AnalyzerNoReturn()
449 #if HAS_ATTRIBUTE(analyzer_noreturn)
450     __attribute__((analyzer_noreturn))
451 #endif
452 {
453   return false;
454 }
455 #define ANALYZER_SKIP_THIS_PATH() static_cast<void>(::AnalyzerNoReturn())
456 #else
457 // The above definition would be safe even outside the analyzer, but defining
458 // the macro away entirely avoids the need for the optimizer to eliminate it.
459 #define ANALYZER_SKIP_THIS_PATH()
460 #endif
461 
462 // Annotates a condition directing static analysis to assume it is always true.
463 // Evaluates to the provided `arg` as a `bool`.
464 //
465 // Usage:
466 // ```
467 //   // Static analysis will assume the following condition always holds.
468 //   if (ANALYZER_ASSUME_TRUE(cond)) ...
469 // ```
470 #if defined(__clang_analyzer__)
AnalyzerAssumeTrue(bool arg)471 inline constexpr bool AnalyzerAssumeTrue(bool arg) {
472   return arg || AnalyzerNoReturn();
473 }
474 #define ANALYZER_ASSUME_TRUE(arg) ::AnalyzerAssumeTrue(!!(arg))
475 #else
476 // Again, the above definition is safe, this is just simpler for the optimizer.
477 #define ANALYZER_ASSUME_TRUE(arg) (arg)
478 #endif
479 
480 // Annotates a function, function pointer, or statement to disallow
481 // optimizations that merge calls. Useful to ensure the source locations of such
482 // calls are not obscured.
483 //
484 // See also:
485 //   https://clang.llvm.org/docs/AttributeReference.html#nomerge
486 //
487 // Usage:
488 // ```
489 //   NOMERGE void Func();  // No direct calls to `Func()` will be merged.
490 //
491 //   using Ptr = decltype(&Func);
492 //   NOMERGE Ptr ptr = &Func;  // No calls through `ptr` will be merged.
493 //
494 //   NOMERGE if (cond) {
495 //     // No calls in this block will be merged.
496 //   }
497 // ```
498 #if __has_cpp_attribute(clang::nomerge)
499 #define NOMERGE [[clang::nomerge]]
500 #else
501 #define NOMERGE
502 #endif
503 
504 // Annotates a type as being suitable for passing in registers despite having a
505 // non-trivial copy or move constructor or destructor. This requires the type
506 // not be concerned about its address remaining constant, be safely usable after
507 // copying its memory, and have a destructor that may be safely omitted on
508 // moved-from instances; an example is `std::unique_ptr`. Unnecessary if the
509 // copy/move constructor(s) and destructor are unconditionally trivial; likely
510 // ineffective if the type is too large to be passed in one or two registers
511 // with the target ABI. However, annotating a type this way will also cause
512 // `IS_TRIVIALLY_RELOCATABLE()` to return true for that type, and so may be
513 // desirable even for large types, if they are placed in containers that
514 // optimize based on that check.
515 //
516 // NOTE: Use with caution; this has subtle effects on constructor/destructor
517 // ordering. When used with types passed or returned by value, values may be
518 // constructed in the source stack frame, passed in a register, and then used
519 // and destroyed in the target stack frame.
520 //
521 // See also:
522 //   https://clang.llvm.org/docs/AttributeReference.html#trivial-abi
523 //   https://libcxx.llvm.org/docs/DesignDocs/UniquePtrTrivialAbi.html
524 //
525 // Usage:
526 // ```
527 //   // Instances of type `S` will be eligible to be passed in registers despite
528 //   // `S`'s nontrivial destructor.
529 //   struct TRIVIAL_ABI S { ~S(); }
530 // ```
531 #if __has_cpp_attribute(clang::trivial_abi)
532 #define TRIVIAL_ABI [[clang::trivial_abi]]
533 #else
534 #define TRIVIAL_ABI
535 #endif
536 
537 // Determines whether a type is trivially relocatable, i.e. a move-and-destroy
538 // sequence can safely be replaced with `memcpy()`. This is true of types with
539 // trivial copy or move construction plus trivial destruction, as well as types
540 // marked `TRIVIAL_ABI`. Useful to optimize container implementations.
541 //
542 // See also:
543 //   https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2023/p1144r8.html
544 //   https://clang.llvm.org/docs/LanguageExtensions.html#:~:text=__is_trivially_relocatable
545 //
546 // Usage:
547 // ```
548 //   if constexpr (IS_TRIVIALLY_RELOCATABLE(T)) {
549 //     // This block will only be executed if type `T` is trivially relocatable.
550 //   }
551 // ```
552 #if HAS_BUILTIN(__is_trivially_relocatable)
553 #define IS_TRIVIALLY_RELOCATABLE(t) __is_trivially_relocatable(t)
554 #else
555 #define IS_TRIVIALLY_RELOCATABLE(t) false
556 #endif
557 
558 // Annotates a member function as safe to call on a moved-from object, which it
559 // will reinitialize.
560 //
561 // See also:
562 //   https://clang.llvm.org/extra/clang-tidy/checks/bugprone/use-after-move.html#reinitialization
563 //
564 // Usage:
565 // ```
566 //   struct S {
567 //     REINITIALIZES_AFTER_MOVE void Reset();
568 //   };
569 //   void Func1(const S&);
570 //   void Func2() {
571 //     S s1;
572 //     S s2 = std::move(s1);
573 //     s1.Reset();
574 //     // clang-tidy's `bugprone-use-after-move` check will not flag the
575 //     // following call as a use-after-move, due to the intervening `Reset()`.
576 //     Func1(s1);
577 //   }
578 // ```
579 #if __has_cpp_attribute(clang::reinitializes)
580 #define REINITIALIZES_AFTER_MOVE [[clang::reinitializes]]
581 #else
582 #define REINITIALIZES_AFTER_MOVE
583 #endif
584 
585 // Annotates a type as owning an object or memory region whose address may be
586 // vended to or stored by other objects. For example, `std::unique_ptr<T>` owns
587 // a `T` and vends its address via `.get()`, and `std::string` owns a block of
588 // `char` and vends its address via `.data()`. Used to detect lifetime errors in
589 // conjunction with `GSL_POINTER`; see documentation there.
590 //
591 // See also:
592 //   https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#SS-ownership
593 //   https://clang.llvm.org/docs/AttributeReference.html#owner
594 //   https://clang.llvm.org/docs/DiagnosticsReference.html#wdangling-gsl
595 //
596 // Usage:
597 // ```
598 //   // Marking `S` as `GSL_OWNER` enables `-Wdangling-gsl` to detect misuse by
599 //   // types annotated as `GSL_POINTER`.
600 //   struct GSL_OWNER S;
601 // ```
602 #if __has_cpp_attribute(gsl::Owner)
603 #define GSL_OWNER [[gsl::Owner]]
604 #else
605 #define GSL_OWNER
606 #endif
607 
608 // Annotates a type as holding a pointer into an owner object (an appropriate
609 // STL or `GSL_OWNER`-annotated type). If an instance of the pointer type is
610 // constructed from an instance of the owner type, and the owner instance is
611 // destroyed, the pointer instance is considered to be dangling. Useful to
612 // diagnose some cases of lifetime errors.
613 //
614 // See also:
615 //   https://clang.llvm.org/docs/AttributeReference.html#pointer
616 //
617 // Usage:
618 // ```
619 //  struct GSL_OWNER T {};
620 //  struct GSL_POINTER S {
621 //    S(const T&);
622 //  };
623 //  S Func() {
624 //    // The following return will not compile; diagnosed as returning address
625 //    // of local temporary.
626 //    return S(T());
627 //  }
628 // ```
629 #if __has_cpp_attribute(gsl::Pointer)
630 #define GSL_POINTER [[gsl::Pointer]]
631 #else
632 #define GSL_POINTER
633 #endif
634 
635 // Annotates a type or variable to add a "logically_const" ABI tag to any
636 // corresponding mangled symbol name(s). Useful to suppress warnings from the
637 // "Mutable Constants" trybot check [1] when logically const instances are named
638 // like `kConstants` but for some reason should not be marked `const`.
639 //
640 // [1]:
641 // https://chromium.googlesource.com/chromium/src/+/main/docs/speed/binary_size/android_binary_size_trybot.md#Mutable-Constants
642 //
643 // Usage:
644 // ```
645 //   struct S {};
646 //   S kConstS;                      // Fails on some trybots.
647 //   LOGICALLY_CONST S kAlsoConstS;  // OK
648 //
649 //   struct LOGICALLY_CONST T {};
650 //   T kConstT;                      // OK
651 // ```
652 #if __has_cpp_attribute(gnu::abi_tag)
653 #define LOGICALLY_CONST [[gnu::abi_tag("logically_const")]]
654 #else
655 #define LOGICALLY_CONST
656 #endif
657 
658 // Annotates a function indicating it is cold, but called from hot functions.
659 // Useful when a performance-sensitive function is usually simple, but in edge
660 // cases must fall back to a more complex handler.
661 //
662 // On X86-64 and AArch64, this changes the calling convention so most registers
663 // are callee-saved, reducing register spills in the caller. This can improve
664 // caller performance in the common case, at the cost of pessimizing the callee.
665 // On other platforms, this attribute has no effect as of Clang 20.
666 //
667 // See also:
668 //   https://clang.llvm.org/docs/AttributeReference.html#preserve-most
669 //
670 // Usage:
671 // ```
672 //   // Calls to this function will not require most registers to be saved.
673 //   PRESERVE_MOST void Func();
674 // ```
675 //
676 // Disable `PRESERVE_MOST` in component builds, since `_dl_runtime_resolve()`
677 // clobbers registers on platforms where it's used, and the component build is
678 // not perf-critical anyway; see
679 // https://github.com/llvm/llvm-project/issues/105588.
680 //
681 // Also disable for Win ARM64 due to as-yet-uninvestigated crashes.
682 // TODO(crbug.com/42204008): Investigate, fix, and re-enable.
683 #if __has_cpp_attribute(clang::preserve_most) &&             \
684     (defined(ARCH_CPU_ARM64) || defined(ARCH_CPU_X86_64)) && \
685     !defined(COMPONENT_BUILD) &&                             \
686     !(BUILDFLAG(IS_WIN) && defined(ARCH_CPU_ARM64))
687 #define PRESERVE_MOST [[clang::preserve_most]]
688 #else
689 #define PRESERVE_MOST
690 #endif
691 
692 // Annotates a pointer or reference parameter or return value for a member
693 // function as having lifetime intertwined with the instance on which the
694 // function is called. For parameters, the function is assumed to store the
695 // value into the called-on object, so if the referred-to object is later
696 // destroyed, the called-on object is also considered to be dangling. For return
697 // values, the value is assumed to point into the called-on object, so if that
698 // object is destroyed, the returned value is also considered to be dangling.
699 // Useful to diagnose some cases of lifetime errors.
700 //
701 // See also:
702 //   https://clang.llvm.org/docs/AttributeReference.html#lifetimebound
703 //
704 // Usage:
705 // ```
706 //   struct S {
707 //      S(int* p LIFETIME_BOUND);
708 //      int* Get() LIFETIME_BOUND;
709 //   };
710 //   S Func1() {
711 //     int i = 0;
712 //     // The following return will not compile; diagnosed as returning address
713 //     // of a stack object.
714 //     return S(&i);
715 //   }
716 //   int* Func2(int* p) {
717 //     // The following return will not compile; diagnosed as returning address
718 //     // of a local temporary.
719 //     return S(p).Get();
720 //   }
721 // ```
722 #if __has_cpp_attribute(clang::lifetimebound)
723 #define LIFETIME_BOUND [[clang::lifetimebound]]
724 #else
725 #define LIFETIME_BOUND
726 #endif
727 
728 // Annotates a function or variable to indicate that it should have weak
729 // linkage. Useful for library code that wants code linking against it to be
730 // able to override its functionality; inside a single target, this is better
731 // accomplished via virtual methods and other more standard mechanisms.
732 //
733 // Any weak definition of a symbol will be overridden at link time by a non-weak
734 // definition. Marking a `const` or `constexpr` variable weak makes it no longer
735 // be considered a compile-time constant, since its value may be different after
736 // linking.
737 //
738 // Multiple weak definitions of a symbol may exist, in which case the linker is
739 // free to select any when there are no non-weak definitions. Like with symbols
740 // marked `inline`, this can lead to subtle, difficult-to-diagnose bugs if not
741 // all definitions are identical.
742 //
743 // A weak declaration that has no definitions at link time will be linked as if
744 // the corresponding address is null. Therefore library code can use weak
745 // declarations and conditionals to allow consumers to provide optional
746 // customizations.
747 //
748 // See also:
749 //   https://clang.llvm.org/docs/AttributeReference.html#weak
750 //
751 // Usage:
752 // ```
753 //   // The following definition defaults `x` to 10, but allows other object
754 //   // files to override its value. Thus, despite `constexpr`, `x` is not
755 //   // considered a compile-time constant (and cannot be used in a `constexpr`
756 //   // context).
757 //   extern const int x;
758 //   WEAK_SYMBOL constexpr int x = 10;
759 //
760 //   // The following declaration allows linking to occur whether a definition
761 //   // of `Func()` is provided or not; if none is present, `&Func` will
762 //   // evaluate to `nullptr` at runtime.
763 //   WEAK_SYMBOL void Func();
764 //
765 //   // The following definition provides a default implementation of `Func2()`,
766 //   // but allows other object files to override.
767 //   WEAK_SYMBOL void Func2() { ... }
768 // ```
769 #if __has_cpp_attribute(gnu::weak)
770 #define WEAK_SYMBOL [[gnu::weak]]
771 #else
772 #define WEAK_SYMBOL
773 #endif
774 
775 // Annotates a function indicating that the compiler should not convert calls
776 // within it to tail calls.
777 //
778 // For a callee-side version of this, see `NOT_TAIL_CALLED`.
779 //
780 // See also:
781 //   https://clang.llvm.org/docs/AttributeReference.html#disable-tail-calls
782 // Usage:
783 // ```
784 //   DISABLE_TAIL_CALLS void Func() {
785 //     // Function calls in this body will not be tail calls.
786 //   }
787 // ```
788 #if __has_cpp_attribute(clang::disable_tail_calls)
789 #define DISABLE_TAIL_CALLS [[clang::disable_tail_calls]]
790 #else
791 #define DISABLE_TAIL_CALLS
792 #endif
793 
794 // Annotates a type or member indicating the minimum possible alignment (one bit
795 // for bitfields, one byte otherwise) should be used. This can be used to
796 // eliminate padding inside objects, at the cost of potentially pessimizing
797 // code, or even generating invalid code (depending on platform restrictions) if
798 // underaligned objects have their addresses taken and passed elsewhere.
799 //
800 // This is similar to the more-broadly-supported `#pragma pack(1)`.
801 //
802 // See also:
803 //   https://gcc.gnu.org/onlinedocs/gcc/Common-Variable-Attributes.html#index-packed-variable-attribute
804 //
805 // Usage:
806 // ```
807 //   struct PACKED_OBJ S1 {
808 //     int8_t a;   // Alignment 1, offset 0, size 1
809 //     int32_t b;  // Alignment 1, offset 1 (0 bytes padding), size 4
810 //   };  // Overall alignment 1, 0 bytes trailing padding, overall size 5
811 //
812 //   struct S2 {
813 //     int8_t a;              // Alignment 1, offset 0, size 1
814 //     int32_t b;             // Alignment 4, offset 4 (3 bytes padding), size 4
815 //     int8_t c;              // Alignment 1, offset 8 (0 bytes padding), size 1
816 //     PACKED_OBJ int32_t d;  // Alignment 1, offset 9 (0 bytes padding), size 4
817 //   };  // Overall alignment 4, 3 bytes trailing padding, overall size 16
818 // ```
819 #if __has_cpp_attribute(gnu::packed)
820 #define PACKED_OBJ [[gnu::packed]]
821 #else
822 #define PACKED_OBJ
823 #endif
824 
825 // Annotates a function indicating that the returned pointer will never be null.
826 // This may allow the compiler to assume null checks on the caller side are
827 // unnecessary.
828 //
829 // In practice, this is usually better-handled by returning a value or
830 // reference, which enforce such guarantees at the type level.
831 //
832 // See also:
833 //   https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html#index-returns_005fnonnull-function-attribute
834 //   https://clang.llvm.org/docs/AttributeReference.html#nullability-attributes
835 //
836 // Usage:
837 // ```
838 //   // The following function will never return `nullptr`.
839 //   RETURNS_NONNULL int* Func();
840 // ```
841 #if __has_cpp_attribute(gnu::returns_nonnull)
842 #define RETURNS_NONNULL [[gnu::returns_nonnull]]
843 #else
844 #define RETURNS_NONNULL
845 #endif
846 
847 // Annotates a function indicating it is const, meaning that it has no
848 // observable side effects and its return value depends only on its arguments.
849 // Const functions may not read external memory other than unchanging objects
850 // (e.g. non-volatile constants), and the compiler is free to replace calls to
851 // them with the return values of earlier calls with the same arguments no
852 // matter what other state might have changed in the meantime.
853 //
854 // This is a much stronger restriction than `const`-qualified functions, and is
855 // rarely appropriate outside small local helpers, which are frequently
856 // inlineable anyway and would not really benefit.
857 //
858 // WARNING: Misusing this attribute can lead to silent miscompilation, UB, and
859 // difficult-to-diagnose bugs. For this and the above reason, usage should be
860 // very rare.
861 //
862 // See also:
863 //   https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html#index-const-function-attribute
864 //
865 // Usage:
866 // ```
867 //   // The compiler may replace calls to this function with values returned
868 //   // from earlier calls, assuming the args match.
869 //   CONST_FUNCTION int Func(int);
870 // ```
871 #if __has_cpp_attribute(gnu::const)
872 #define CONST_FUNCTION [[gnu::const]]
873 #else
874 #define CONST_FUNCTION
875 #endif
876 
877 // Annotates a function indicating it is pure, meaning that it has no observable
878 // side effects. Unlike functions annotated `CONST_FUNCTION`, pure functions may
879 // still read external memory, and thus their return values may change between
880 // calls. `strlen()` and `memcmp()` are examples of pure functions. Useful to
881 // allow folding/reordering calls for optimization purposes.
882 //
883 // WARNING: Misusing this attribute can lead to silent miscompilation, UB, and
884 // difficult-to-diagnose bugs. Because apparently-safe invocations can sometimes
885 // have side effects (especially when invoking "overridable" functionality like
886 // virtual or templated methods), such misuse is far more likely than it seems.
887 // Therefore, this macro should generally be used only in key vocabulary types,
888 // where the perf and ergonomic benefits of callers not needing to worry about
889 // caching results in local variables in hot code outweighs the risks.
890 //
891 // See also:
892 //   https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html#index-pure-function-attribute
893 //
894 // Usage:
895 // ```
896 //   // Calls to this function may be subject to more aggressive common
897 //   // subexpression (CSE) optimization.
898 //   PURE_FUNCTION int Func(int);
899 // ```
900 #if __has_cpp_attribute(gnu::pure)
901 #define PURE_FUNCTION [[gnu::pure]]
902 #else
903 #define PURE_FUNCTION
904 #endif
905 
906 // Annotates a function or class data member indicating it can lead to
907 // out-of-bounds accesses (OOB) if given incorrect inputs.
908 //
909 // For functions, this commonly includes functions which take pointers, sizes,
910 // iterators, sentinels, etc. and cannot fully check their preconditions (e.g.
911 // that the provided pointer actually points to an allocation of at least the
912 // provided size). Useful to diagnose potential misuse via
913 // `-Wunsafe-buffer-usage`, as well as to mark functions potentially in need of
914 // safer alternatives.
915 //
916 // For fields, this would be used to annotate both pointer and size fields that
917 // have not yet been converted to a span.
918 //
919 // All functions or fields annotated with this macro should come with a `#
920 // Safety` comment that explains what the caller must guarantee to prevent OOB.
921 // Ideally, unsafe functions should also be paired with a safer version, e.g.
922 // one that replaces pointer parameters with `span`s; otherwise, document safer
923 // replacement coding patterns callers can migrate to.
924 //
925 // Annotating a function `UNSAFE_BUFFER_USAGE` means all call sites (that do not
926 // disable the warning) must wrap calls in `UNSAFE_BUFFERS()`; see documentation
927 // there. Annotating a field `UNSAFE_BUFFER_USAGE` means that `UNSAFE_BUFFERS()`
928 // must wrap expressions that mutate of the field.
929 //
930 // See also:
931 //   https://chromium.googlesource.com/chromium/src/+/main/docs/unsafe_buffers.md
932 //   https://clang.llvm.org/docs/SafeBuffers.html
933 //   https://clang.llvm.org/docs/DiagnosticsReference.html#wunsafe-buffer-usage
934 //
935 // Usage:
936 // ```
937 //   // Calls to this function must be wrapped in `UNSAFE_BUFFERS()`.
938 //   UNSAFE_BUFFER_USAGE void Func(T* input, T* end);
939 //
940 //   struct S {
941 //     // Changing this pointer requires `UNSAFE_BUFFERS()`.
942 //     UNSAFE_BUFFER_USAGE int* p;
943 //   };
944 // ```
945 #if __has_cpp_attribute(clang::unsafe_buffer_usage)
946 #define UNSAFE_BUFFER_USAGE [[clang::unsafe_buffer_usage]]
947 #else
948 #define UNSAFE_BUFFER_USAGE
949 #endif
950 
951 // Annotates code indicating that it should be permanently exempted from
952 // `-Wunsafe-buffer-usage`. For temporary cases such as migrating callers to
953 // safer patterns, use `UNSAFE_TODO()` instead; see documentation there.
954 //
955 // All calls to functions annotated with `UNSAFE_BUFFER_USAGE` must be marked
956 // with one of these two macros; they can also be used around pointer
957 // arithmetic, pointer subscripting, and the like.
958 //
959 // ** USE OF THIS MACRO SHOULD BE VERY RARE.** Using this macro indicates that
960 // the compiler cannot verify that the code avoids OOB, and manual review is
961 // required. Even with manual review, it's easy for assumptions to change and
962 // security bugs to creep in over time. Prefer safer patterns instead.
963 //
964 // Usage should wrap the minimum necessary code, and *must* include a
965 // `// SAFETY: ...` comment that explains how the code guarantees safety or
966 // meets the requirements of called `UNSAFE_BUFFER_USAGE` functions. Guarantees
967 // must be manually verifiable by the Chrome security team using only local
968 // invariants; contact security@chromium.org to schedule such a review. Valid
969 // invariants include:
970 // - Runtime conditions or `CHECK()`s nearby
971 // - Invariants guaranteed by types in the surrounding code
972 // - Invariants guaranteed by function calls in the surrounding code
973 // - Caller requirements, if the containing function is itself annotated with
974 //   `UNSAFE_BUFFER_USAGE`; this is less safe and should be a last resort
975 //
976 // See also:
977 //   https://chromium.googlesource.com/chromium/src/+/main/docs/unsafe_buffers.md
978 //   https://clang.llvm.org/docs/SafeBuffers.html
979 //   https://clang.llvm.org/docs/DiagnosticsReference.html#wunsafe-buffer-usage
980 //
981 // Usage:
982 // ```
983 //   // The following call will not trigger a compiler warning even if `Func()`
984 //   // is annotated `UNSAFE_BUFFER_USAGE`.
985 //   return UNSAFE_BUFFERS(Func(input, end));
986 // ```
987 //
988 // Test for `__clang__` directly, as there's no `__has_pragma` or similar (see
989 // https://github.com/llvm/llvm-project/issues/51887).
990 #if defined(__clang__)
991 // Disabling `clang-format` allows each `_Pragma` to be on its own line, as
992 // recommended by https://gcc.gnu.org/onlinedocs/cpp/Pragmas.html.
993 // clang-format off
994 #define UNSAFE_BUFFERS(...)                  \
995   _Pragma("clang unsafe_buffer_usage begin") \
996   __VA_ARGS__                                \
997   _Pragma("clang unsafe_buffer_usage end")
998 // clang-format on
999 #else
1000 #define UNSAFE_BUFFERS(...) __VA_ARGS__
1001 #endif
1002 
1003 // Annotates code indicating that it should be temporarily exempted from
1004 // `-Wunsafe-buffer-usage`. While this is functionally the same as
1005 // `UNSAFE_BUFFERS()`, semantically it indicates that this is for migration
1006 // purposes, and should be cleaned up as soon as possible.
1007 //
1008 // Usage:
1009 // ```
1010 //   // The following call will not trigger a compiler warning even if `Func()`
1011 //   // is annotated `UNSAFE_BUFFER_USAGE`.
1012 //   return UNSAFE_TODO(Func(input, end));
1013 // ```
1014 #define UNSAFE_TODO(...) UNSAFE_BUFFERS(__VA_ARGS__)
1015 
1016 // Annotates a function restricting its availability based on compile-time
1017 // information in the evaluated context. Useful to convert runtime errors to
1018 // compile-time errors if functions' arguments are always known at compile time.
1019 //
1020 // SFINAE and `requires` clauses can restrict function availability based on the
1021 // unevaluated context (type information and syntactic correctness). This
1022 // provides a similar capability based on the evaluated context (variable
1023 // values). If the condition fails, or cannot be determined at compile time, the
1024 // function is excluded from the overload set.
1025 //
1026 // Some use cases could be satisfied without this by marking the function
1027 // `consteval` and breaking compile when the condition fails (e.g. via
1028 // `CHECK()`/`assert()`). However, `ENABLE_IF_ATTR()` is generally superior:
1029 //   - Not all desired functions can be made `consteval`; e.g. most
1030 //     constructors.
1031 //   - The error message in the macro case is clearer and more actionable.
1032 //   - `ENABLE_IF_ATTR()` interacts better with template metaprogramming.
1033 //
1034 // See also:
1035 //   https://clang.llvm.org/docs/AttributeReference.html#enable-if
1036 //   https://github.com/chromium/subspace/issues/266
1037 //
1038 // Usage:
1039 // ```
1040 //   void NotConsteval(int a) {
1041 //     assert(a > 0);
1042 //   }
1043 //   consteval void WithoutEnableIf(int a) {
1044 //     assert(a > 0);
1045 //   }
1046 //   void WithEnableIf(int a) ENABLE_IF_ATTR(a > 0, "arg must be positive") {}
1047 //   void Func(int i) {
1048 //     // Compiles; assertion fails at runtime.
1049 //     NotConsteval(-1);
1050 //
1051 //     // Will not compile; diagnosed as not a constant expression.
1052 //     WithoutEnableIf(-1);
1053 //
1054 //     // Will not compile; diagnosed as no matching function call with
1055 //     // "note: candidate disabled: arg must be positive".
1056 //     WithEnableIf(-1);
1057 //
1058 //     // Will not compile (same reason). Marking `Func()` as
1059 //     // `ENABLE_IF_ATTR(i > 0, ...)` will not help; the compiler's analysis is
1060 //     // not sufficiently sophisticated to propagate this constraint.
1061 //     WithEnableIf(i);
1062 //   }
1063 // ```
1064 #if HAS_ATTRIBUTE(enable_if)
1065 #define ENABLE_IF_ATTR(cond, msg) __attribute__((enable_if(cond, msg)))
1066 #else
1067 #define ENABLE_IF_ATTR(cond, msg)
1068 #endif
1069 
1070 #endif  // BASE_COMPILER_SPECIFIC_H_
1071