2
// Copyright (C) 1999 and onwards Google, Inc.
5
// These are weird things we need to do to get this compiling on
6
// random systems (and on SWIG).
11
#include "base/definer.h"
13
#include <limits.h> // So we can set the bounds of our types
14
#include <string.h> // for memcpy()
15
#include <stdlib.h> // for free()
17
#if defined(OS_MACOSX)
18
#include <unistd.h> // for getpagesize() on mac
19
#elif defined(OS_CYGWIN)
20
#include <malloc.h> // for memalign()
23
#include "integral_types.h"
25
// Must happens before inttypes.h inclusion */
26
#if defined(OS_MACOSX)
27
/* From MacOSX's inttypes.h:
28
* "C++ implementations should define these macros only when
29
* __STDC_FORMAT_MACROS is defined before <inttypes.h> is included." */
30
#ifndef __STDC_FORMAT_MACROS
31
#define __STDC_FORMAT_MACROS
32
#endif /* __STDC_FORMAT_MACROS */
33
#endif /* OS_MACOSX */
35
/* Default for most OSes */
36
/* We use SIGPWR since that seems unlikely to be used for other reasons. */
37
#define GOOGLE_OBSCURE_SIGNAL SIGPWR
39
#if defined OS_LINUX || defined OS_CYGWIN
45
// mysql.h sets _GNU_SOURCE which sets __USE_MISC in <features.h>
46
// sys/types.h typedefs uint if __USE_MISC
47
// mysql typedefs uint if HAVE_UINT not set
48
// The following typedef is carefully considered, and should not cause
50
#if !defined(__USE_MISC)
51
#if !defined(HAVE_UINT)
53
typedef unsigned int uint;
55
#if !defined(HAVE_USHORT)
57
typedef unsigned short ushort;
59
#if !defined(HAVE_ULONG)
61
typedef unsigned long ulong;
65
#if defined(__cplusplus)
66
#include <cstddef> // For _GLIBCXX macros
69
#if !defined(HAVE_TLS) && defined(_GLIBCXX_HAVE_TLS) && defined(ARCH_K8)
73
#elif defined OS_FREEBSD
76
#include <machine/endian.h>
78
#elif defined OS_SOLARIS
81
#include <sys/isa_defs.h>
83
// Solaris doesn't define sig_t (function taking an int, returning void)
84
typedef void (*sig_t)(int);
86
// Solaris only defines strtoll, not strtoq
87
#define strtoq strtoll
88
#define strtouq strtoull
90
// It doesn't define the posix-standard(?) u_int_16
91
#include <sys/int_types.h>
92
typedef uint16_t u_int16_t;
94
#elif defined OS_MACOSX
97
#include <machine/endian.h>
98
/* Let's try and follow the Linux convention */
99
#define __BYTE_ORDER BYTE_ORDER
100
#define __LITTLE_ENDIAN LITTLE_ENDIAN
101
#define __BIG_ENDIAN BIG_ENDIAN
105
#if defined __sunos__ || defined __freebsd__
106
#ifdef _LITTLE_ENDIAN
107
#define IS_LITTLE_ENDIAN
108
#elif defined _BIG_ENDIAN
109
#define IS_BIG_ENDIAN
113
// The following guarenty declaration of the byte swap functions, and
114
// define __BYTE_ORDER for MSVC
117
#define __BYTE_ORDER __LITTLE_ENDIAN
118
#define bswap_16(x) _byteswap_ushort(x)
119
#define bswap_32(x) _byteswap_ulong(x)
120
#define bswap_64(x) _byteswap_uint64(x)
121
#elif defined(OS_MACOSX)
122
// Mac OS X / Darwin features
123
#include <libkern/OSByteOrder.h>
124
#define bswap_16(x) OSSwapInt16(x)
125
#define bswap_32(x) OSSwapInt32(x)
126
#define bswap_64(x) OSSwapInt64(x)
127
#elif defined __sunos__
128
#include <sys/byteorder.h>
129
#define bswap_16(x) BSWAP_16(x)
130
#define bswap_32(x) BSWAP_32(x)
131
#define bswap_64(x) BSWAP_64(x)
132
#elif defined __freebsd__
133
#include <sys/endian.h>
134
#define bswap_16(x) bswap16(x)
135
#define bswap_32(x) bswap32(x)
136
#define bswap_64(x) bswap64(x)
138
#include <byteswap.h>
142
// define the macros IS_LITTLE_ENDIAN or IS_BIG_ENDIAN
143
// using the above endian defintions from endian.h if
144
// endian.h was included
146
#if __BYTE_ORDER == __LITTLE_ENDIAN
147
#define IS_LITTLE_ENDIAN
150
#if __BYTE_ORDER == __BIG_ENDIAN
151
#define IS_BIG_ENDIAN
156
#if defined(__LITTLE_ENDIAN__)
157
#define IS_LITTLE_ENDIAN
158
#elif defined(__BIG_ENDIAN__)
159
#define IS_BIG_ENDIAN
162
// there is also PDP endian ...
164
#endif // __BYTE_ORDER
166
// Define the OS's path separator
167
#ifdef __cplusplus // C won't merge duplicate const variables at link time
168
// Some headers provide a macro for this (GCC's system.h), remove it so that we
170
#undef PATH_SEPARATOR
172
const char PATH_SEPARATOR = '\\';
174
const char PATH_SEPARATOR = '/';
178
// Windows has O_BINARY as a flag to open() (like "b" for fopen).
179
// Linux doesn't need make this distinction.
180
#if defined OS_LINUX && !defined O_BINARY
184
// va_copy portability definitions
186
// MSVC doesn't have va_copy yet.
187
// This is believed to work for 32-bit msvc. This may not work at all for
189
// If va_list uses the single-element-array trick, you will probably get
190
// a compiler error here.
193
inline void va_copy(va_list& a, va_list& b) {
197
// Nor does it have uid_t
202
// Mac OS X / Darwin features
204
#if defined(OS_MACOSX)
206
// For mmap, Linux defines both MAP_ANONYMOUS and MAP_ANON and says MAP_ANON is
207
// deprecated. In Darwin, MAP_ANON is all there is.
208
#if !defined MAP_ANONYMOUS
209
#define MAP_ANONYMOUS MAP_ANON
212
// Linux has this in <sys/cdefs.h>
213
#define __ptr_t void *
215
// Linux has this in <linux/errno.h>
216
#define EXFULL ENOMEM // not really that great a translation...
218
// Mach-O supports sections (albeit with small names), but doesn't have
219
// vars at the beginning and end. Instead you should call the function
220
// getsectdata("__DATA", name, &size).
221
#define HAVE_ATTRIBUTE_SECTION 1
223
// Any function with ATTRIBUTE_SECTION must not be inlined, or it will
224
// be placed into whatever section its caller is placed into.
225
#define ATTRIBUTE_SECTION(name) \
226
__attribute__ ((section ("__DATA, " #name))) __attribute__ ((noinline))
228
#define ENUM_DYLD_BOOL // so that we don't pollute the global namespace
230
#include <mach-o/getsect.h>
231
#include <mach-o/dyld.h>
233
class AssignAttributeStartEnd {
235
AssignAttributeStartEnd(const char* name, char** pstart, char** pend) {
236
// Find out what dynamic library name is defined in
237
for (int i = _dyld_image_count() - 1; i >= 0; --i) {
238
const mach_header* hdr = _dyld_get_image_header(i);
240
*pstart = getsectdatafromheader(hdr, "__DATA", name, &len);
241
if (*pstart) { // NULL if not defined in this dynamic library
242
*pstart += _dyld_get_image_vmaddr_slide(i); // correct for reloc
243
*pend = *pstart + len;
247
// If we get here, not defined in a dll at all. See if defined statically.
248
unsigned long len; // don't ask me why this type isn't uint32_t too...
249
*pstart = getsectdata("__DATA", name, &len);
250
*pend = *pstart + len;
254
// 1) DEFINE_ATTRIBUTE_SECTION_VARS: must be called once per unique
255
// name. You want to make sure this is executed before any
256
// DECLARE_ATTRIBUTE_SECTION_VARS; the easiest way is to put them
257
// in the same .cc file. Put this call at the global level.
258
// 2) INIT_ATTRIBUTE_SECTION_VARS: you can scatter calls to this in
259
// multiple places to help ensure execution before any
260
// DECLARE_ATTRIBUTE_SECTION_VARS. You must have at least one
261
// DEFINE, but you can have many INITs. Put each in its own scope.
262
// 3) DECLARE_ATTRIBUTE_SECTION_VARS: must be called before using
263
// ATTRIBUTE_SECTION_START or ATTRIBUTE_SECTION_STOP on a name.
264
// Put this call at the global level.
265
#define DECLARE_ATTRIBUTE_SECTION_VARS(name) \
266
extern char* __start_##name; \
267
extern char* __stop_##name;
269
#define INIT_ATTRIBUTE_SECTION_VARS(name) \
270
DECLARE_ATTRIBUTE_SECTION_VARS(name); \
271
static const AssignAttributeStartEnd __assign_##name( \
272
#name, &__start_##name, &__stop_##name)
274
#define DEFINE_ATTRIBUTE_SECTION_VARS(name) \
275
char* __start_##name, *__stop_##name; \
276
INIT_ATTRIBUTE_SECTION_VARS(name)
278
// Darwin doesn't have strnlen. No comment.
279
inline size_t strnlen(const char *s, size_t maxlen) {
280
const char* end = (const char *)memchr(s, '\0', maxlen);
286
using namespace std; // just like VC++, we need a using here
288
// Doesn't exist on OSX; used in google.cc for send() to mean "no flags".
289
#define MSG_NOSIGNAL 0
291
// No SIGPWR on MacOSX. SIGINFO seems suitably obscure.
292
#undef GOOGLE_OBSCURE_SIGNAL
293
#define GOOGLE_OBSCURE_SIGNAL SIGINFO
295
#elif defined(OS_CYGWIN) // Cygwin-specific behavior.
297
#if defined(__CYGWIN32__)
298
#define __WORDSIZE 32
300
// It's probably possible to support 64-bit, but the #defines will need checked.
301
#error "Cygwin is currently only 32-bit."
304
// No signalling on Windows.
305
#undef GOOGLE_OBSCURE_SIGNAL
306
#define GOOGLE_OBSCURE_SIGNAL 0
313
inline int sigaltstack(stack_t* ss, stack_t* oss) { return 0; }
315
#define PTHREAD_STACK_MIN 0 // Not provided by cygwin
317
// Scans memory for a character.
318
// memrchr is used in a few places, but it's linux-specific.
319
inline void* memrchr(const void* bytes, int find_char, size_t len) {
320
const unsigned char* cursor =
321
reinterpret_cast<const unsigned char*>(bytes) + len - 1;
322
unsigned char actual_char = find_char;
323
for (; cursor >= bytes; --cursor) {
324
if (*cursor == actual_char) {
325
return const_cast<void*>(reinterpret_cast<const void*>(cursor));
333
// Klocwork static analysis tool's C/C++ complier kwcc
334
#if defined(__KLOCWORK__)
335
#define STATIC_ANALYSIS
336
#endif // __KLOCWORK__
338
// GCC-specific features
340
#if (defined(COMPILER_GCC3) || defined(COMPILER_ICC) || defined(OS_MACOSX)) && !defined(SWIG)
343
// Tell the compiler to do printf format string checking if the
344
// compiler supports it; see the 'format' attribute in
345
// <http://gcc.gnu.org/onlinedocs/gcc-4.3.0/gcc/Function-Attributes.html>.
347
// N.B.: As the GCC manual states, "[s]ince non-static C++ methods
348
// have an implicit 'this' argument, the arguments of such methods
349
// should be counted from two, not one."
351
#define PRINTF_ATTRIBUTE(string_index, first_to_check) \
352
__attribute__((__format__ (__printf__, string_index, first_to_check)))
353
#define SCANF_ATTRIBUTE(string_index, first_to_check) \
354
__attribute__((__format__ (__scanf__, string_index, first_to_check)))
357
// Prevent the compiler from padding a structure to natural alignment
359
#define PACKED __attribute__ ((packed))
361
// Cache line alignment
362
#if defined(__i386__) || defined(__x86_64__)
363
#define CACHELINE_SIZE 64
364
#define CACHELINE_ALIGNED __attribute__((aligned(CACHELINE_SIZE)))
365
#elif defined(__ARM_ARCH_5T__)
366
#define CACHELINE_SIZE 32
367
#define CACHELINE_ALIGNED
369
#define CACHELINE_ALIGNED
373
// Prevent the compiler from complaining about or optimizing away variables
374
// that appear unused
375
// (careful, others e.g. third_party/libxml/xmlversion.h also define this)
376
#undef ATTRIBUTE_UNUSED
377
#define ATTRIBUTE_UNUSED __attribute__ ((unused))
380
// For functions we want to force inline or not inline.
381
// Introduced in gcc 3.1.
382
#define ATTRIBUTE_ALWAYS_INLINE __attribute__ ((always_inline))
383
#define HAVE_ATTRIBUTE_ALWAYS_INLINE 1
384
#define ATTRIBUTE_NOINLINE __attribute__ ((noinline))
385
#define HAVE_ATTRIBUTE_NOINLINE 1
387
// For weak functions
388
#undef ATTRIBUTE_WEAK
389
#define ATTRIBUTE_WEAK __attribute__ ((weak))
390
#define HAVE_ATTRIBUTE_WEAK 1
392
// Tell the compiler to use "initial-exec" mode for a thread-local variable.
393
// See http://people.redhat.com/drepper/tls.pdf for the gory details.
394
#define ATTRIBUTE_INITIAL_EXEC __attribute__ ((tls_model ("initial-exec")))
397
// Tell the compiler that a given function never returns
399
#define ATTRIBUTE_NORETURN __attribute__((noreturn))
401
// For deprecated functions, variables, and types.
402
// gcc 3.1.1 and later provide this attribute.
403
// gcc 3.1.1 and later provide -Wdeprecated-declarations, on by default,
404
// and then -Werror converts such warning to an error
405
// gcc 4.2.1 and later provide -Wno-error=deprecated-declarations,
406
// so that use of a deprecated entity is a warning but not an error
408
// gcc 4.2.1 and gcc 4.2.2 ignore ATTRIBUTE_DEPRECATED on virtual functions.
409
// this is fixed in gcc 4.3.1 (crosstool v12). -- mec, 2008-10-21
411
// 2010-05-19(mec): Failed.
412
// Too many people started deprecations and then stopped working on them.
413
// The deprecation messages just became build noise.
414
// The two-part deletion plan:
415
// change definition of ATTRIBUTE_DEPRECATED to an empty macro
416
// then global change: ATTRIBUTE_DEPRECATED -> /* deprecated */
417
// We may introduce a new facility like this in the future,
418
// probably with a different name. See message from iant to c-style:
419
#define ATTRIBUTE_DEPRECATED
421
#ifndef HAVE_ATTRIBUTE_SECTION // may have been pre-set to 0, e.g. for Darwin
422
#define HAVE_ATTRIBUTE_SECTION 1
425
#if HAVE_ATTRIBUTE_SECTION // define section support for the case of GCC
428
// Tell the compiler/linker to put a given function into a section and define
429
// "__start_ ## name" and "__stop_ ## name" symbols to bracket the section.
430
// Sections can not span more than none compilation unit.
431
// This functionality is supported by GNU linker.
432
// Any function with ATTRIBUTE_SECTION must not be inlined, or it will
433
// be placed into whatever section its caller is placed into.
435
#ifndef ATTRIBUTE_SECTION
436
#define ATTRIBUTE_SECTION(name) \
437
__attribute__ ((section (#name))) __attribute__ ((noinline))
441
// Weak section declaration to be used as a global declaration
442
// for ATTRIBUTE_SECTION_START|STOP(name) to compile and link
443
// even without functions with ATTRIBUTE_SECTION(name).
444
// DEFINE_ATTRIBUTE_SECTION should be in the exactly one file; it's
445
// a no-op on ELF but not on Mach-O.
447
#ifndef DECLARE_ATTRIBUTE_SECTION_VARS
448
#define DECLARE_ATTRIBUTE_SECTION_VARS(name) \
449
extern char __start_##name[] ATTRIBUTE_WEAK; \
450
extern char __stop_##name[] ATTRIBUTE_WEAK
452
#ifndef DEFINE_ATTRIBUTE_SECTION_VARS
453
#define INIT_ATTRIBUTE_SECTION_VARS(name)
454
#define DEFINE_ATTRIBUTE_SECTION_VARS(name)
458
// Return void* pointers to start/end of a section of code with
459
// functions having ATTRIBUTE_SECTION(name).
460
// Returns 0 if no such functions exits.
461
// One must DECLARE_ATTRIBUTE_SECTION_VARS(name) for this to compile and link.
463
#define ATTRIBUTE_SECTION_START(name) (reinterpret_cast<void*>(__start_##name))
464
#define ATTRIBUTE_SECTION_STOP(name) (reinterpret_cast<void*>(__stop_##name))
466
#endif // HAVE_ATTRIBUTE_SECTION
469
// The legacy prod71 libc does not provide the stack alignment required for use
470
// of SSE intrinsics. In order to properly use the intrinsics you need to use
471
// a trampoline function which aligns the stack prior to calling your code,
472
// or as of crosstool v10 with gcc 4.2.0 there is an attribute which asks
473
// gcc to do this for you.
475
// It has also been discovered that crosstool up to and including v10 does not
476
// provide proper alignment for pthread_once() functions in x86-64 code either.
477
// Unfortunately gcc does not provide force_align_arg_pointer as an option in
478
// x86-64 code, so this requires us to always have a trampoline.
480
// For an example of using this see util/hash/adler32*
482
#if defined(__i386__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 2))
483
#define ATTRIBUTE_STACK_ALIGN_FOR_OLD_LIBC __attribute__((force_align_arg_pointer))
484
#define REQUIRE_STACK_ALIGN_TRAMPOLINE (0)
485
#elif defined(__i386__) || defined(__x86_64__)
486
#define REQUIRE_STACK_ALIGN_TRAMPOLINE (1)
487
#define ATTRIBUTE_STACK_ALIGN_FOR_OLD_LIBC
489
#define REQUIRE_STACK_ALIGN_TRAMPOLINE (0)
490
#define ATTRIBUTE_STACK_ALIGN_FOR_OLD_LIBC
495
// Tell the compiler to warn about unused return values for functions declared
496
// with this macro. The macro should be used on function declarations
497
// following the argument list:
499
// Sprocket* AllocateSprocket() MUST_USE_RESULT;
501
#undef MUST_USE_RESULT
502
#if (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) \
503
&& !defined(COMPILER_ICC)
504
#define MUST_USE_RESULT __attribute__ ((warn_unused_result))
506
#define MUST_USE_RESULT
510
#if (defined(COMPILER_ICC) || defined(COMPILER_GCC3) || defined(__llvm__))
511
// Defined behavior on some of the uarchs:
513
// prefetch to all levels of the hierarchy (except on p4: prefetch to L2)
514
// PREFETCH_HINT_NTA:
515
// p4: fetch to L2, but limit to 1 way (out of the 8 ways)
516
// core: skip L2, go directly to L1
517
// k8 rev E and later: skip L2, can go to either of the 2-ways in L1
519
PREFETCH_HINT_T0 = 3, // More temporal locality
520
PREFETCH_HINT_T1 = 2,
521
PREFETCH_HINT_T2 = 1, // Less temporal locality
522
PREFETCH_HINT_NTA = 0 // No temporal locality
525
// prefetch is a no-op for this target. Feel free to add more sections above.
528
extern inline void prefetch(const char *x, int hint) {
529
#if defined(COMPILER_ICC) || defined(__llvm__)
530
// In the gcc version of prefetch(), hint is only a constant _after_ inlining
531
// (assumed to have been successful). icc views things differently, and
532
// checks constant-ness _before_ inlining. This leads to compilation errors
533
// with the gcc version in icc.
535
// One way round this is to use a switch statement to explicitly match
536
// prefetch hint enumerations, and invoke __builtin_prefetch for each valid
537
// value. icc's optimization removes the switch and unused case statements
538
// after inlining, so that this boils down in the end to the same as for gcc;
539
// that is, a single inlined prefetchX instruction. Demonstrate by compiling
540
// with icc options -xK -O2 and viewing assembly language output.
542
// Note that this version of prefetch() cannot verify constant-ness of hint.
543
// If client code calls prefetch() with a variable value for hint, it will
544
// receive the full expansion of the switch below, perhaps also not inlined.
545
// This should however not be a problem in the general case of well behaved
546
// caller code that uses the supplied prefetch hint enumerations.
548
case PREFETCH_HINT_T0:
549
__builtin_prefetch(x, 0, PREFETCH_HINT_T0);
551
case PREFETCH_HINT_T1:
552
__builtin_prefetch(x, 0, PREFETCH_HINT_T1);
554
case PREFETCH_HINT_T2:
555
__builtin_prefetch(x, 0, PREFETCH_HINT_T2);
557
case PREFETCH_HINT_NTA:
558
__builtin_prefetch(x, 0, PREFETCH_HINT_NTA);
561
__builtin_prefetch(x);
564
#elif defined(COMPILER_GCC3)
565
#if !defined(ARCH_PIII) || defined(__SSE__)
566
if (__builtin_constant_p(hint)) {
567
__builtin_prefetch(x, 0, hint);
569
// Defaults to PREFETCH_HINT_T0
570
__builtin_prefetch(x);
573
// We want a __builtin_prefetch, but we build with the default -march=i386
574
// where __builtin_prefetch quietly turns into nothing.
575
// Once we crank up to -march=pentium3 or higher the __SSE__
576
// clause above will kick in with the builtin.
578
if (hint == PREFETCH_HINT_NTA)
579
__asm__ __volatile__("prefetchnta (%0)" : : "r"(x));
582
// You get no effect. Feel free to add more sections above.
587
// prefetch intrinsic (bring data to L1 without polluting L2 cache)
588
extern inline void prefetch(const char *x) {
589
return prefetch(x, 0);
591
#endif // ifdef __cplusplus
594
// GCC can be told that a certain branch is not likely to be taken (for
595
// instance, a CHECK failure), and use that information in static analysis.
596
// Giving it this information can help it optimize for the common case in
597
// the absence of better information (ie. -fprofile-arcs).
599
#if defined(COMPILER_GCC3)
600
#define PREDICT_FALSE(x) (__builtin_expect(x, 0))
601
#define PREDICT_TRUE(x) (__builtin_expect(!!(x), 1))
603
#define PREDICT_FALSE(x) x
604
#define PREDICT_TRUE(x) x
607
#define FTELLO ftello
608
#define FSEEKO fseeko
610
#if !defined(__cplusplus) && !defined(OS_MACOSX) && !defined(OS_CYGWIN)
611
// stdlib.h only declares this in C++, not in C, so we declare it here.
612
// Also make sure to avoid declaring it on platforms which don't support it.
613
extern int posix_memalign(void **memptr, size_t alignment, size_t size);
616
inline void *aligned_malloc(size_t size, int minimum_alignment) {
617
#if defined(OS_MACOSX)
618
// mac lacks memalign(), posix_memalign(), however, according to
619
// http://stackoverflow.com/questions/196329/osx-lacks-memalign
620
// mac allocs are already 16-byte aligned.
621
if (minimum_alignment <= 16)
623
// next, try to return page-aligned memory. perhaps overkill
624
if (minimum_alignment <= getpagesize())
628
#elif defined(OS_CYGWIN)
629
return memalign(minimum_alignment, size);
630
#else // !OS_MACOSX && !OS_CYGWIN
632
if (posix_memalign(&ptr, minimum_alignment, size) != 0)
639
inline void aligned_free(void *aligned_memory) {
640
free(aligned_memory);
645
#define PRINTF_ATTRIBUTE(string_index, first_to_check)
646
#define SCANF_ATTRIBUTE(string_index, first_to_check)
648
#define CACHELINE_ALIGNED
649
#define ATTRIBUTE_UNUSED
650
#define ATTRIBUTE_ALWAYS_INLINE
651
#define ATTRIBUTE_NOINLINE
652
#define ATTRIBUTE_WEAK
653
#define HAVE_ATTRIBUTE_WEAK 0
654
#define ATTRIBUTE_INITIAL_EXEC
655
#define ATTRIBUTE_NORETURN
656
#define ATTRIBUTE_DEPRECATED
657
#define HAVE_ATTRIBUTE_SECTION 0
658
#define ATTRIBUTE_STACK_ALIGN_FOR_OLD_LIBC
659
#define REQUIRE_STACK_ALIGN_TRAMPOLINE (0)
660
#define MUST_USE_RESULT
661
extern inline void prefetch(const char *x) {}
662
#define PREDICT_FALSE(x) x
663
#define PREDICT_TRUE(x) x
665
// These should be redefined appropriately if better alternatives to
666
// ftell/fseek exist in the compiler
672
#if !HAVE_ATTRIBUTE_SECTION // provide dummy definitions
674
#define ATTRIBUTE_SECTION(name)
675
#define INIT_ATTRIBUTE_SECTION_VARS(name)
676
#define DEFINE_ATTRIBUTE_SECTION_VARS(name)
677
#define DECLARE_ATTRIBUTE_SECTION_VARS(name)
678
#define ATTRIBUTE_SECTION_START(name) (reinterpret_cast<void*>(0))
679
#define ATTRIBUTE_SECTION_STOP(name) (reinterpret_cast<void*>(0))
681
#endif // !HAVE_ATTRIBUTE_SECTION
683
#if defined __sunos__ || defined _WIN32
684
inline double drem(double x, double y) {
687
// If quot is slightly less than 0.5, we round down explicitly. We have to
688
// do this explicitly because (0.5 + quot) when quot=(0.5-epsilon) gives you 1
689
// and that's rounding the wrong way. Oh, floating point!
690
if (quot < 0.5 && quot > -0.5) {
692
} else if (quot > 0) {
697
double ret = x - iquot * y;
702
// HK's fun windows fixer-upper defines go here! Woo.
704
#define strtoll _strtoi64
705
#define strtoull _strtoui64
706
#define safe_vsnprintf _vsnprintf
707
#define snprintf _snprintf
709
inline void va_copy(va_list& a, va_list& b) {
714
#define snprintf _snprintf
716
inline double sqrt(int x) { return sqrt((double)x); }
717
inline int isinf(double x) {
718
const int float_point_class =_fpclass(x);
719
if (float_point_class == _FPCLASS_PINF) return 1;
720
if (float_point_class == _FPCLASS_NINF) return -1;
725
#ifdef COMPILER_MSVC /* if Visual C++ */
727
// This compiler flag can be easily overlooked on MSVC.
728
// _CHAR_UNSIGNED gets set with the /J flag.
729
#ifndef _CHAR_UNSIGNED
730
#error chars must be unsigned! Use the /J flag on the compiler command line.
733
// MSVC is a little hyper-active in it's warnings
734
// Signed vs. unsigned comparison is ok.
735
#pragma warning(disable : 4018 )
736
// We know casting from a long to a char may lose data
737
#pragma warning(disable : 4244 )
738
// Don't need performance warnings about converting ints to bools
739
#pragma warning(disable : 4800 )
740
// Integral constant overflow is apparently ok too
744
#pragma warning(disable : 4307 )
745
// It's ok to use this* in constructor
749
// C() : cont_(this) { ...
750
#pragma warning(disable : 4355 )
751
// Truncating from double to float is ok
752
#pragma warning(disable : 4305 )
754
#include <winsock2.h>
759
#include <float.h> // for nextafter functionality on windows
760
#include <math.h> // for HUGE_VAL
763
#define HUGE_VALF (static_cast<float>(HUGE_VAL))
768
// VC++ doesn't understand "uint"
771
typedef unsigned int uint;
774
#define strtoq _strtoi64
775
#define strtouq _strtoui64
776
#define strtoll _strtoi64
777
#define strtoull _strtoui64
778
#define atoll _atoi64
781
// VC++ 6 and before ship without an ostream << operator for 64-bit ints
782
#if (_MSC_VER <= 1200)
786
inline ostream& operator<< (ostream& os, const unsigned __int64& num ) {
787
// Fake operator; doesn't actually do anything.
788
LOG(FATAL) << "64-bit ostream operator << not supported in VC++ 6";
793
// You say tomato, I say atotom
794
#define PATH_MAX MAX_PATH
796
// You say tomato, I say _tomato
797
#define vsnprintf _vsnprintf
798
#define snprintf _snprintf
799
#define strcasecmp _stricmp
800
#define strncasecmp _strnicmp
802
#define nextafter _nextafter
805
#define hypotf _hypotf
807
#define strdup _strdup
808
#define tempnam _tempnam
810
#define getcwd _getcwd
811
#define putenv _putenv
814
// You say tomato, I say toma
815
#define random() rand()
816
#define srandom(x) srand(x)
818
// You say juxtapose, I say transpose
819
#define bcopy(s, d, n) memcpy(d, s, n)
821
inline void *aligned_malloc(size_t size, int minimum_alignment) {
822
return _aligned_malloc(size, minimum_alignment);
825
inline void aligned_free(void *aligned_memory) {
826
_aligned_free(aligned_memory);
829
// ----- BEGIN VC++ STUBS & FAKE DEFINITIONS ---------------------------------
831
// See http://en.wikipedia.org/wiki/IEEE_754 for details of
832
// floating point format.
835
FP_NAN, // is "Not a Number"
836
FP_INFINITE, // is either plus or minus infinity.
838
FP_SUBNORMAL, // is too small to be represented in normalized format.
839
FP_NORMAL // if nothing of the above is correct that it must be a
840
// normal floating-point number.
843
inline int fpclassify_double(double x) {
844
const int float_point_class =_fpclass(x);
846
switch (float_point_class) {
847
case _FPCLASS_SNAN: // Signaling NaN
848
case _FPCLASS_QNAN: // Quiet NaN
851
case _FPCLASS_NZ: // Negative zero ( -0)
852
case _FPCLASS_PZ: // Positive 0 (+0)
855
case _FPCLASS_NINF: // Negative infinity ( -INF)
856
case _FPCLASS_PINF: // Positive infinity (+INF)
857
c99_class = FP_INFINITE;
859
case _FPCLASS_ND: // Negative denormalized
860
case _FPCLASS_PD: // Positive denormalized
861
c99_class = FP_SUBNORMAL;
863
case _FPCLASS_NN: // Negative normalized non-zero
864
case _FPCLASS_PN: // Positive normalized non-zero
865
c99_class = FP_NORMAL;
868
c99_class = FP_NAN; // Should never happen
874
// This function handle the special subnormal case for float; it will
875
// become a normal number while casting to double.
876
// bit_cast is avoided to simplify dependency and to create a code that is
877
// easy to deploy in C code
878
inline int fpclassify_float(float x) {
879
uint32 bitwise_representation;
880
memcpy(&bitwise_representation, &x, 4);
881
if ((bitwise_representation & 0x7f800000) == 0 &&
882
(bitwise_representation & 0x007fffff) != 0)
884
return fpclassify_double(x);
887
// This define takes care of the denormalized float; the casting to
888
// double make it a normal number
889
#define fpclassify(x) ((sizeof(x) == sizeof(float)) ? fpclassify_float(x) : fpclassify_double(x))
893
inline int isinf(double x) {
894
const int float_point_class =_fpclass(x);
895
if (float_point_class == _FPCLASS_PINF) return 1;
896
if (float_point_class == _FPCLASS_NINF) return -1;
900
// #include "conflict-signal.h"
901
typedef void (*sig_t)(int);
903
// These actually belong in errno.h but there's a name confilict in errno
904
// on WinNT. They (and a ton more) are also found in Winsock2.h, but
905
// if'd out under NT. We need this subset at minimum.
906
#define EXFULL ENOMEM // not really that great a translation...
907
//#define EWOULDBLOCK WSAEWOULDBLOCK
908
//#ifndef PTHREADS_REDHAT_WIN32
909
//#define ETIMEDOUT WSAETIMEDOUT
911
//#define ENOTSOCK WSAENOTSOCK
912
//#define EINPROGRESS WSAEINPROGRESS
913
//#define ECONNRESET WSAECONNRESET
918
using std::make_pair;
924
typedef vector<pair<const char*, const char*> > KeyValVec;
927
// Really from <string.h>
930
inline void bzero(void *s, int n) {
935
#define __ptr_t void *
937
// Defined all over the place.
941
typedef unsigned int mode_t;
943
// u_int16_t, int16_t don't exist in MSVC
944
typedef unsigned short u_int16_t;
945
typedef short int16_t;
947
// ----- END VC++ STUBS & FAKE DEFINITIONS ----------------------------------
949
#endif // COMPILER_MSVC
951
#ifdef STL_MSVC // not always the same as COMPILER_MSVC
952
#include "base/port_hash.h"
954
struct PortableHashBase { };
957
// The SWIGged version of an abstract class must be concrete if any methods
958
// return objects of the abstract type.
960
// This location is deprecated, the new preferred location is in base/macros.h.
966
#if defined(OS_WINDOWS) || defined(OS_MACOSX)
967
// gethostbyname() *is* thread-safe for Windows native threads. It is also
968
// safe on Mac OS X, where it uses thread-local storage, even though the
969
// manpages claim otherwise. For details, see
970
// http://lists.apple.com/archives/Darwin-dev/2006/May/msg00008.html
972
// gethostbyname() is not thread-safe. So disallow its use. People
973
// should either use the HostLookup::Lookup*() methods, or gethostbyname_r()
974
#define gethostbyname gethostbyname_is_not_thread_safe_DO_NOT_USE
977
// create macros in which the programmer should enclose all specializations
978
// for hash_maps and hash_sets. This is necessary since these classes are not
979
// STL standardized. Depending on the STL implementation they are in different
980
// namespaces. Right now the right namespace is passed by the Makefile
981
// Examples: gcc3: -DHASH_NAMESPACE=__gnu_cxx
982
// icc: -DHASH_NAMESPACE=std
985
#ifndef HASH_NAMESPACE
986
# define HASH_NAMESPACE_DECLARATION_START
987
# define HASH_NAMESPACE_DECLARATION_END
989
# define HASH_NAMESPACE_DECLARATION_START namespace HASH_NAMESPACE {
990
# define HASH_NAMESPACE_DECLARATION_END }
993
// Our STL-like classes use __STD.
994
#if defined(COMPILER_GCC3) || defined(COMPILER_ICC) || defined(OS_MACOSX) || defined(COMPILER_MSVC)
998
#if defined COMPILER_GCC3 || defined COMPILER_ICC
999
#define STREAM_SET(s, bit) (s).setstate(ios_base::bit)
1000
#define STREAM_SETF(s, flag) (s).setf(ios_base::flag)
1002
#define STREAM_SET(s, bit) (s).set(ios::bit)
1003
#define STREAM_SETF(s, flag) (s).setf(ios::flag)
1006
// Portable handling of unaligned loads and stores
1008
#if defined(ARCH_PIII) || defined(ARCH_ATHLON) || defined(ARCH_K8) || defined(_ARCH_PPC)
1010
// x86 and x86-64 can perform unaligned loads/stores directly;
1011
// modern PowerPC hardware can also do unaligned integer loads and stores;
1012
// but note: the FPU still sends unaligned loads and stores to a trap handler!
1014
#define UNALIGNED_LOAD16(_p) (*reinterpret_cast<const uint16 *>(_p))
1015
#define UNALIGNED_LOAD32(_p) (*reinterpret_cast<const uint32 *>(_p))
1016
#define UNALIGNED_LOAD64(_p) (*reinterpret_cast<const uint64 *>(_p))
1018
#define UNALIGNED_STORE16(_p, _val) (*reinterpret_cast<uint16 *>(_p) = (_val))
1019
#define UNALIGNED_STORE32(_p, _val) (*reinterpret_cast<uint32 *>(_p) = (_val))
1020
#define UNALIGNED_STORE64(_p, _val) (*reinterpret_cast<uint64 *>(_p) = (_val))
1024
#define NEED_ALIGNED_LOADS
1026
// These functions are provided for architectures that don't support
1027
// unaligned loads and stores.
1029
inline uint16 UNALIGNED_LOAD16(const void *p) {
1031
memcpy(&t, p, sizeof t);
1035
inline uint32 UNALIGNED_LOAD32(const void *p) {
1037
memcpy(&t, p, sizeof t);
1041
inline uint64 UNALIGNED_LOAD64(const void *p) {
1043
memcpy(&t, p, sizeof t);
1047
inline void UNALIGNED_STORE16(void *p, uint16 v) {
1048
memcpy(p, &v, sizeof v);
1051
inline void UNALIGNED_STORE32(void *p, uint32 v) {
1052
memcpy(p, &v, sizeof v);
1055
inline void UNALIGNED_STORE64(void *p, uint64 v) {
1056
memcpy(p, &v, sizeof v);
1062
#define UNALIGNED_LOADW(_p) UNALIGNED_LOAD64(_p)
1063
#define UNALIGNED_STOREW(_p, _val) UNALIGNED_STORE64(_p, _val)
1065
#define UNALIGNED_LOADW(_p) UNALIGNED_LOAD32(_p)
1066
#define UNALIGNED_STOREW(_p, _val) UNALIGNED_STORE32(_p, _val)
1069
// printf macros for size_t, in the style of inttypes.h
1071
#define __PRIS_PREFIX "z"
1073
#define __PRIS_PREFIX
1076
// Use these macros after a % in a printf format string
1077
// to get correct 32/64 bit behavior, like this:
1078
// size_t size = records.size();
1079
// printf("%"PRIuS"\n", size);
1081
#define PRIdS __PRIS_PREFIX "d"
1082
#define PRIxS __PRIS_PREFIX "x"
1083
#define PRIuS __PRIS_PREFIX "u"
1084
#define PRIXS __PRIS_PREFIX "X"
1085
#define PRIoS __PRIS_PREFIX "o"
1087
#define GPRIuPTHREAD "lu"
1088
#define GPRIxPTHREAD "lx"
1090
#define PRINTABLE_PTHREAD(pthreadt) reinterpret_cast<uintptr_t>(pthreadt)
1092
#define PRINTABLE_PTHREAD(pthreadt) pthreadt
1095
#define SIZEOF_MEMBER(t, f) sizeof(((t*) 4096)->f)
1097
#define OFFSETOF_MEMBER(t, f) \
1098
(reinterpret_cast<char*>( \
1099
&reinterpret_cast<t*>(16)->f) - \
1100
reinterpret_cast<char*>(16))
1102
#ifdef PTHREADS_REDHAT_WIN32
1106
#include <pthread.h>
1107
// pthread_t is not a simple integer or pointer on Win32
1108
std::ostream& operator << (std::ostream& out, const pthread_t& thread_id);
1111
#endif // BASE_PORT_H_