1 // Copyright 2014 the V8 project authors. All rights reserved.
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 V8_BASE_MACROS_H_
6 #define V8_BASE_MACROS_H_
7
8 #include <limits>
9 #include <type_traits>
10
11 #include "src/base/compiler-specific.h"
12 #include "src/base/logging.h"
13
14 // No-op macro which is used to work around MSVC's funky VA_ARGS support.
15 #define EXPAND(x) x
16
17 // This macro does nothing. That's all.
18 #define NOTHING(...)
19
20 // TODO(all) Replace all uses of this macro with C++'s offsetof. To do that, we
21 // have to make sure that only standard-layout types and simple field
22 // designators are used.
23 #define OFFSET_OF(type, field) \
24 (reinterpret_cast<intptr_t>(&(reinterpret_cast<type*>(16)->field)) - 16)
25
26
27 // The arraysize(arr) macro returns the # of elements in an array arr.
28 // The expression is a compile-time constant, and therefore can be
29 // used in defining new arrays, for example. If you use arraysize on
30 // a pointer by mistake, you will get a compile-time error.
31 #define arraysize(array) (sizeof(ArraySizeHelper(array)))
32
33
34 // This template function declaration is used in defining arraysize.
35 // Note that the function doesn't need an implementation, as we only
36 // use its type.
37 template <typename T, size_t N>
38 char (&ArraySizeHelper(T (&array)[N]))[N];
39
40
41 #if !V8_CC_MSVC
42 // That gcc wants both of these prototypes seems mysterious. VC, for
43 // its part, can't decide which to use (another mystery). Matching of
44 // template overloads: the final frontier.
45 template <typename T, size_t N>
46 char (&ArraySizeHelper(const T (&array)[N]))[N];
47 #endif
48
49 // bit_cast<Dest,Source> is a template function that implements the
50 // equivalent of "*reinterpret_cast<Dest*>(&source)". We need this in
51 // very low-level functions like the protobuf library and fast math
52 // support.
53 //
54 // float f = 3.14159265358979;
55 // int i = bit_cast<int32>(f);
56 // // i = 0x40490fdb
57 //
58 // The classical address-casting method is:
59 //
60 // // WRONG
61 // float f = 3.14159265358979; // WRONG
62 // int i = * reinterpret_cast<int*>(&f); // WRONG
63 //
64 // The address-casting method actually produces undefined behavior
65 // according to ISO C++ specification section 3.10 -15 -. Roughly, this
66 // section says: if an object in memory has one type, and a program
67 // accesses it with a different type, then the result is undefined
68 // behavior for most values of "different type".
69 //
70 // This is true for any cast syntax, either *(int*)&f or
71 // *reinterpret_cast<int*>(&f). And it is particularly true for
72 // conversions between integral lvalues and floating-point lvalues.
73 //
74 // The purpose of 3.10 -15- is to allow optimizing compilers to assume
75 // that expressions with different types refer to different memory. gcc
76 // 4.0.1 has an optimizer that takes advantage of this. So a
77 // non-conforming program quietly produces wildly incorrect output.
78 //
79 // The problem is not the use of reinterpret_cast. The problem is type
80 // punning: holding an object in memory of one type and reading its bits
81 // back using a different type.
82 //
83 // The C++ standard is more subtle and complex than this, but that
84 // is the basic idea.
85 //
86 // Anyways ...
87 //
88 // bit_cast<> calls memcpy() which is blessed by the standard,
89 // especially by the example in section 3.9 . Also, of course,
90 // bit_cast<> wraps up the nasty logic in one place.
91 //
92 // Fortunately memcpy() is very fast. In optimized mode, with a
93 // constant size, gcc 2.95.3, gcc 4.0.1, and msvc 7.1 produce inline
94 // code with the minimal amount of data movement. On a 32-bit system,
95 // memcpy(d,s,4) compiles to one load and one store, and memcpy(d,s,8)
96 // compiles to two loads and two stores.
97 //
98 // I tested this code with gcc 2.95.3, gcc 4.0.1, icc 8.1, and msvc 7.1.
99 //
100 // WARNING: if Dest or Source is a non-POD type, the result of the memcpy
101 // is likely to surprise you.
102 template <class Dest, class Source>
bit_cast(Source const & source)103 V8_INLINE Dest bit_cast(Source const& source) {
104 static_assert(sizeof(Dest) == sizeof(Source),
105 "source and dest must be same size");
106 Dest dest;
107 memcpy(&dest, &source, sizeof(dest));
108 return dest;
109 }
110
111 // Explicitly declare the assignment operator as deleted.
112 // Note: This macro is deprecated and will be removed soon. Please explicitly
113 // delete the assignment operator instead.
114 #define DISALLOW_ASSIGN(TypeName) TypeName& operator=(const TypeName&) = delete
115
116 // Explicitly declare the copy constructor and assignment operator as deleted.
117 // This also deletes the implicit move constructor and implicit move assignment
118 // operator, but still allows to manually define them.
119 // Note: This macro is deprecated and will be removed soon. Please explicitly
120 // delete the copy constructor and assignment operator instead.
121 #define DISALLOW_COPY_AND_ASSIGN(TypeName) \
122 TypeName(const TypeName&) = delete; \
123 DISALLOW_ASSIGN(TypeName)
124
125 // Explicitly declare all implicit constructors as deleted, namely the
126 // default constructor, copy constructor and operator= functions.
127 // This is especially useful for classes containing only static methods.
128 #define DISALLOW_IMPLICIT_CONSTRUCTORS(TypeName) \
129 TypeName() = delete; \
130 DISALLOW_COPY_AND_ASSIGN(TypeName)
131
132 // Disallow copying a type, but provide default construction, move construction
133 // and move assignment. Especially useful for move-only structs.
134 #define MOVE_ONLY_WITH_DEFAULT_CONSTRUCTORS(TypeName) \
135 TypeName() = default; \
136 MOVE_ONLY_NO_DEFAULT_CONSTRUCTOR(TypeName)
137
138 // Disallow copying a type, and only provide move construction and move
139 // assignment. Especially useful for move-only structs.
140 #define MOVE_ONLY_NO_DEFAULT_CONSTRUCTOR(TypeName) \
141 TypeName(TypeName&&) V8_NOEXCEPT = default; \
142 TypeName& operator=(TypeName&&) V8_NOEXCEPT = default; \
143 DISALLOW_COPY_AND_ASSIGN(TypeName)
144
145 // A macro to disallow the dynamic allocation.
146 // This should be used in the private: declarations for a class
147 // Declaring operator new and delete as deleted is not spec compliant.
148 // Extract from 3.2.2 of C++11 spec:
149 // [...] A non-placement deallocation function for a class is
150 // odr-used by the definition of the destructor of that class, [...]
151 #define DISALLOW_NEW_AND_DELETE() \
152 void* operator new(size_t) { v8::base::OS::Abort(); } \
153 void* operator new[](size_t) { v8::base::OS::Abort(); } \
154 void operator delete(void*, size_t) { v8::base::OS::Abort(); } \
155 void operator delete[](void*, size_t) { v8::base::OS::Abort(); }
156
157 // Define V8_USE_ADDRESS_SANITIZER macro.
158 #if defined(__has_feature)
159 #if __has_feature(address_sanitizer)
160 #define V8_USE_ADDRESS_SANITIZER 1
161 #endif
162 #endif
163
164 // Define DISABLE_ASAN macro.
165 #ifdef V8_USE_ADDRESS_SANITIZER
166 #define DISABLE_ASAN __attribute__((no_sanitize_address))
167 #else
168 #define DISABLE_ASAN
169 #endif
170
171 // Define V8_USE_MEMORY_SANITIZER macro.
172 #if defined(__has_feature)
173 #if __has_feature(memory_sanitizer)
174 #define V8_USE_MEMORY_SANITIZER 1
175 #endif
176 #endif
177
178 // DISABLE_CFI_PERF -- Disable Control Flow Integrity checks for Perf reasons.
179 #define DISABLE_CFI_PERF V8_CLANG_NO_SANITIZE("cfi")
180
181 // DISABLE_CFI_ICALL -- Disable Control Flow Integrity indirect call checks,
182 // useful because calls into JITed code can not be CFI verified.
183 #ifdef V8_OS_WIN
184 // On Windows, also needs __declspec(guard(nocf)) for CFG.
185 #define DISABLE_CFI_ICALL \
186 V8_CLANG_NO_SANITIZE("cfi-icall") \
187 __declspec(guard(nocf))
188 #else
189 #define DISABLE_CFI_ICALL V8_CLANG_NO_SANITIZE("cfi-icall")
190 #endif
191
192 #if V8_CC_GNU
193 #define V8_IMMEDIATE_CRASH() __builtin_trap()
194 #else
195 #define V8_IMMEDIATE_CRASH() ((void(*)())0)()
196 #endif
197
198 // A convenience wrapper around static_assert without a string message argument.
199 // Once C++17 becomes the default, this macro can be removed in favor of the
200 // new static_assert(condition) overload.
201 #define STATIC_ASSERT(test) static_assert(test, #test)
202
203 namespace v8 {
204 namespace base {
205
206 // Note that some implementations of std::is_trivially_copyable mandate that at
207 // least one of the copy constructor, move constructor, copy assignment or move
208 // assignment is non-deleted, while others do not. Be aware that also
209 // base::is_trivially_copyable will differ for these cases.
210 template <typename T>
211 struct is_trivially_copyable {
212 #if V8_CC_MSVC
213 // Unfortunately, MSVC 2015 is broken in that std::is_trivially_copyable can
214 // be false even though it should be true according to the standard.
215 // (status at 2018-02-26, observed on the msvc waterfall bot).
216 // Interestingly, the lower-level primitives used below are working as
217 // intended, so we reimplement this according to the standard.
218 // See also https://developercommunity.visualstudio.com/content/problem/
219 // 170883/msvc-type-traits-stdis-trivial-is-bugged.html.
220 static constexpr bool value =
221 // Copy constructor is trivial or deleted.
222 (std::is_trivially_copy_constructible<T>::value ||
223 !std::is_copy_constructible<T>::value) &&
224 // Copy assignment operator is trivial or deleted.
225 (std::is_trivially_copy_assignable<T>::value ||
226 !std::is_copy_assignable<T>::value) &&
227 // Move constructor is trivial or deleted.
228 (std::is_trivially_move_constructible<T>::value ||
229 !std::is_move_constructible<T>::value) &&
230 // Move assignment operator is trivial or deleted.
231 (std::is_trivially_move_assignable<T>::value ||
232 !std::is_move_assignable<T>::value) &&
233 // (Some implementations mandate that one of the above is non-deleted, but
234 // the standard does not, so let's skip this check.)
235 // Trivial non-deleted destructor.
236 std::is_trivially_destructible<T>::value;
237 #else
238 static constexpr bool value = std::is_trivially_copyable<T>::value;
239 #endif
240 };
241 #define ASSERT_TRIVIALLY_COPYABLE(T) \
242 static_assert(::v8::base::is_trivially_copyable<T>::value, \
243 #T " should be trivially copyable")
244 #define ASSERT_NOT_TRIVIALLY_COPYABLE(T) \
245 static_assert(!::v8::base::is_trivially_copyable<T>::value, \
246 #T " should not be trivially copyable")
247
248 // The USE(x, ...) template is used to silence C++ compiler warnings
249 // issued for (yet) unused variables (typically parameters).
250 // The arguments are guaranteed to be evaluated from left to right.
251 struct Use {
252 template <typename T>
UseUse253 Use(T&&) {} // NOLINT(runtime/explicit)
254 };
255 #define USE(...) \
256 do { \
257 ::v8::base::Use unused_tmp_array_for_use_macro[]{__VA_ARGS__}; \
258 (void)unused_tmp_array_for_use_macro; \
259 } while (false)
260
261 // Evaluate the instantiations of an expression with parameter packs.
262 // Since USE has left-to-right evaluation order of it's arguments,
263 // the parameter pack is iterated from left to right and side effects
264 // have defined behavior.
265 #define ITERATE_PACK(...) USE(0, ((__VA_ARGS__), 0)...)
266
267 } // namespace base
268 } // namespace v8
269
270 // implicit_cast<A>(x) triggers an implicit cast from {x} to type {A}. This is
271 // useful in situations where static_cast<A>(x) would do too much.
272 // Only use this for cheap-to-copy types, or use move semantics explicitly.
273 template <class A>
implicit_cast(A x)274 V8_INLINE A implicit_cast(A x) {
275 return x;
276 }
277
278 // Define our own macros for writing 64-bit constants. This is less fragile
279 // than defining __STDC_CONSTANT_MACROS before including <stdint.h>, and it
280 // works on compilers that don't have it (like MSVC).
281 #if V8_CC_MSVC
282 # if V8_HOST_ARCH_64_BIT
283 # define V8_PTR_PREFIX "ll"
284 # else
285 # define V8_PTR_PREFIX ""
286 # endif // V8_HOST_ARCH_64_BIT
287 #elif V8_CC_MINGW64
288 # define V8_PTR_PREFIX "I64"
289 #elif V8_HOST_ARCH_64_BIT
290 # define V8_PTR_PREFIX "l"
291 #else
292 #if V8_OS_AIX
293 #define V8_PTR_PREFIX "l"
294 #else
295 # define V8_PTR_PREFIX ""
296 #endif
297 #endif
298
299 #define V8PRIxPTR V8_PTR_PREFIX "x"
300 #define V8PRIdPTR V8_PTR_PREFIX "d"
301 #define V8PRIuPTR V8_PTR_PREFIX "u"
302
303 #if V8_TARGET_ARCH_64_BIT
304 #define V8_PTR_HEX_DIGITS 12
305 #define V8PRIxPTR_FMT "0x%012" V8PRIxPTR
306 #else
307 #define V8_PTR_HEX_DIGITS 8
308 #define V8PRIxPTR_FMT "0x%08" V8PRIxPTR
309 #endif
310
311 // ptrdiff_t is 't' according to the standard, but MSVC uses 'I'.
312 #if V8_CC_MSVC
313 #define V8PRIxPTRDIFF "Ix"
314 #define V8PRIdPTRDIFF "Id"
315 #define V8PRIuPTRDIFF "Iu"
316 #else
317 #define V8PRIxPTRDIFF "tx"
318 #define V8PRIdPTRDIFF "td"
319 #define V8PRIuPTRDIFF "tu"
320 #endif
321
322 // Fix for Mac OS X defining uintptr_t as "unsigned long":
323 #if V8_OS_MACOSX
324 #undef V8PRIxPTR
325 #define V8PRIxPTR "lx"
326 #undef V8PRIdPTR
327 #define V8PRIdPTR "ld"
328 #undef V8PRIuPTR
329 #define V8PRIuPTR "lxu"
330 #endif
331
332 // Make a uint64 from two uint32_t halves.
make_uint64(uint32_t high,uint32_t low)333 inline uint64_t make_uint64(uint32_t high, uint32_t low) {
334 return (uint64_t{high} << 32) + low;
335 }
336
337 // Return the largest multiple of m which is <= x.
338 template <typename T>
RoundDown(T x,intptr_t m)339 inline T RoundDown(T x, intptr_t m) {
340 STATIC_ASSERT(std::is_integral<T>::value);
341 // m must be a power of two.
342 DCHECK(m != 0 && ((m & (m - 1)) == 0));
343 return x & static_cast<T>(-m);
344 }
345 template <intptr_t m, typename T>
RoundDown(T x)346 constexpr inline T RoundDown(T x) {
347 STATIC_ASSERT(std::is_integral<T>::value);
348 // m must be a power of two.
349 STATIC_ASSERT(m != 0 && ((m & (m - 1)) == 0));
350 return x & static_cast<T>(-m);
351 }
352
353 // Return the smallest multiple of m which is >= x.
354 template <typename T>
RoundUp(T x,intptr_t m)355 inline T RoundUp(T x, intptr_t m) {
356 STATIC_ASSERT(std::is_integral<T>::value);
357 return RoundDown<T>(static_cast<T>(x + m - 1), m);
358 }
359 template <intptr_t m, typename T>
RoundUp(T x)360 constexpr inline T RoundUp(T x) {
361 STATIC_ASSERT(std::is_integral<T>::value);
362 return RoundDown<m, T>(static_cast<T>(x + (m - 1)));
363 }
364
365 template <typename T, typename U>
IsAligned(T value,U alignment)366 constexpr inline bool IsAligned(T value, U alignment) {
367 return (value & (alignment - 1)) == 0;
368 }
369
AlignedAddress(void * address,size_t alignment)370 inline void* AlignedAddress(void* address, size_t alignment) {
371 // The alignment must be a power of two.
372 DCHECK_EQ(alignment & (alignment - 1), 0u);
373 return reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(address) &
374 ~static_cast<uintptr_t>(alignment - 1));
375 }
376
377 // Bounds checks for float to integer conversions, which does truncation. Hence,
378 // the range of legal values is (min - 1, max + 1).
379 template <typename int_t, typename float_t, typename biggest_int_t = int64_t>
is_inbounds(float_t v)380 bool is_inbounds(float_t v) {
381 static_assert(sizeof(int_t) < sizeof(biggest_int_t),
382 "int_t can't be bounds checked by the compiler");
383 constexpr float_t kLowerBound =
384 static_cast<float_t>(std::numeric_limits<int_t>::min()) - 1;
385 constexpr float_t kUpperBound =
386 static_cast<float_t>(std::numeric_limits<int_t>::max()) + 1;
387 constexpr bool kLowerBoundIsMin =
388 static_cast<biggest_int_t>(kLowerBound) ==
389 static_cast<biggest_int_t>(std::numeric_limits<int_t>::min());
390 constexpr bool kUpperBoundIsMax =
391 static_cast<biggest_int_t>(kUpperBound) ==
392 static_cast<biggest_int_t>(std::numeric_limits<int_t>::max());
393 // Using USE(var) is only a workaround for a GCC 8.1 bug.
394 USE(kLowerBoundIsMin);
395 USE(kUpperBoundIsMax);
396 return (kLowerBoundIsMin ? (kLowerBound <= v) : (kLowerBound < v)) &&
397 (kUpperBoundIsMax ? (v <= kUpperBound) : (v < kUpperBound));
398 }
399
400 #ifdef V8_OS_WIN
401
402 // Setup for Windows shared library export.
403 #ifdef BUILDING_V8_SHARED
404 #define V8_EXPORT_PRIVATE __declspec(dllexport)
405 #elif USING_V8_SHARED
406 #define V8_EXPORT_PRIVATE __declspec(dllimport)
407 #else
408 #define V8_EXPORT_PRIVATE
409 #endif // BUILDING_V8_SHARED
410
411 #else // V8_OS_WIN
412
413 // Setup for Linux shared library export.
414 #if V8_HAS_ATTRIBUTE_VISIBILITY
415 #ifdef BUILDING_V8_SHARED
416 #define V8_EXPORT_PRIVATE __attribute__((visibility("default")))
417 #else
418 #define V8_EXPORT_PRIVATE
419 #endif
420 #else
421 #define V8_EXPORT_PRIVATE
422 #endif
423
424 #endif // V8_OS_WIN
425
426 #endif // V8_BASE_MACROS_H_
427