1 // -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*-
2 // Copyright (c) 2005, Google Inc.
3 // All rights reserved.
4 //
5 // Redistribution and use in source and binary forms, with or without
6 // modification, are permitted provided that the following conditions are
7 // met:
8 //
9 //     * Redistributions of source code must retain the above copyright
10 // notice, this list of conditions and the following disclaimer.
11 //     * Redistributions in binary form must reproduce the above
12 // copyright notice, this list of conditions and the following disclaimer
13 // in the documentation and/or other materials provided with the
14 // distribution.
15 //     * Neither the name of Google Inc. nor the names of its
16 // contributors may be used to endorse or promote products derived from
17 // this software without specific prior written permission.
18 //
19 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 
31 #ifndef _BASICTYPES_H_
32 #define _BASICTYPES_H_
33 
34 #include <config.h>
35 #include <string.h>       // for memcpy()
36 #ifdef HAVE_INTTYPES_H
37 #include <inttypes.h>     // gets us PRId64, etc
38 #endif
39 
40 // To use this in an autoconf setting, make sure you run the following
41 // autoconf macros:
42 //    AC_HEADER_STDC              /* for stdint_h and inttypes_h */
43 //    AC_CHECK_TYPES([__int64])   /* defined in some windows platforms */
44 
45 #ifdef HAVE_INTTYPES_H
46 #include <inttypes.h>           // uint16_t might be here; PRId64 too.
47 #endif
48 #ifdef HAVE_STDINT_H
49 #include <stdint.h>             // to get uint16_t (ISO naming madness)
50 #endif
51 #include <sys/types.h>          // our last best hope for uint16_t
52 
53 // Standard typedefs
54 // All Google code is compiled with -funsigned-char to make "char"
55 // unsigned.  Google code therefore doesn't need a "uchar" type.
56 // TODO(csilvers): how do we make sure unsigned-char works on non-gcc systems?
57 typedef signed char         schar;
58 typedef int8_t              int8;
59 typedef int16_t             int16;
60 typedef int32_t             int32;
61 typedef int64_t             int64;
62 
63 // NOTE: unsigned types are DANGEROUS in loops and other arithmetical
64 // places.  Use the signed types unless your variable represents a bit
65 // pattern (eg a hash value) or you really need the extra bit.  Do NOT
66 // use 'unsigned' to express "this value should always be positive";
67 // use assertions for this.
68 
69 typedef uint8_t            uint8;
70 typedef uint16_t           uint16;
71 typedef uint32_t           uint32;
72 typedef uint64_t           uint64;
73 
74 const uint16 kuint16max = (   (uint16) 0xFFFF);
75 const uint32 kuint32max = (   (uint32) 0xFFFFFFFF);
76 const uint64 kuint64max = ( (((uint64) kuint32max) << 32) | kuint32max );
77 
78 const  int8  kint8max   = (   (  int8) 0x7F);
79 const  int16 kint16max  = (   ( int16) 0x7FFF);
80 const  int32 kint32max  = (   ( int32) 0x7FFFFFFF);
81 const  int64 kint64max =  ( ((( int64) kint32max) << 32) | kuint32max );
82 
83 const  int8  kint8min   = (   (  int8) 0x80);
84 const  int16 kint16min  = (   ( int16) 0x8000);
85 const  int32 kint32min  = (   ( int32) 0x80000000);
86 const  int64 kint64min =  (-kint64max - 1LL);
87 
88 // Define the "portable" printf and scanf macros, if they're not
89 // already there (via the inttypes.h we #included above, hopefully).
90 // Mostly it's old systems that don't support inttypes.h, so we assume
91 // they're 32 bit.
92 #ifndef PRIx64
93 #define PRIx64 "llx"
94 #endif
95 #ifndef SCNx64
96 #define SCNx64 "llx"
97 #endif
98 #ifndef PRId64
99 #define PRId64 "lld"
100 #endif
101 #ifndef SCNd64
102 #define SCNd64 "lld"
103 #endif
104 #ifndef PRIu64
105 #define PRIu64 "llu"
106 #endif
107 #ifndef PRIxPTR
108 #define PRIxPTR "lx"
109 #endif
110 
111 // Also allow for printing of a pthread_t.
112 #define GPRIuPTHREAD "lu"
113 #define GPRIxPTHREAD "lx"
114 #if defined(__CYGWIN__) || defined(__CYGWIN32__) || defined(__APPLE__) || defined(__FreeBSD__)
115 #define PRINTABLE_PTHREAD(pthreadt) reinterpret_cast<uintptr_t>(pthreadt)
116 #else
117 #define PRINTABLE_PTHREAD(pthreadt) pthreadt
118 #endif
119 
120 #ifdef HAVE_BUILTIN_EXPECT
121 #define PREDICT_TRUE(x) __builtin_expect(!!(x), 1)
122 #define PREDICT_FALSE(x) __builtin_expect(!!(x), 0)
123 #else
124 #define PREDICT_TRUE(x) (x)
125 #define PREDICT_FALSE(x) (x)
126 #endif
127 
128 // A macro to disallow the evil copy constructor and operator= functions
129 // This should be used in the private: declarations for a class
130 #define DISALLOW_EVIL_CONSTRUCTORS(TypeName)    \
131   TypeName(const TypeName&);                    \
132   void operator=(const TypeName&)
133 
134 // An alternate name that leaves out the moral judgment... :-)
135 #define DISALLOW_COPY_AND_ASSIGN(TypeName) DISALLOW_EVIL_CONSTRUCTORS(TypeName)
136 
137 // The COMPILE_ASSERT macro can be used to verify that a compile time
138 // expression is true. For example, you could use it to verify the
139 // size of a static array:
140 //
141 //   COMPILE_ASSERT(sizeof(num_content_type_names) == sizeof(int),
142 //                  content_type_names_incorrect_size);
143 //
144 // or to make sure a struct is smaller than a certain size:
145 //
146 //   COMPILE_ASSERT(sizeof(foo) < 128, foo_too_large);
147 //
148 // The second argument to the macro is the name of the variable. If
149 // the expression is false, most compilers will issue a warning/error
150 // containing the name of the variable.
151 //
152 // Implementation details of COMPILE_ASSERT:
153 //
154 // - COMPILE_ASSERT works by defining an array type that has -1
155 //   elements (and thus is invalid) when the expression is false.
156 //
157 // - The simpler definition
158 //
159 //     #define COMPILE_ASSERT(expr, msg) typedef char msg[(expr) ? 1 : -1]
160 //
161 //   does not work, as gcc supports variable-length arrays whose sizes
162 //   are determined at run-time (this is gcc's extension and not part
163 //   of the C++ standard).  As a result, gcc fails to reject the
164 //   following code with the simple definition:
165 //
166 //     int foo;
167 //     COMPILE_ASSERT(foo, msg); // not supposed to compile as foo is
168 //                               // not a compile-time constant.
169 //
170 // - By using the type CompileAssert<(bool(expr))>, we ensures that
171 //   expr is a compile-time constant.  (Template arguments must be
172 //   determined at compile-time.)
173 //
174 // - The outter parentheses in CompileAssert<(bool(expr))> are necessary
175 //   to work around a bug in gcc 3.4.4 and 4.0.1.  If we had written
176 //
177 //     CompileAssert<bool(expr)>
178 //
179 //   instead, these compilers will refuse to compile
180 //
181 //     COMPILE_ASSERT(5 > 0, some_message);
182 //
183 //   (They seem to think the ">" in "5 > 0" marks the end of the
184 //   template argument list.)
185 //
186 // - The array size is (bool(expr) ? 1 : -1), instead of simply
187 //
188 //     ((expr) ? 1 : -1).
189 //
190 //   This is to avoid running into a bug in MS VC 7.1, which
191 //   causes ((0.0) ? 1 : -1) to incorrectly evaluate to 1.
192 
193 template <bool>
194 struct CompileAssert {
195 };
196 
197 #ifdef HAVE___ATTRIBUTE__
198 # define ATTRIBUTE_UNUSED __attribute__((unused))
199 #else
200 # define ATTRIBUTE_UNUSED
201 #endif
202 
203 #if defined(HAVE___ATTRIBUTE__) && defined(HAVE_TLS) && \
204     !(defined(__GNUC__) && !defined(__clang__) && defined(__arm__))
205 #define ATTR_INITIAL_EXEC __attribute__ ((tls_model ("initial-exec")))
206 #else
207 #define ATTR_INITIAL_EXEC
208 #endif
209 
210 #define COMPILE_ASSERT(expr, msg)                               \
211   typedef CompileAssert<(bool(expr))> msg[bool(expr) ? 1 : -1] ATTRIBUTE_UNUSED
212 
213 #define arraysize(a)  (sizeof(a) / sizeof(*(a)))
214 
215 #define OFFSETOF_MEMBER(strct, field)                                   \
216    (reinterpret_cast<char*>(&reinterpret_cast<strct*>(16)->field) -     \
217     reinterpret_cast<char*>(16))
218 
219 // bit_cast<Dest,Source> implements the equivalent of
220 // "*reinterpret_cast<Dest*>(&source)".
221 //
222 // The reinterpret_cast method would produce undefined behavior
223 // according to ISO C++ specification section 3.10 -15 -.
224 // bit_cast<> calls memcpy() which is blessed by the standard,
225 // especially by the example in section 3.9.
226 //
227 // Fortunately memcpy() is very fast.  In optimized mode, with a
228 // constant size, gcc 2.95.3, gcc 4.0.1, and msvc 7.1 produce inline
229 // code with the minimal amount of data movement.  On a 32-bit system,
230 // memcpy(d,s,4) compiles to one load and one store, and memcpy(d,s,8)
231 // compiles to two loads and two stores.
232 
233 template <class Dest, class Source>
bit_cast(const Source & source)234 inline Dest bit_cast(const Source& source) {
235   COMPILE_ASSERT(sizeof(Dest) == sizeof(Source), bitcasting_unequal_sizes);
236   Dest dest;
237   memcpy(&dest, &source, sizeof(dest));
238   return dest;
239 }
240 
241 // bit_store<Dest,Source> implements the equivalent of
242 // "dest = *reinterpret_cast<Dest*>(&source)".
243 //
244 // This prevents undefined behavior when the dest pointer is unaligned.
245 template <class Dest, class Source>
bit_store(Dest * dest,const Source * source)246 inline void bit_store(Dest *dest, const Source *source) {
247   COMPILE_ASSERT(sizeof(Dest) == sizeof(Source), bitcasting_unequal_sizes);
248   memcpy(dest, source, sizeof(Dest));
249 }
250 
251 #ifdef HAVE___ATTRIBUTE__
252 # define ATTRIBUTE_WEAK      __attribute__((weak))
253 # define ATTRIBUTE_NOINLINE  __attribute__((noinline))
254 #else
255 # define ATTRIBUTE_WEAK
256 # define ATTRIBUTE_NOINLINE
257 #endif
258 
259 #if defined(HAVE___ATTRIBUTE__) && defined(__ELF__)
260 # define ATTRIBUTE_VISIBILITY_HIDDEN __attribute__((visibility("hidden")))
261 #else
262 # define ATTRIBUTE_VISIBILITY_HIDDEN
263 #endif
264 
265 // Section attributes are supported for both ELF and Mach-O, but in
266 // very different ways.  Here's the API we provide:
267 // 1) ATTRIBUTE_SECTION: put this with the declaration of all functions
268 //    you want to be in the same linker section
269 // 2) DEFINE_ATTRIBUTE_SECTION_VARS: must be called once per unique
270 //    name.  You want to make sure this is executed before any
271 //    DECLARE_ATTRIBUTE_SECTION_VARS; the easiest way is to put them
272 //    in the same .cc file.  Put this call at the global level.
273 // 3) INIT_ATTRIBUTE_SECTION_VARS: you can scatter calls to this in
274 //    multiple places to help ensure execution before any
275 //    DECLARE_ATTRIBUTE_SECTION_VARS.  You must have at least one
276 //    DEFINE, but you can have many INITs.  Put each in its own scope.
277 // 4) DECLARE_ATTRIBUTE_SECTION_VARS: must be called before using
278 //    ATTRIBUTE_SECTION_START or ATTRIBUTE_SECTION_STOP on a name.
279 //    Put this call at the global level.
280 // 5) ATTRIBUTE_SECTION_START/ATTRIBUTE_SECTION_STOP: call this to say
281 //    where in memory a given section is.  All functions declared with
282 //    ATTRIBUTE_SECTION are guaranteed to be between START and STOP.
283 
284 #if defined(HAVE___ATTRIBUTE__) && defined(__ELF__)
285 # define ATTRIBUTE_SECTION(name) __attribute__ ((section (#name))) __attribute__((noinline))
286 
287   // Weak section declaration to be used as a global declaration
288   // for ATTRIBUTE_SECTION_START|STOP(name) to compile and link
289   // even without functions with ATTRIBUTE_SECTION(name).
290 # define DECLARE_ATTRIBUTE_SECTION_VARS(name) \
291     extern char __start_##name[] ATTRIBUTE_WEAK; \
292     extern char __stop_##name[] ATTRIBUTE_WEAK
293 # define INIT_ATTRIBUTE_SECTION_VARS(name)     // no-op for ELF
294 # define DEFINE_ATTRIBUTE_SECTION_VARS(name)   // no-op for ELF
295 
296   // Return void* pointers to start/end of a section of code with functions
297   // having ATTRIBUTE_SECTION(name), or 0 if no such function exists.
298   // One must DECLARE_ATTRIBUTE_SECTION(name) for this to compile and link.
299 # define ATTRIBUTE_SECTION_START(name) (reinterpret_cast<void*>(__start_##name))
300 # define ATTRIBUTE_SECTION_STOP(name) (reinterpret_cast<void*>(__stop_##name))
301 # define HAVE_ATTRIBUTE_SECTION_START 1
302 
303 #elif defined(HAVE___ATTRIBUTE__) && defined(__MACH__)
304 # define ATTRIBUTE_SECTION(name) __attribute__ ((section ("__TEXT, " #name)))
305 
306 #include <mach-o/getsect.h>
307 #include <mach-o/dyld.h>
308 class AssignAttributeStartEnd {
309  public:
AssignAttributeStartEnd(const char * name,char ** pstart,char ** pend)310   AssignAttributeStartEnd(const char* name, char** pstart, char** pend) {
311     // Find out what dynamic library name is defined in
312     if (_dyld_present()) {
313       for (int i = _dyld_image_count() - 1; i >= 0; --i) {
314         const mach_header* hdr = _dyld_get_image_header(i);
315 #ifdef MH_MAGIC_64
316         if (hdr->magic == MH_MAGIC_64) {
317           uint64_t len;
318           *pstart = getsectdatafromheader_64((mach_header_64*)hdr,
319                                              "__TEXT", name, &len);
320           if (*pstart) {   // NULL if not defined in this dynamic library
321             *pstart += _dyld_get_image_vmaddr_slide(i);   // correct for reloc
322             *pend = *pstart + len;
323             return;
324           }
325         }
326 #endif
327         if (hdr->magic == MH_MAGIC) {
328           uint32_t len;
329           *pstart = getsectdatafromheader(hdr, "__TEXT", name, &len);
330           if (*pstart) {   // NULL if not defined in this dynamic library
331             *pstart += _dyld_get_image_vmaddr_slide(i);   // correct for reloc
332             *pend = *pstart + len;
333             return;
334           }
335         }
336       }
337     }
338     // If we get here, not defined in a dll at all.  See if defined statically.
339     unsigned long len;    // don't ask me why this type isn't uint32_t too...
340     *pstart = getsectdata("__TEXT", name, &len);
341     *pend = *pstart + len;
342   }
343 };
344 
345 #define DECLARE_ATTRIBUTE_SECTION_VARS(name)    \
346   extern char* __start_##name;                  \
347   extern char* __stop_##name
348 
349 #define INIT_ATTRIBUTE_SECTION_VARS(name)               \
350   DECLARE_ATTRIBUTE_SECTION_VARS(name);                 \
351   static const AssignAttributeStartEnd __assign_##name( \
352     #name, &__start_##name, &__stop_##name)
353 
354 #define DEFINE_ATTRIBUTE_SECTION_VARS(name)     \
355   char* __start_##name, *__stop_##name;         \
356   INIT_ATTRIBUTE_SECTION_VARS(name)
357 
358 # define ATTRIBUTE_SECTION_START(name) (reinterpret_cast<void*>(__start_##name))
359 # define ATTRIBUTE_SECTION_STOP(name) (reinterpret_cast<void*>(__stop_##name))
360 # define HAVE_ATTRIBUTE_SECTION_START 1
361 
362 #else  // not HAVE___ATTRIBUTE__ && __ELF__, nor HAVE___ATTRIBUTE__ && __MACH__
363 # define ATTRIBUTE_SECTION(name)
364 # define DECLARE_ATTRIBUTE_SECTION_VARS(name)
365 # define INIT_ATTRIBUTE_SECTION_VARS(name)
366 # define DEFINE_ATTRIBUTE_SECTION_VARS(name)
367 # define ATTRIBUTE_SECTION_START(name) (reinterpret_cast<void*>(0))
368 # define ATTRIBUTE_SECTION_STOP(name) (reinterpret_cast<void*>(0))
369 
370 #endif  // HAVE___ATTRIBUTE__ and __ELF__ or __MACH__
371 
372 #if defined(HAVE___ATTRIBUTE__)
373 # if (defined(__i386__) || defined(__x86_64__))
374 #   define CACHELINE_ALIGNED __attribute__((aligned(64)))
375 # elif (defined(__PPC__) || defined(__PPC64__))
376 #   define CACHELINE_ALIGNED __attribute__((aligned(16)))
377 # elif (defined(__arm__))
378 #   define CACHELINE_ALIGNED __attribute__((aligned(64)))
379     // some ARMs have shorter cache lines (ARM1176JZF-S is 32 bytes for example) but obviously 64-byte aligned implies 32-byte aligned
380 # elif (defined(__mips__))
381 #   define CACHELINE_ALIGNED __attribute__((aligned(128)))
382 # elif (defined(__aarch64__))
383 #   define CACHELINE_ALIGNED __attribute__((aligned(64)))
384     // implementation specific, Cortex-A53 and 57 should have 64 bytes
385 # elif (defined(__s390__))
386 #   define CACHELINE_ALIGNED __attribute__((aligned(256)))
387 # else
388 #   error Could not determine cache line length - unknown architecture
389 # endif
390 #else
391 # define CACHELINE_ALIGNED
392 #endif  // defined(HAVE___ATTRIBUTE__)
393 
394 #if defined(HAVE___ATTRIBUTE__ALIGNED_FN)
395 #  define CACHELINE_ALIGNED_FN CACHELINE_ALIGNED
396 #else
397 #  define CACHELINE_ALIGNED_FN
398 #endif
399 
400 // Structure for discovering alignment
401 union MemoryAligner {
402   void*  p;
403   double d;
404   size_t s;
405 } CACHELINE_ALIGNED;
406 
407 #if defined(HAVE___ATTRIBUTE__) && defined(__ELF__)
408 #define ATTRIBUTE_HIDDEN __attribute__((visibility("hidden")))
409 #else
410 #define ATTRIBUTE_HIDDEN
411 #endif
412 
413 #if defined(__GNUC__)
414 #define ATTRIBUTE_ALWAYS_INLINE __attribute__((always_inline))
415 #elif defined(_MSC_VER)
416 #define ATTRIBUTE_ALWAYS_INLINE __forceinline
417 #else
418 #define ATTRIBUTE_ALWAYS_INLINE
419 #endif
420 
421 // The following enum should be used only as a constructor argument to indicate
422 // that the variable has static storage class, and that the constructor should
423 // do nothing to its state.  It indicates to the reader that it is legal to
424 // declare a static nistance of the class, provided the constructor is given
425 // the base::LINKER_INITIALIZED argument.  Normally, it is unsafe to declare a
426 // static variable that has a constructor or a destructor because invocation
427 // order is undefined.  However, IF the type can be initialized by filling with
428 // zeroes (which the loader does for static variables), AND the destructor also
429 // does nothing to the storage, then a constructor declared as
430 //       explicit MyClass(base::LinkerInitialized x) {}
431 // and invoked as
432 //       static MyClass my_variable_name(base::LINKER_INITIALIZED);
433 namespace base {
434 enum LinkerInitialized { LINKER_INITIALIZED };
435 }
436 
437 #endif  // _BASICTYPES_H_
438