1 /*-------------------------------------------------------------------------
4 * Fundamental C definitions. This is included by every .c file in
5 * PostgreSQL (via either postgres.h or postgres_fe.h, as appropriate).
7 * Note that the definitions here are not intended to be exposed to clients
8 * of the frontend interface libraries --- so we don't worry much about
9 * polluting the namespace with lots of stuff...
12 * Portions Copyright (c) 1996-2017, PostgreSQL Global Development Group
13 * Portions Copyright (c) 1994, Regents of the University of California
17 *-------------------------------------------------------------------------
20 *----------------------------------------------------------------
23 * When adding stuff to this file, please try to put stuff
24 * into the relevant section, or add new sections as appropriate.
27 * ------- ------------------------------------------------
28 * 0) pg_config.h and standard system headers
29 * 1) hacks to cope with non-ANSI C compilers
30 * 2) bool, true, false, TRUE, FALSE, NULL
31 * 3) standard system types
32 * 4) IsValid macros for system types
33 * 5) offsetof, lengthof, endof, alignment
35 * 7) widely useful macros
37 * 9) system-specific hacks
39 * NOTE: since this file is included by both frontend and backend modules, it's
40 * almost certainly wrong to put an "extern" declaration here. typedefs and
41 * macros are the kind of thing that might go here.
43 *----------------------------------------------------------------
48 #include "postgres_ext.h"
50 /* Must undef pg_config_ext.h symbols before including pg_config.h */
53 #include "pg_config.h"
54 #include "pg_config_manual.h" /* must be after pg_config.h */
57 * We always rely on the WIN32 macro being set by our build system,
58 * but _WIN32 is the compiler pre-defined macro. So make sure we define
59 * WIN32 whenever _WIN32 is set, to facilitate standalone building.
61 #if defined(_WIN32) && !defined(WIN32)
65 #if !defined(WIN32) && !defined(__CYGWIN__) /* win32 includes further down */
66 #include "pg_config_os.h" /* must be before any system header files */
69 #if _MSC_VER >= 1400 || defined(HAVE_CRTDEFS_H)
70 #define errcode __msvc_errcode
76 * We have to include stdlib.h here because it defines many of these macros
77 * on some platforms, and we only want our definitions used if stdlib.h doesn't
78 * have its own. The same goes for stddef and stdarg if present.
92 #include <sys/types.h>
95 #if defined(WIN32) || defined(__CYGWIN__)
96 #include <fcntl.h> /* ensure O_BINARY is available */
99 #if defined(WIN32) || defined(__CYGWIN__)
100 /* We have to redefine some system functions after they are included above. */
101 #include "pg_config_os.h"
105 * Force disable inlining if PG_FORCE_DISABLE_INLINE is defined. This is used
106 * to work around compiler bugs and might also be useful for investigatory
107 * purposes by defining the symbol in the platform's header..
109 * This is done early (in slightly the wrong section) as functionality later
110 * in this file might want to rely on inline functions.
112 #ifdef PG_FORCE_DISABLE_INLINE
117 /* Must be before gettext() games below */
120 #define _(x) gettext(x)
125 #define gettext(x) (x)
126 #define dgettext(d,x) (x)
127 #define ngettext(s,p,n) ((n) == 1 ? (s) : (p))
128 #define dngettext(d,s,p,n) ((n) == 1 ? (s) : (p))
132 * Use this to mark string constants as needing translation at some later
133 * time, rather than immediately. This is useful for cases where you need
134 * access to the original string and translated string, and for cases where
135 * immediate translation is not possible, like when initializing global
137 * http://www.gnu.org/software/autoconf/manual/gettext/Special-cases.html
139 #define gettext_noop(x) (x)
142 /* ----------------------------------------------------------------
143 * Section 1: hacks to cope with non-ANSI C compilers
145 * type prefixes (const, signed, volatile, inline) are handled in pg_config.h.
146 * ----------------------------------------------------------------
151 * Convert the argument to a string, using the C preprocessor.
153 * Concatenate two arguments together, using the C preprocessor.
155 * Note: There used to be support here for pre-ANSI C compilers that didn't
156 * support # and ##. Nowadays, these macros are just for clarity and/or
157 * backward compatibility with existing PostgreSQL code.
159 #define CppAsString(identifier) #identifier
160 #define CppConcat(x, y) x##y
163 * dummyret is used to set return values in macros that use ?: to make
164 * assignments. gcc wants these to be void, other compilers like char
166 #ifdef __GNUC__ /* GNU cc */
167 #define dummyret void
169 #define dummyret char
172 /* Which __func__ symbol do we have, if any? */
173 #ifdef HAVE_FUNCNAME__FUNC
174 #define PG_FUNCNAME_MACRO __func__
176 #ifdef HAVE_FUNCNAME__FUNCTION
177 #define PG_FUNCNAME_MACRO __FUNCTION__
179 #define PG_FUNCNAME_MACRO NULL
183 /* ----------------------------------------------------------------
184 * Section 2: bool, true, false, TRUE, FALSE, NULL
185 * ----------------------------------------------------------------
190 * Boolean value, either true or false.
192 * XXX for C++ compilers, we assume the compiler has a compatible
193 * built-in definition of bool.
203 #define true ((bool) 1)
207 #define false ((bool) 0)
211 typedef bool *BoolPtr;
226 #define NULL ((void *) 0)
230 /* ----------------------------------------------------------------
231 * Section 3: standard system types
232 * ----------------------------------------------------------------
237 * Variable holding address of any memory resident object.
239 * XXX Pointer arithmetic is done with this, so it can't be void *
240 * under "true" ANSI compilers.
242 typedef char *Pointer;
246 * Signed integer, EXACTLY N BITS IN SIZE,
247 * used for numerical computations and the
248 * frontend/backend protocol.
251 typedef signed char int8; /* == 8 bits */
252 typedef signed short int16; /* == 16 bits */
253 typedef signed int int32; /* == 32 bits */
254 #endif /* not HAVE_INT8 */
258 * Unsigned integer, EXACTLY N BITS IN SIZE,
259 * used for numerical computations and the
260 * frontend/backend protocol.
263 typedef unsigned char uint8; /* == 8 bits */
264 typedef unsigned short uint16; /* == 16 bits */
265 typedef unsigned int uint32; /* == 32 bits */
266 #endif /* not HAVE_UINT8 */
270 * Unit of bitwise operation, AT LEAST N BITS IN SIZE.
272 typedef uint8 bits8; /* >= 8 bits */
273 typedef uint16 bits16; /* >= 16 bits */
274 typedef uint32 bits32; /* >= 32 bits */
279 #ifdef HAVE_LONG_INT_64
280 /* Plain "long int" fits, use it */
283 typedef long int int64;
286 typedef unsigned long int uint64;
288 #elif defined(HAVE_LONG_LONG_INT_64)
289 /* We have working support for "long long int", use that */
292 typedef long long int int64;
295 typedef unsigned long long int uint64;
298 /* neither HAVE_LONG_INT_64 nor HAVE_LONG_LONG_INT_64 */
299 #error must have a working 64-bit integer datatype
302 /* Decide if we need to decorate 64-bit constants */
303 #ifdef HAVE_LL_CONSTANTS
304 #define INT64CONST(x) ((int64) x##LL)
305 #define UINT64CONST(x) ((uint64) x##ULL)
307 #define INT64CONST(x) ((int64) x)
308 #define UINT64CONST(x) ((uint64) x)
311 /* snprintf format strings to use for 64-bit integers */
312 #define INT64_FORMAT "%" INT64_MODIFIER "d"
313 #define UINT64_FORMAT "%" INT64_MODIFIER "u"
316 * 128-bit signed and unsigned integers
317 * There currently is only a limited support for the type. E.g. 128bit
318 * literals and snprintf are not supported; but math is.
320 #if defined(PG_INT128_TYPE)
322 typedef PG_INT128_TYPE int128;
323 typedef unsigned PG_INT128_TYPE uint128;
327 * stdint.h limits aren't guaranteed to be present and aren't guaranteed to
328 * have compatible types with our fixed width types. So just define our own.
330 #define PG_INT8_MIN (-0x7F-1)
331 #define PG_INT8_MAX (0x7F)
332 #define PG_UINT8_MAX (0xFF)
333 #define PG_INT16_MIN (-0x7FFF-1)
334 #define PG_INT16_MAX (0x7FFF)
335 #define PG_UINT16_MAX (0xFFFF)
336 #define PG_INT32_MIN (-0x7FFFFFFF-1)
337 #define PG_INT32_MAX (0x7FFFFFFF)
338 #define PG_UINT32_MAX (0xFFFFFFFF)
339 #define PG_INT64_MIN (-INT64CONST(0x7FFFFFFFFFFFFFFF) - 1)
340 #define PG_INT64_MAX INT64CONST(0x7FFFFFFFFFFFFFFF)
341 #define PG_UINT64_MAX UINT64CONST(0xFFFFFFFFFFFFFFFF)
344 * We now always use int64 timestamps, but keep this symbol defined for the
345 * benefit of external code that might test it.
347 #define HAVE_INT64_TIMESTAMP
351 * Size of any memory resident object, as returned by sizeof.
357 * Index into any memory resident array.
360 * Indices are non negative.
362 typedef unsigned int Index;
366 * Offset into any memory resident array.
369 * This differs from an Index in that an Index is always
370 * non negative, whereas Offset may be negative.
372 typedef signed int Offset;
375 * Common Postgres datatype names (as used in the catalogs)
377 typedef float float4;
378 typedef double float8;
381 * Oid, RegProcedure, TransactionId, SubTransactionId, MultiXactId,
385 /* typedef Oid is in postgres_ext.h */
388 * regproc is the type name used in the include/catalog headers, but
389 * RegProcedure is the preferred name in C code.
392 typedef regproc RegProcedure;
394 typedef uint32 TransactionId;
396 typedef uint32 LocalTransactionId;
398 typedef uint32 SubTransactionId;
400 #define InvalidSubTransactionId ((SubTransactionId) 0)
401 #define TopSubTransactionId ((SubTransactionId) 1)
403 /* MultiXactId must be equivalent to TransactionId, to fit in t_xmax */
404 typedef TransactionId MultiXactId;
406 typedef uint32 MultiXactOffset;
408 typedef uint32 CommandId;
410 #define FirstCommandId ((CommandId) 0)
411 #define InvalidCommandId (~(CommandId)0)
414 * Array indexing support
423 * Variable-length datatypes all share the 'struct varlena' header.
425 * NOTE: for TOASTable types, this is an oversimplification, since the value
426 * may be compressed or moved out-of-line. However datatype-specific routines
427 * are mostly content to deal with de-TOASTed values only, and of course
428 * client-side routines should never see a TOASTed value. But even in a
429 * de-TOASTed value, beware of touching vl_len_ directly, as its representation
430 * is no longer convenient. It's recommended that code always use the VARDATA,
431 * VARSIZE, and SET_VARSIZE macros instead of relying on direct mentions of
432 * the struct fields. See postgres.h for details of the TOASTed form.
437 char vl_len_[4]; /* Do not touch this field directly! */
438 char vl_dat[FLEXIBLE_ARRAY_MEMBER]; /* Data content is here */
441 #define VARHDRSZ ((int32) sizeof(int32))
444 * These widely-used datatypes are just a varlena header and the data bytes.
445 * There is no terminating null or anything like that --- the data length is
446 * always VARSIZE(ptr) - VARHDRSZ.
448 typedef struct varlena bytea;
449 typedef struct varlena text;
450 typedef struct varlena BpChar; /* blank-padded char, ie SQL char(n) */
451 typedef struct varlena VarChar; /* var-length char, ie SQL varchar(n) */
454 * Specialized array types. These are physically laid out just the same
455 * as regular arrays (so that the regular array subscripting code works
456 * with them). They exist as distinct types mostly for historical reasons:
457 * they have nonstandard I/O behavior which we don't want to change for fear
458 * of breaking applications that look at the system catalogs. There is also
459 * an implementation issue for oidvector: it's part of the primary key for
460 * pg_proc, and we can't use the normal btree array support routines for that
461 * without circularity.
465 int32 vl_len_; /* these fields must match ArrayType! */
466 int ndim; /* always 1 for int2vector */
467 int32 dataoffset; /* always 0 for int2vector */
471 int16 values[FLEXIBLE_ARRAY_MEMBER];
476 int32 vl_len_; /* these fields must match ArrayType! */
477 int ndim; /* always 1 for oidvector */
478 int32 dataoffset; /* always 0 for oidvector */
482 Oid values[FLEXIBLE_ARRAY_MEMBER];
486 * Representation of a Name: effectively just a C string, but null-padded to
487 * exactly NAMEDATALEN bytes. The use of a struct is historical.
489 typedef struct nameData
491 char data[NAMEDATALEN];
493 typedef NameData *Name;
495 #define NameStr(name) ((name).data)
498 * Support macros for escaping strings. escape_backslash should be TRUE
499 * if generating a non-standard-conforming string. Prefixing a string
500 * with ESCAPE_STRING_SYNTAX guarantees it is non-standard-conforming.
501 * Beware of multiple evaluation of the "ch" argument!
503 #define SQL_STR_DOUBLE(ch, escape_backslash) \
504 ((ch) == '\'' || ((ch) == '\\' && (escape_backslash)))
506 #define ESCAPE_STRING_SYNTAX 'E'
508 /* ----------------------------------------------------------------
509 * Section 4: IsValid macros for system types
510 * ----------------------------------------------------------------
514 * True iff bool is valid.
516 #define BoolIsValid(boolean) ((boolean) == false || (boolean) == true)
520 * True iff pointer is valid.
522 #define PointerIsValid(pointer) ((const void*)(pointer) != NULL)
526 * True iff pointer is properly aligned to point to the given type.
528 #define PointerIsAligned(pointer, type) \
529 (((uintptr_t)(pointer) % (sizeof (type))) == 0)
531 #define OffsetToPointer(base, offset) \
532 ((void *)((char *) base + offset))
534 #define OidIsValid(objectId) ((bool) ((objectId) != InvalidOid))
536 #define RegProcedureIsValid(p) OidIsValid(p)
539 /* ----------------------------------------------------------------
540 * Section 5: offsetof, lengthof, endof, alignment
541 * ----------------------------------------------------------------
545 * Offset of a structure/union field within that structure/union.
547 * XXX This is supposed to be part of stddef.h, but isn't on
548 * some systems (like SunOS 4).
551 #define offsetof(type, field) ((long) &((type *)0)->field)
552 #endif /* offsetof */
556 * Number of elements in an array.
558 #define lengthof(array) (sizeof (array) / sizeof ((array)[0]))
562 * Address of the element one past the last in an array.
564 #define endof(array) (&(array)[lengthof(array)])
567 * Alignment macros: align a length or address appropriately for a given type.
568 * The fooALIGN() macros round up to a multiple of the required alignment,
569 * while the fooALIGN_DOWN() macros round down. The latter are more useful
570 * for problems like "how many X-sized structures will fit in a page?".
572 * NOTE: TYPEALIGN[_DOWN] will not work if ALIGNVAL is not a power of 2.
573 * That case seems extremely unlikely to be needed in practice, however.
577 #define TYPEALIGN(ALIGNVAL,LEN) \
578 (((uintptr_t) (LEN) + ((ALIGNVAL) - 1)) & ~((uintptr_t) ((ALIGNVAL) - 1)))
580 #define SHORTALIGN(LEN) TYPEALIGN(ALIGNOF_SHORT, (LEN))
581 #define INTALIGN(LEN) TYPEALIGN(ALIGNOF_INT, (LEN))
582 #define LONGALIGN(LEN) TYPEALIGN(ALIGNOF_LONG, (LEN))
583 #define DOUBLEALIGN(LEN) TYPEALIGN(ALIGNOF_DOUBLE, (LEN))
584 #define MAXALIGN(LEN) TYPEALIGN(MAXIMUM_ALIGNOF, (LEN))
585 /* MAXALIGN covers only built-in types, not buffers */
586 #define BUFFERALIGN(LEN) TYPEALIGN(ALIGNOF_BUFFER, (LEN))
587 #define CACHELINEALIGN(LEN) TYPEALIGN(PG_CACHE_LINE_SIZE, (LEN))
589 #define TYPEALIGN_DOWN(ALIGNVAL,LEN) \
590 (((uintptr_t) (LEN)) & ~((uintptr_t) ((ALIGNVAL) - 1)))
592 #define SHORTALIGN_DOWN(LEN) TYPEALIGN_DOWN(ALIGNOF_SHORT, (LEN))
593 #define INTALIGN_DOWN(LEN) TYPEALIGN_DOWN(ALIGNOF_INT, (LEN))
594 #define LONGALIGN_DOWN(LEN) TYPEALIGN_DOWN(ALIGNOF_LONG, (LEN))
595 #define DOUBLEALIGN_DOWN(LEN) TYPEALIGN_DOWN(ALIGNOF_DOUBLE, (LEN))
596 #define MAXALIGN_DOWN(LEN) TYPEALIGN_DOWN(MAXIMUM_ALIGNOF, (LEN))
599 * The above macros will not work with types wider than uintptr_t, like with
600 * uint64 on 32-bit platforms. That's not problem for the usual use where a
601 * pointer or a length is aligned, but for the odd case that you need to
602 * align something (potentially) wider, use TYPEALIGN64.
604 #define TYPEALIGN64(ALIGNVAL,LEN) \
605 (((uint64) (LEN) + ((ALIGNVAL) - 1)) & ~((uint64) ((ALIGNVAL) - 1)))
607 /* we don't currently need wider versions of the other ALIGN macros */
608 #define MAXALIGN64(LEN) TYPEALIGN64(MAXIMUM_ALIGNOF, (LEN))
613 * GCC: https://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
614 * GCC: https://gcc.gnu.org/onlinedocs/gcc/Type-Attributes.html
615 * Sunpro: https://docs.oracle.com/cd/E18659_01/html/821-1384/gjzke.html
616 * XLC: http://www-01.ibm.com/support/knowledgecenter/SSGH2K_11.1.0/com.ibm.xlc111.aix.doc/language_ref/function_attributes.html
617 * XLC: http://www-01.ibm.com/support/knowledgecenter/SSGH2K_11.1.0/com.ibm.xlc111.aix.doc/language_ref/type_attrib.html
621 /* only GCC supports the unused attribute */
623 #define pg_attribute_unused() __attribute__((unused))
625 #define pg_attribute_unused()
628 /* GCC and XLC support format attributes */
629 #if defined(__GNUC__) || defined(__IBMC__)
630 #define pg_attribute_format_arg(a) __attribute__((format_arg(a)))
631 #define pg_attribute_printf(f,a) __attribute__((format(PG_PRINTF_ATTRIBUTE, f, a)))
633 #define pg_attribute_format_arg(a)
634 #define pg_attribute_printf(f,a)
637 /* GCC, Sunpro and XLC support aligned, packed and noreturn */
638 #if defined(__GNUC__) || defined(__SUNPRO_C) || defined(__IBMC__)
639 #define pg_attribute_aligned(a) __attribute__((aligned(a)))
640 #define pg_attribute_noreturn() __attribute__((noreturn))
641 #define pg_attribute_packed() __attribute__((packed))
642 #define HAVE_PG_ATTRIBUTE_NORETURN 1
645 * NB: aligned and packed are not given default definitions because they
646 * affect code functionality; they *must* be implemented by the compiler
647 * if they are to be used.
649 #define pg_attribute_noreturn()
652 /* ----------------------------------------------------------------
653 * Section 6: assertions
654 * ----------------------------------------------------------------
658 * USE_ASSERT_CHECKING, if defined, turns on all the assertions.
661 * It should _NOT_ be defined in releases or in benchmark copies
665 * Assert() can be used in both frontend and backend code. In frontend code it
666 * just calls the standard assert, if it's available. If use of assertions is
667 * not configured, it does nothing.
669 #ifndef USE_ASSERT_CHECKING
671 #define Assert(condition) ((void)true)
672 #define AssertMacro(condition) ((void)true)
673 #define AssertArg(condition) ((void)true)
674 #define AssertState(condition) ((void)true)
675 #define AssertPointerAlignment(ptr, bndr) ((void)true)
676 #define Trap(condition, errorType) ((void)true)
677 #define TrapMacro(condition, errorType) (true)
679 #elif defined(FRONTEND)
682 #define Assert(p) assert(p)
683 #define AssertMacro(p) ((void) assert(p))
684 #define AssertArg(condition) assert(condition)
685 #define AssertState(condition) assert(condition)
686 #define AssertPointerAlignment(ptr, bndr) ((void)true)
687 #else /* USE_ASSERT_CHECKING && !FRONTEND */
691 * Generates an exception if the given condition is true.
693 #define Trap(condition, errorType) \
696 ExceptionalCondition(CppAsString(condition), (errorType), \
697 __FILE__, __LINE__); \
701 * TrapMacro is the same as Trap but it's intended for use in macros:
703 * #define foo(x) (AssertMacro(x != 0), bar(x))
707 #define TrapMacro(condition, errorType) \
708 ((bool) (! (condition) || \
709 (ExceptionalCondition(CppAsString(condition), (errorType), \
710 __FILE__, __LINE__), 0)))
712 #define Assert(condition) \
713 Trap(!(condition), "FailedAssertion")
715 #define AssertMacro(condition) \
716 ((void) TrapMacro(!(condition), "FailedAssertion"))
718 #define AssertArg(condition) \
719 Trap(!(condition), "BadArgument")
721 #define AssertState(condition) \
722 Trap(!(condition), "BadState")
725 * Check that `ptr' is `bndr' aligned.
727 #define AssertPointerAlignment(ptr, bndr) \
728 Trap(TYPEALIGN(bndr, (uintptr_t)(ptr)) != (uintptr_t)(ptr), \
731 #endif /* USE_ASSERT_CHECKING && !FRONTEND */
734 * Macros to support compile-time assertion checks.
736 * If the "condition" (a compile-time-constant expression) evaluates to false,
737 * throw a compile error using the "errmessage" (a string literal).
739 * gcc 4.6 and up supports _Static_assert(), but there are bizarre syntactic
740 * placement restrictions. These macros make it safe to use as a statement
741 * or in an expression, respectively.
743 * Otherwise we fall back on a kluge that assumes the compiler will complain
744 * about a negative width for a struct bit-field. This will not include a
745 * helpful error message, but it beats not getting an error at all.
747 #ifdef HAVE__STATIC_ASSERT
748 #define StaticAssertStmt(condition, errmessage) \
749 do { _Static_assert(condition, errmessage); } while(0)
750 #define StaticAssertExpr(condition, errmessage) \
751 ({ StaticAssertStmt(condition, errmessage); true; })
752 #else /* !HAVE__STATIC_ASSERT */
753 #define StaticAssertStmt(condition, errmessage) \
754 ((void) sizeof(struct { int static_assert_failure : (condition) ? 1 : -1; }))
755 #define StaticAssertExpr(condition, errmessage) \
756 StaticAssertStmt(condition, errmessage)
757 #endif /* HAVE__STATIC_ASSERT */
761 * Compile-time checks that a variable (or expression) has the specified type.
763 * AssertVariableIsOfType() can be used as a statement.
764 * AssertVariableIsOfTypeMacro() is intended for use in macros, eg
765 * #define foo(x) (AssertVariableIsOfTypeMacro(x, int), bar(x))
767 * If we don't have __builtin_types_compatible_p, we can still assert that
768 * the types have the same size. This is far from ideal (especially on 32-bit
769 * platforms) but it provides at least some coverage.
771 #ifdef HAVE__BUILTIN_TYPES_COMPATIBLE_P
772 #define AssertVariableIsOfType(varname, typename) \
773 StaticAssertStmt(__builtin_types_compatible_p(__typeof__(varname), typename), \
774 CppAsString(varname) " does not have type " CppAsString(typename))
775 #define AssertVariableIsOfTypeMacro(varname, typename) \
776 ((void) StaticAssertExpr(__builtin_types_compatible_p(__typeof__(varname), typename), \
777 CppAsString(varname) " does not have type " CppAsString(typename)))
778 #else /* !HAVE__BUILTIN_TYPES_COMPATIBLE_P */
779 #define AssertVariableIsOfType(varname, typename) \
780 StaticAssertStmt(sizeof(varname) == sizeof(typename), \
781 CppAsString(varname) " does not have type " CppAsString(typename))
782 #define AssertVariableIsOfTypeMacro(varname, typename) \
783 ((void) StaticAssertExpr(sizeof(varname) == sizeof(typename), \
784 CppAsString(varname) " does not have type " CppAsString(typename)))
785 #endif /* HAVE__BUILTIN_TYPES_COMPATIBLE_P */
788 /* ----------------------------------------------------------------
789 * Section 7: widely useful macros
790 * ----------------------------------------------------------------
794 * Return the maximum of two numbers.
796 #define Max(x, y) ((x) > (y) ? (x) : (y))
800 * Return the minimum of two numbers.
802 #define Min(x, y) ((x) < (y) ? (x) : (y))
806 * Return the absolute value of the argument.
808 #define Abs(x) ((x) >= 0 ? (x) : -(x))
812 * Like standard library function strncpy(), except that result string
813 * is guaranteed to be null-terminated --- that is, at most N-1 bytes
814 * of the source string will be kept.
815 * Also, the macro returns no result (too hard to do that without
816 * evaluating the arguments multiple times, which seems worse).
818 * BTW: when you need to copy a non-null-terminated string (like a text
819 * datum) and add a null, do not do it with StrNCpy(..., len+1). That
820 * might seem to work, but it fetches one byte more than there is in the
821 * text object. One fine day you'll have a SIGSEGV because there isn't
822 * another byte before the end of memory. Don't laugh, we've had real
823 * live bug reports from real live users over exactly this mistake.
824 * Do it honestly with "memcpy(dst,src,len); dst[len] = '\0';", instead.
826 #define StrNCpy(dst,src,len) \
829 char * _dst = (dst); \
834 strncpy(_dst, (src), _len); \
835 _dst[_len-1] = '\0'; \
840 /* Get a bit mask of the bits set in non-long aligned addresses */
841 #define LONG_ALIGN_MASK (sizeof(long) - 1)
845 * Exactly the same as standard library function memset(), but considerably
846 * faster for zeroing small word-aligned structures (such as parsetree nodes).
847 * This has to be a macro because the main point is to avoid function-call
848 * overhead. However, we have also found that the loop is faster than
849 * native libc memset() on some platforms, even those with assembler
850 * memset() functions. More research needs to be done, perhaps with
851 * MEMSET_LOOP_LIMIT tests in configure.
853 #define MemSet(start, val, len) \
856 /* must be void* because we don't know if it is integer aligned yet */ \
857 void *_vstart = (void *) (start); \
861 if ((((uintptr_t) _vstart) & LONG_ALIGN_MASK) == 0 && \
862 (_len & LONG_ALIGN_MASK) == 0 && \
864 _len <= MEMSET_LOOP_LIMIT && \
866 * If MEMSET_LOOP_LIMIT == 0, optimizer should find \
867 * the whole "if" false at compile time. \
869 MEMSET_LOOP_LIMIT != 0) \
871 long *_start = (long *) _vstart; \
872 long *_stop = (long *) ((char *) _start + _len); \
873 while (_start < _stop) \
877 memset(_vstart, _val, _len); \
881 * MemSetAligned is the same as MemSet except it omits the test to see if
882 * "start" is word-aligned. This is okay to use if the caller knows a-priori
883 * that the pointer is suitably aligned (typically, because he just got it
884 * from palloc(), which always delivers a max-aligned pointer).
886 #define MemSetAligned(start, val, len) \
889 long *_start = (long *) (start); \
893 if ((_len & LONG_ALIGN_MASK) == 0 && \
895 _len <= MEMSET_LOOP_LIMIT && \
896 MEMSET_LOOP_LIMIT != 0) \
898 long *_stop = (long *) ((char *) _start + _len); \
899 while (_start < _stop) \
903 memset(_start, _val, _len); \
908 * MemSetTest/MemSetLoop are a variant version that allow all the tests in
909 * MemSet to be done at compile time in cases where "val" and "len" are
910 * constants *and* we know the "start" pointer must be word-aligned.
911 * If MemSetTest succeeds, then it is okay to use MemSetLoop, otherwise use
912 * MemSetAligned. Beware of multiple evaluations of the arguments when using
915 #define MemSetTest(val, len) \
916 ( ((len) & LONG_ALIGN_MASK) == 0 && \
917 (len) <= MEMSET_LOOP_LIMIT && \
918 MEMSET_LOOP_LIMIT != 0 && \
921 #define MemSetLoop(start, val, len) \
924 long * _start = (long *) (start); \
925 long * _stop = (long *) ((char *) _start + (Size) (len)); \
927 while (_start < _stop) \
933 * Mark a point as unreachable in a portable fashion. This should preferably
934 * be something that the compiler understands, to aid code generation.
935 * In assert-enabled builds, we prefer abort() for debugging reasons.
937 #if defined(HAVE__BUILTIN_UNREACHABLE) && !defined(USE_ASSERT_CHECKING)
938 #define pg_unreachable() __builtin_unreachable()
939 #elif defined(_MSC_VER) && !defined(USE_ASSERT_CHECKING)
940 #define pg_unreachable() __assume(0)
942 #define pg_unreachable() abort()
947 * Hints to the compiler about the likelihood of a branch. Both likely() and
948 * unlikely() return the boolean value of the contained expression.
950 * These should only be used sparingly, in very hot code paths. It's very easy
951 * to mis-estimate likelihoods.
954 #define likely(x) __builtin_expect((x) != 0, 1)
955 #define unlikely(x) __builtin_expect((x) != 0, 0)
957 #define likely(x) ((x) != 0)
958 #define unlikely(x) ((x) != 0)
962 /* ----------------------------------------------------------------
963 * Section 8: random stuff
964 * ----------------------------------------------------------------
968 #define HIGHBIT (0x80)
969 #define IS_HIGHBIT_SET(ch) ((unsigned char)(ch) & HIGHBIT)
971 #define STATUS_OK (0)
972 #define STATUS_ERROR (-1)
973 #define STATUS_EOF (-2)
974 #define STATUS_FOUND (1)
975 #define STATUS_WAITING (2)
979 * Append PG_USED_FOR_ASSERTS_ONLY to definitions of variables that are only
980 * used in assert-enabled builds, to avoid compiler warnings about unused
981 * variables in assert-disabled builds.
983 #ifdef USE_ASSERT_CHECKING
984 #define PG_USED_FOR_ASSERTS_ONLY
986 #define PG_USED_FOR_ASSERTS_ONLY pg_attribute_unused()
990 /* gettext domain name mangling */
993 * To better support parallel installations of major PostgreSQL
994 * versions as well as parallel installations of major library soname
995 * versions, we mangle the gettext domain name by appending those
996 * version numbers. The coding rule ought to be that wherever the
997 * domain name is mentioned as a literal, it must be wrapped into
998 * PG_TEXTDOMAIN(). The macros below do not work on non-literals; but
999 * that is somewhat intentional because it avoids having to worry
1000 * about multiple states of premangling and postmangling as the values
1001 * are being passed around.
1003 * Make sure this matches the installation rules in nls-global.mk.
1006 /* need a second indirection because we want to stringize the macro value, not the name */
1007 #define CppAsString2(x) CppAsString(x)
1009 #ifdef SO_MAJOR_VERSION
1010 #define PG_TEXTDOMAIN(domain) (domain CppAsString2(SO_MAJOR_VERSION) "-" PG_MAJORVERSION)
1012 #define PG_TEXTDOMAIN(domain) (domain "-" PG_MAJORVERSION)
1016 /* ----------------------------------------------------------------
1017 * Section 9: system-specific hacks
1019 * This should be limited to things that absolutely have to be
1020 * included in every source file. The port-specific header file
1021 * is usually a better place for this sort of thing.
1022 * ----------------------------------------------------------------
1026 * NOTE: this is also used for opening text files.
1027 * WIN32 treats Control-Z as EOF in files opened in text mode.
1028 * Therefore, we open files in binary mode on Win32 so we can read
1029 * literal control-Z. The other affect is that we see CRLF, but
1030 * that is OK because we can already handle those cleanly.
1032 #if defined(WIN32) || defined(__CYGWIN__)
1033 #define PG_BINARY O_BINARY
1034 #define PG_BINARY_A "ab"
1035 #define PG_BINARY_R "rb"
1036 #define PG_BINARY_W "wb"
1039 #define PG_BINARY_A "a"
1040 #define PG_BINARY_R "r"
1041 #define PG_BINARY_W "w"
1045 * Provide prototypes for routines not present in a particular machine's
1046 * standard C library.
1049 #if !HAVE_DECL_SNPRINTF
1050 extern int snprintf(char *str, size_t count, const char *fmt,...) pg_attribute_printf(3, 4);
1053 #if !HAVE_DECL_VSNPRINTF
1054 extern int vsnprintf(char *str, size_t count, const char *fmt, va_list args);
1057 #if !defined(HAVE_MEMMOVE) && !defined(memmove)
1058 #define memmove(d, s, c) bcopy(s, d, c)
1061 /* no special DLL markers on most ports */
1070 * The following is used as the arg list for signal handlers. Any ports
1071 * that take something other than an int argument should override this in
1072 * their pg_config_os.h file. Note that variable names are required
1073 * because it is used in both the prototypes as well as the definitions.
1074 * Note also the long name. We expect that this won't collide with
1075 * other names causing compiler warnings.
1079 #define SIGNAL_ARGS int postgres_signal_arg
1083 * When there is no sigsetjmp, its functionality is provided by plain
1084 * setjmp. Incidentally, nothing provides setjmp's functionality in
1085 * that case. We now support the case only on Windows.
1088 #define sigjmp_buf jmp_buf
1089 #define sigsetjmp(x,y) setjmp(x)
1090 #define siglongjmp longjmp
1093 #if defined(HAVE_FDATASYNC) && !HAVE_DECL_FDATASYNC
1094 extern int fdatasync(int fildes);
1097 /* If strtoq() exists, rename it to the more standard strtoll() */
1098 #if defined(HAVE_LONG_LONG_INT_64) && !defined(HAVE_STRTOLL) && defined(HAVE_STRTOQ)
1099 #define strtoll strtoq
1100 #define HAVE_STRTOLL 1
1103 /* If strtouq() exists, rename it to the more standard strtoull() */
1104 #if defined(HAVE_LONG_LONG_INT_64) && !defined(HAVE_STRTOULL) && defined(HAVE_STRTOUQ)
1105 #define strtoull strtouq
1106 #define HAVE_STRTOULL 1
1110 * We assume if we have these two functions, we have their friends too, and
1111 * can use the wide-character functions.
1113 #if defined(HAVE_WCSTOMBS) && defined(HAVE_TOWLOWER)
1114 #define USE_WIDE_UPPER_LOWER
1117 /* EXEC_BACKEND defines */
1119 #define NON_EXEC_STATIC
1121 #define NON_EXEC_STATIC static
1124 /* /port compatibility functions */