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-2019, 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) compiler characteristics
30 * 2) bool, true, false
31 * 3) standard system types
32 * 4) IsValid macros for system types
33 * 5) offsetof, lengthof, alignment
35 * 7) widely useful macros
37 * 9) system-specific hacks
39 * NOTE: since this file is included by both frontend and backend modules,
40 * it's usually wrong to put an "extern" declaration here, unless it's
41 * ifdef'd so that it's seen in only one case or the other.
42 * typedefs and macros are the kind of thing that might go here.
44 *----------------------------------------------------------------
49 #include "postgres_ext.h"
51 /* Must undef pg_config_ext.h symbols before including pg_config.h */
54 #include "pg_config.h"
55 #include "pg_config_manual.h" /* must be after pg_config.h */
56 #include "pg_config_os.h" /* must be before any system header files */
58 /* System header files that should be available everywhere in Postgres */
70 #include <sys/types.h>
72 #if defined(WIN32) || defined(__CYGWIN__)
73 #include <fcntl.h> /* ensure O_BINARY is available */
81 /* ----------------------------------------------------------------
82 * Section 1: compiler characteristics
84 * type prefixes (const, signed, volatile, inline) are handled in pg_config.h.
85 * ----------------------------------------------------------------
89 * Disable "inline" if PG_FORCE_DISABLE_INLINE is defined.
90 * This is used to work around compiler bugs and might also be useful for
91 * investigatory purposes.
93 #ifdef PG_FORCE_DISABLE_INLINE
101 * GCC: https://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
102 * GCC: https://gcc.gnu.org/onlinedocs/gcc/Type-Attributes.html
103 * Sunpro: https://docs.oracle.com/cd/E18659_01/html/821-1384/gjzke.html
104 * XLC: https://www.ibm.com/support/knowledgecenter/SSGH2K_13.1.2/com.ibm.xlc131.aix.doc/language_ref/function_attributes.html
105 * XLC: https://www.ibm.com/support/knowledgecenter/SSGH2K_13.1.2/com.ibm.xlc131.aix.doc/language_ref/type_attrib.html
108 /* only GCC supports the unused attribute */
110 #define pg_attribute_unused() __attribute__((unused))
112 #define pg_attribute_unused()
116 * Append PG_USED_FOR_ASSERTS_ONLY to definitions of variables that are only
117 * used in assert-enabled builds, to avoid compiler warnings about unused
118 * variables in assert-disabled builds.
120 #ifdef USE_ASSERT_CHECKING
121 #define PG_USED_FOR_ASSERTS_ONLY
123 #define PG_USED_FOR_ASSERTS_ONLY pg_attribute_unused()
126 /* GCC and XLC support format attributes */
127 #if defined(__GNUC__) || defined(__IBMC__)
128 #define pg_attribute_format_arg(a) __attribute__((format_arg(a)))
129 #define pg_attribute_printf(f,a) __attribute__((format(PG_PRINTF_ATTRIBUTE, f, a)))
131 #define pg_attribute_format_arg(a)
132 #define pg_attribute_printf(f,a)
135 /* GCC, Sunpro and XLC support aligned, packed and noreturn */
136 #if defined(__GNUC__) || defined(__SUNPRO_C) || defined(__IBMC__)
137 #define pg_attribute_aligned(a) __attribute__((aligned(a)))
138 #define pg_attribute_noreturn() __attribute__((noreturn))
139 #define pg_attribute_packed() __attribute__((packed))
140 #define HAVE_PG_ATTRIBUTE_NORETURN 1
143 * NB: aligned and packed are not given default definitions because they
144 * affect code functionality; they *must* be implemented by the compiler
145 * if they are to be used.
147 #define pg_attribute_noreturn()
151 * Use "pg_attribute_always_inline" in place of "inline" for functions that
152 * we wish to force inlining of, even when the compiler's heuristics would
153 * choose not to. But, if possible, don't force inlining in unoptimized
156 #if (defined(__GNUC__) && __GNUC__ > 3 && defined(__OPTIMIZE__)) || defined(__SUNPRO_C) || defined(__IBMC__)
157 /* GCC > 3, Sunpro and XLC support always_inline via __attribute__ */
158 #define pg_attribute_always_inline __attribute__((always_inline)) inline
159 #elif defined(_MSC_VER)
160 /* MSVC has a special keyword for this */
161 #define pg_attribute_always_inline __forceinline
163 /* Otherwise, the best we can do is to say "inline" */
164 #define pg_attribute_always_inline inline
168 * Forcing a function not to be inlined can be useful if it's the slow path of
169 * a performance-critical function, or should be visible in profiles to allow
170 * for proper cost attribution. Note that unlike the pg_attribute_XXX macros
171 * above, this should be placed before the function's return type and name.
173 /* GCC, Sunpro and XLC support noinline via __attribute__ */
174 #if (defined(__GNUC__) && __GNUC__ > 2) || defined(__SUNPRO_C) || defined(__IBMC__)
175 #define pg_noinline __attribute__((noinline))
176 /* msvc via declspec */
177 #elif defined(_MSC_VER)
178 #define pg_noinline __declspec(noinline)
184 * Mark a point as unreachable in a portable fashion. This should preferably
185 * be something that the compiler understands, to aid code generation.
186 * In assert-enabled builds, we prefer abort() for debugging reasons.
188 #if defined(HAVE__BUILTIN_UNREACHABLE) && !defined(USE_ASSERT_CHECKING)
189 #define pg_unreachable() __builtin_unreachable()
190 #elif defined(_MSC_VER) && !defined(USE_ASSERT_CHECKING)
191 #define pg_unreachable() __assume(0)
193 #define pg_unreachable() abort()
197 * Hints to the compiler about the likelihood of a branch. Both likely() and
198 * unlikely() return the boolean value of the contained expression.
200 * These should only be used sparingly, in very hot code paths. It's very easy
201 * to mis-estimate likelihoods.
204 #define likely(x) __builtin_expect((x) != 0, 1)
205 #define unlikely(x) __builtin_expect((x) != 0, 0)
207 #define likely(x) ((x) != 0)
208 #define unlikely(x) ((x) != 0)
213 * Convert the argument to a string, using the C preprocessor.
215 * Convert the argument to a string, after one round of macro expansion.
217 * Concatenate two arguments together, using the C preprocessor.
219 * Note: There used to be support here for pre-ANSI C compilers that didn't
220 * support # and ##. Nowadays, these macros are just for clarity and/or
221 * backward compatibility with existing PostgreSQL code.
223 #define CppAsString(identifier) #identifier
224 #define CppAsString2(x) CppAsString(x)
225 #define CppConcat(x, y) x##y
229 * Returns the number of macro arguments it is passed.
231 * An empty argument still counts as an argument, so effectively, this is
232 * "one more than the number of commas in the argument list".
234 * This works for up to 63 arguments. Internally, VA_ARGS_NARGS_() is passed
235 * 64+N arguments, and the C99 standard only requires macros to allow up to
236 * 127 arguments, so we can't portably go higher. The implementation is
237 * pretty trivial: VA_ARGS_NARGS_() returns its 64th argument, and we set up
238 * the call so that that is the appropriate one of the list of constants.
239 * This idea is due to Laurent Deniau.
241 #define VA_ARGS_NARGS(...) \
242 VA_ARGS_NARGS_(__VA_ARGS__, \
244 59,58,57,56,55,54,53,52,51,50, \
245 49,48,47,46,45,44,43,42,41,40, \
246 39,38,37,36,35,34,33,32,31,30, \
247 29,28,27,26,25,24,23,22,21,20, \
248 19,18,17,16,15,14,13,12,11,10, \
249 9, 8, 7, 6, 5, 4, 3, 2, 1, 0)
250 #define VA_ARGS_NARGS_( \
251 _01,_02,_03,_04,_05,_06,_07,_08,_09,_10, \
252 _11,_12,_13,_14,_15,_16,_17,_18,_19,_20, \
253 _21,_22,_23,_24,_25,_26,_27,_28,_29,_30, \
254 _31,_32,_33,_34,_35,_36,_37,_38,_39,_40, \
255 _41,_42,_43,_44,_45,_46,_47,_48,_49,_50, \
256 _51,_52,_53,_54,_55,_56,_57,_58,_59,_60, \
257 _61,_62,_63, N, ...) \
261 * dummyret is used to set return values in macros that use ?: to make
262 * assignments. gcc wants these to be void, other compilers like char
264 #ifdef __GNUC__ /* GNU cc */
265 #define dummyret void
267 #define dummyret char
270 /* Which __func__ symbol do we have, if any? */
271 #ifdef HAVE_FUNCNAME__FUNC
272 #define PG_FUNCNAME_MACRO __func__
274 #ifdef HAVE_FUNCNAME__FUNCTION
275 #define PG_FUNCNAME_MACRO __FUNCTION__
277 #define PG_FUNCNAME_MACRO NULL
282 /* ----------------------------------------------------------------
283 * Section 2: bool, true, false
284 * ----------------------------------------------------------------
289 * Boolean value, either true or false.
291 * Use stdbool.h if available and its bool has size 1. That's useful for
292 * better compiler and debugger output and for compatibility with third-party
293 * libraries. But PostgreSQL currently cannot deal with bool of other sizes;
294 * there are static assertions around the code to prevent that.
296 * For C++ compilers, we assume the compiler has a compatible built-in
297 * definition of bool.
302 #if defined(HAVE_STDBOOL_H) && SIZEOF_BOOL == 1
304 #define USE_STDBOOL 1
308 typedef unsigned char bool;
312 #define true ((bool) 1)
316 #define false ((bool) 0)
323 /* ----------------------------------------------------------------
324 * Section 3: standard system types
325 * ----------------------------------------------------------------
330 * Variable holding address of any memory resident object.
332 * XXX Pointer arithmetic is done with this, so it can't be void *
333 * under "true" ANSI compilers.
335 typedef char *Pointer;
339 * Signed integer, EXACTLY N BITS IN SIZE,
340 * used for numerical computations and the
341 * frontend/backend protocol.
344 typedef signed char int8; /* == 8 bits */
345 typedef signed short int16; /* == 16 bits */
346 typedef signed int int32; /* == 32 bits */
347 #endif /* not HAVE_INT8 */
351 * Unsigned integer, EXACTLY N BITS IN SIZE,
352 * used for numerical computations and the
353 * frontend/backend protocol.
356 typedef unsigned char uint8; /* == 8 bits */
357 typedef unsigned short uint16; /* == 16 bits */
358 typedef unsigned int uint32; /* == 32 bits */
359 #endif /* not HAVE_UINT8 */
363 * Unit of bitwise operation, AT LEAST N BITS IN SIZE.
365 typedef uint8 bits8; /* >= 8 bits */
366 typedef uint16 bits16; /* >= 16 bits */
367 typedef uint32 bits32; /* >= 32 bits */
372 #ifdef HAVE_LONG_INT_64
373 /* Plain "long int" fits, use it */
376 typedef long int int64;
379 typedef unsigned long int uint64;
381 #define INT64CONST(x) (x##L)
382 #define UINT64CONST(x) (x##UL)
383 #elif defined(HAVE_LONG_LONG_INT_64)
384 /* We have working support for "long long int", use that */
387 typedef long long int int64;
390 typedef unsigned long long int uint64;
392 #define INT64CONST(x) (x##LL)
393 #define UINT64CONST(x) (x##ULL)
395 /* neither HAVE_LONG_INT_64 nor HAVE_LONG_LONG_INT_64 */
396 #error must have a working 64-bit integer datatype
399 /* snprintf format strings to use for 64-bit integers */
400 #define INT64_FORMAT "%" INT64_MODIFIER "d"
401 #define UINT64_FORMAT "%" INT64_MODIFIER "u"
404 * 128-bit signed and unsigned integers
405 * There currently is only limited support for such types.
406 * E.g. 128bit literals and snprintf are not supported; but math is.
407 * Also, because we exclude such types when choosing MAXIMUM_ALIGNOF,
408 * it must be possible to coerce the compiler to allocate them on no
409 * more than MAXALIGN boundaries.
411 #if defined(PG_INT128_TYPE)
412 #if defined(pg_attribute_aligned) || ALIGNOF_PG_INT128_TYPE <= MAXIMUM_ALIGNOF
413 #define HAVE_INT128 1
415 typedef PG_INT128_TYPE int128
416 #if defined(pg_attribute_aligned)
417 pg_attribute_aligned(MAXIMUM_ALIGNOF)
421 typedef unsigned PG_INT128_TYPE uint128
422 #if defined(pg_attribute_aligned)
423 pg_attribute_aligned(MAXIMUM_ALIGNOF)
431 * stdint.h limits aren't guaranteed to be present and aren't guaranteed to
432 * have compatible types with our fixed width types. So just define our own.
434 #define PG_INT8_MIN (-0x7F-1)
435 #define PG_INT8_MAX (0x7F)
436 #define PG_UINT8_MAX (0xFF)
437 #define PG_INT16_MIN (-0x7FFF-1)
438 #define PG_INT16_MAX (0x7FFF)
439 #define PG_UINT16_MAX (0xFFFF)
440 #define PG_INT32_MIN (-0x7FFFFFFF-1)
441 #define PG_INT32_MAX (0x7FFFFFFF)
442 #define PG_UINT32_MAX (0xFFFFFFFFU)
443 #define PG_INT64_MIN (-INT64CONST(0x7FFFFFFFFFFFFFFF) - 1)
444 #define PG_INT64_MAX INT64CONST(0x7FFFFFFFFFFFFFFF)
445 #define PG_UINT64_MAX UINT64CONST(0xFFFFFFFFFFFFFFFF)
447 /* Max value of size_t might also be missing if we don't have stdint.h */
449 #if SIZEOF_SIZE_T == 8
450 #define SIZE_MAX PG_UINT64_MAX
452 #define SIZE_MAX PG_UINT32_MAX
457 * We now always use int64 timestamps, but keep this symbol defined for the
458 * benefit of external code that might test it.
460 #define HAVE_INT64_TIMESTAMP
464 * Size of any memory resident object, as returned by sizeof.
470 * Index into any memory resident array.
473 * Indices are non negative.
475 typedef unsigned int Index;
479 * Offset into any memory resident array.
482 * This differs from an Index in that an Index is always
483 * non negative, whereas Offset may be negative.
485 typedef signed int Offset;
488 * Common Postgres datatype names (as used in the catalogs)
490 typedef float float4;
491 typedef double float8;
494 * Oid, RegProcedure, TransactionId, SubTransactionId, MultiXactId,
498 /* typedef Oid is in postgres_ext.h */
501 * regproc is the type name used in the include/catalog headers, but
502 * RegProcedure is the preferred name in C code.
505 typedef regproc RegProcedure;
507 typedef uint32 TransactionId;
509 typedef uint32 LocalTransactionId;
511 typedef uint32 SubTransactionId;
513 #define InvalidSubTransactionId ((SubTransactionId) 0)
514 #define TopSubTransactionId ((SubTransactionId) 1)
516 /* MultiXactId must be equivalent to TransactionId, to fit in t_xmax */
517 typedef TransactionId MultiXactId;
519 typedef uint32 MultiXactOffset;
521 typedef uint32 CommandId;
523 #define FirstCommandId ((CommandId) 0)
524 #define InvalidCommandId (~(CommandId)0)
527 * Array indexing support
536 * Variable-length datatypes all share the 'struct varlena' header.
538 * NOTE: for TOASTable types, this is an oversimplification, since the value
539 * may be compressed or moved out-of-line. However datatype-specific routines
540 * are mostly content to deal with de-TOASTed values only, and of course
541 * client-side routines should never see a TOASTed value. But even in a
542 * de-TOASTed value, beware of touching vl_len_ directly, as its
543 * representation is no longer convenient. It's recommended that code always
544 * use macros VARDATA_ANY, VARSIZE_ANY, VARSIZE_ANY_EXHDR, VARDATA, VARSIZE,
545 * and SET_VARSIZE instead of relying on direct mentions of the struct fields.
546 * See postgres.h for details of the TOASTed form.
551 char vl_len_[4]; /* Do not touch this field directly! */
552 char vl_dat[FLEXIBLE_ARRAY_MEMBER]; /* Data content is here */
555 #define VARHDRSZ ((int32) sizeof(int32))
558 * These widely-used datatypes are just a varlena header and the data bytes.
559 * There is no terminating null or anything like that --- the data length is
560 * always VARSIZE_ANY_EXHDR(ptr).
562 typedef struct varlena bytea;
563 typedef struct varlena text;
564 typedef struct varlena BpChar; /* blank-padded char, ie SQL char(n) */
565 typedef struct varlena VarChar; /* var-length char, ie SQL varchar(n) */
568 * Specialized array types. These are physically laid out just the same
569 * as regular arrays (so that the regular array subscripting code works
570 * with them). They exist as distinct types mostly for historical reasons:
571 * they have nonstandard I/O behavior which we don't want to change for fear
572 * of breaking applications that look at the system catalogs. There is also
573 * an implementation issue for oidvector: it's part of the primary key for
574 * pg_proc, and we can't use the normal btree array support routines for that
575 * without circularity.
579 int32 vl_len_; /* these fields must match ArrayType! */
580 int ndim; /* always 1 for int2vector */
581 int32 dataoffset; /* always 0 for int2vector */
585 int16 values[FLEXIBLE_ARRAY_MEMBER];
590 int32 vl_len_; /* these fields must match ArrayType! */
591 int ndim; /* always 1 for oidvector */
592 int32 dataoffset; /* always 0 for oidvector */
596 Oid values[FLEXIBLE_ARRAY_MEMBER];
600 * Representation of a Name: effectively just a C string, but null-padded to
601 * exactly NAMEDATALEN bytes. The use of a struct is historical.
603 typedef struct nameData
605 char data[NAMEDATALEN];
607 typedef NameData *Name;
609 #define NameStr(name) ((name).data)
612 /* ----------------------------------------------------------------
613 * Section 4: IsValid macros for system types
614 * ----------------------------------------------------------------
618 * True iff bool is valid.
620 #define BoolIsValid(boolean) ((boolean) == false || (boolean) == true)
624 * True iff pointer is valid.
626 #define PointerIsValid(pointer) ((const void*)(pointer) != NULL)
630 * True iff pointer is properly aligned to point to the given type.
632 #define PointerIsAligned(pointer, type) \
633 (((uintptr_t)(pointer) % (sizeof (type))) == 0)
635 #define OffsetToPointer(base, offset) \
636 ((void *)((char *) base + offset))
638 #define OidIsValid(objectId) ((bool) ((objectId) != InvalidOid))
640 #define RegProcedureIsValid(p) OidIsValid(p)
643 /* ----------------------------------------------------------------
644 * Section 5: offsetof, lengthof, alignment
645 * ----------------------------------------------------------------
649 * Offset of a structure/union field within that structure/union.
651 * XXX This is supposed to be part of stddef.h, but isn't on
652 * some systems (like SunOS 4).
655 #define offsetof(type, field) ((long) &((type *)0)->field)
656 #endif /* offsetof */
660 * Number of elements in an array.
662 #define lengthof(array) (sizeof (array) / sizeof ((array)[0]))
665 * Alignment macros: align a length or address appropriately for a given type.
666 * The fooALIGN() macros round up to a multiple of the required alignment,
667 * while the fooALIGN_DOWN() macros round down. The latter are more useful
668 * for problems like "how many X-sized structures will fit in a page?".
670 * NOTE: TYPEALIGN[_DOWN] will not work if ALIGNVAL is not a power of 2.
671 * That case seems extremely unlikely to be needed in practice, however.
673 * NOTE: MAXIMUM_ALIGNOF, and hence MAXALIGN(), intentionally exclude any
674 * larger-than-8-byte types the compiler might have.
678 #define TYPEALIGN(ALIGNVAL,LEN) \
679 (((uintptr_t) (LEN) + ((ALIGNVAL) - 1)) & ~((uintptr_t) ((ALIGNVAL) - 1)))
681 #define SHORTALIGN(LEN) TYPEALIGN(ALIGNOF_SHORT, (LEN))
682 #define INTALIGN(LEN) TYPEALIGN(ALIGNOF_INT, (LEN))
683 #define LONGALIGN(LEN) TYPEALIGN(ALIGNOF_LONG, (LEN))
684 #define DOUBLEALIGN(LEN) TYPEALIGN(ALIGNOF_DOUBLE, (LEN))
685 #define MAXALIGN(LEN) TYPEALIGN(MAXIMUM_ALIGNOF, (LEN))
686 /* MAXALIGN covers only built-in types, not buffers */
687 #define BUFFERALIGN(LEN) TYPEALIGN(ALIGNOF_BUFFER, (LEN))
688 #define CACHELINEALIGN(LEN) TYPEALIGN(PG_CACHE_LINE_SIZE, (LEN))
690 #define TYPEALIGN_DOWN(ALIGNVAL,LEN) \
691 (((uintptr_t) (LEN)) & ~((uintptr_t) ((ALIGNVAL) - 1)))
693 #define SHORTALIGN_DOWN(LEN) TYPEALIGN_DOWN(ALIGNOF_SHORT, (LEN))
694 #define INTALIGN_DOWN(LEN) TYPEALIGN_DOWN(ALIGNOF_INT, (LEN))
695 #define LONGALIGN_DOWN(LEN) TYPEALIGN_DOWN(ALIGNOF_LONG, (LEN))
696 #define DOUBLEALIGN_DOWN(LEN) TYPEALIGN_DOWN(ALIGNOF_DOUBLE, (LEN))
697 #define MAXALIGN_DOWN(LEN) TYPEALIGN_DOWN(MAXIMUM_ALIGNOF, (LEN))
698 #define BUFFERALIGN_DOWN(LEN) TYPEALIGN_DOWN(ALIGNOF_BUFFER, (LEN))
701 * The above macros will not work with types wider than uintptr_t, like with
702 * uint64 on 32-bit platforms. That's not problem for the usual use where a
703 * pointer or a length is aligned, but for the odd case that you need to
704 * align something (potentially) wider, use TYPEALIGN64.
706 #define TYPEALIGN64(ALIGNVAL,LEN) \
707 (((uint64) (LEN) + ((ALIGNVAL) - 1)) & ~((uint64) ((ALIGNVAL) - 1)))
709 /* we don't currently need wider versions of the other ALIGN macros */
710 #define MAXALIGN64(LEN) TYPEALIGN64(MAXIMUM_ALIGNOF, (LEN))
713 /* ----------------------------------------------------------------
714 * Section 6: assertions
715 * ----------------------------------------------------------------
719 * USE_ASSERT_CHECKING, if defined, turns on all the assertions.
722 * It should _NOT_ be defined in releases or in benchmark copies
726 * Assert() can be used in both frontend and backend code. In frontend code it
727 * just calls the standard assert, if it's available. If use of assertions is
728 * not configured, it does nothing.
730 #ifndef USE_ASSERT_CHECKING
732 #define Assert(condition) ((void)true)
733 #define AssertMacro(condition) ((void)true)
734 #define AssertArg(condition) ((void)true)
735 #define AssertState(condition) ((void)true)
736 #define AssertPointerAlignment(ptr, bndr) ((void)true)
737 #define Trap(condition, errorType) ((void)true)
738 #define TrapMacro(condition, errorType) (true)
740 #elif defined(FRONTEND)
743 #define Assert(p) assert(p)
744 #define AssertMacro(p) ((void) assert(p))
745 #define AssertArg(condition) assert(condition)
746 #define AssertState(condition) assert(condition)
747 #define AssertPointerAlignment(ptr, bndr) ((void)true)
749 #else /* USE_ASSERT_CHECKING && !FRONTEND */
753 * Generates an exception if the given condition is true.
755 #define Trap(condition, errorType) \
758 ExceptionalCondition(#condition, (errorType), \
759 __FILE__, __LINE__); \
763 * TrapMacro is the same as Trap but it's intended for use in macros:
765 * #define foo(x) (AssertMacro(x != 0), bar(x))
769 #define TrapMacro(condition, errorType) \
770 ((bool) (! (condition) || \
771 (ExceptionalCondition(#condition, (errorType), \
772 __FILE__, __LINE__), 0)))
774 #define Assert(condition) \
777 ExceptionalCondition(#condition, "FailedAssertion", \
778 __FILE__, __LINE__); \
781 #define AssertMacro(condition) \
782 ((void) ((condition) || \
783 (ExceptionalCondition(#condition, "FailedAssertion", \
784 __FILE__, __LINE__), 0)))
786 #define AssertArg(condition) \
789 ExceptionalCondition(#condition, "BadArgument", \
790 __FILE__, __LINE__); \
793 #define AssertState(condition) \
796 ExceptionalCondition(#condition, "BadState", \
797 __FILE__, __LINE__); \
801 * Check that `ptr' is `bndr' aligned.
803 #define AssertPointerAlignment(ptr, bndr) \
804 Trap(TYPEALIGN(bndr, (uintptr_t)(ptr)) != (uintptr_t)(ptr), \
807 #endif /* USE_ASSERT_CHECKING && !FRONTEND */
810 * ExceptionalCondition is compiled into the backend whether or not
811 * USE_ASSERT_CHECKING is defined, so as to support use of extensions
812 * that are built with that #define with a backend that isn't. Hence,
813 * we should declare it as long as !FRONTEND.
816 extern void ExceptionalCondition(const char *conditionName,
817 const char *errorType,
818 const char *fileName, int lineNumber) pg_attribute_noreturn();
822 * Macros to support compile-time assertion checks.
824 * If the "condition" (a compile-time-constant expression) evaluates to false,
825 * throw a compile error using the "errmessage" (a string literal).
827 * gcc 4.6 and up supports _Static_assert(), but there are bizarre syntactic
828 * placement restrictions. These macros make it safe to use as a statement
829 * or in an expression, respectively.
831 * Otherwise we fall back on a kluge that assumes the compiler will complain
832 * about a negative width for a struct bit-field. This will not include a
833 * helpful error message, but it beats not getting an error at all.
836 #ifdef HAVE__STATIC_ASSERT
837 #define StaticAssertStmt(condition, errmessage) \
838 do { _Static_assert(condition, errmessage); } while(0)
839 #define StaticAssertExpr(condition, errmessage) \
840 ((void) ({ StaticAssertStmt(condition, errmessage); true; }))
841 #else /* !HAVE__STATIC_ASSERT */
842 #define StaticAssertStmt(condition, errmessage) \
843 ((void) sizeof(struct { int static_assert_failure : (condition) ? 1 : -1; }))
844 #define StaticAssertExpr(condition, errmessage) \
845 StaticAssertStmt(condition, errmessage)
846 #endif /* HAVE__STATIC_ASSERT */
848 #if defined(__cpp_static_assert) && __cpp_static_assert >= 200410
849 #define StaticAssertStmt(condition, errmessage) \
850 static_assert(condition, errmessage)
851 #define StaticAssertExpr(condition, errmessage) \
852 ({ static_assert(condition, errmessage); })
854 #define StaticAssertStmt(condition, errmessage) \
855 do { struct static_assert_struct { int static_assert_failure : (condition) ? 1 : -1; }; } while(0)
856 #define StaticAssertExpr(condition, errmessage) \
857 ((void) ({ StaticAssertStmt(condition, errmessage); }))
863 * Compile-time checks that a variable (or expression) has the specified type.
865 * AssertVariableIsOfType() can be used as a statement.
866 * AssertVariableIsOfTypeMacro() is intended for use in macros, eg
867 * #define foo(x) (AssertVariableIsOfTypeMacro(x, int), bar(x))
869 * If we don't have __builtin_types_compatible_p, we can still assert that
870 * the types have the same size. This is far from ideal (especially on 32-bit
871 * platforms) but it provides at least some coverage.
873 #ifdef HAVE__BUILTIN_TYPES_COMPATIBLE_P
874 #define AssertVariableIsOfType(varname, typename) \
875 StaticAssertStmt(__builtin_types_compatible_p(__typeof__(varname), typename), \
876 CppAsString(varname) " does not have type " CppAsString(typename))
877 #define AssertVariableIsOfTypeMacro(varname, typename) \
878 (StaticAssertExpr(__builtin_types_compatible_p(__typeof__(varname), typename), \
879 CppAsString(varname) " does not have type " CppAsString(typename)))
880 #else /* !HAVE__BUILTIN_TYPES_COMPATIBLE_P */
881 #define AssertVariableIsOfType(varname, typename) \
882 StaticAssertStmt(sizeof(varname) == sizeof(typename), \
883 CppAsString(varname) " does not have type " CppAsString(typename))
884 #define AssertVariableIsOfTypeMacro(varname, typename) \
885 (StaticAssertExpr(sizeof(varname) == sizeof(typename), \
886 CppAsString(varname) " does not have type " CppAsString(typename)))
887 #endif /* HAVE__BUILTIN_TYPES_COMPATIBLE_P */
890 /* ----------------------------------------------------------------
891 * Section 7: widely useful macros
892 * ----------------------------------------------------------------
896 * Return the maximum of two numbers.
898 #define Max(x, y) ((x) > (y) ? (x) : (y))
902 * Return the minimum of two numbers.
904 #define Min(x, y) ((x) < (y) ? (x) : (y))
908 * Return the absolute value of the argument.
910 #define Abs(x) ((x) >= 0 ? (x) : -(x))
914 * Like standard library function strncpy(), except that result string
915 * is guaranteed to be null-terminated --- that is, at most N-1 bytes
916 * of the source string will be kept.
917 * Also, the macro returns no result (too hard to do that without
918 * evaluating the arguments multiple times, which seems worse).
920 * BTW: when you need to copy a non-null-terminated string (like a text
921 * datum) and add a null, do not do it with StrNCpy(..., len+1). That
922 * might seem to work, but it fetches one byte more than there is in the
923 * text object. One fine day you'll have a SIGSEGV because there isn't
924 * another byte before the end of memory. Don't laugh, we've had real
925 * live bug reports from real live users over exactly this mistake.
926 * Do it honestly with "memcpy(dst,src,len); dst[len] = '\0';", instead.
928 #define StrNCpy(dst,src,len) \
931 char * _dst = (dst); \
936 strncpy(_dst, (src), _len); \
937 _dst[_len-1] = '\0'; \
942 /* Get a bit mask of the bits set in non-long aligned addresses */
943 #define LONG_ALIGN_MASK (sizeof(long) - 1)
947 * Exactly the same as standard library function memset(), but considerably
948 * faster for zeroing small word-aligned structures (such as parsetree nodes).
949 * This has to be a macro because the main point is to avoid function-call
950 * overhead. However, we have also found that the loop is faster than
951 * native libc memset() on some platforms, even those with assembler
952 * memset() functions. More research needs to be done, perhaps with
953 * MEMSET_LOOP_LIMIT tests in configure.
955 #define MemSet(start, val, len) \
958 /* must be void* because we don't know if it is integer aligned yet */ \
959 void *_vstart = (void *) (start); \
963 if ((((uintptr_t) _vstart) & LONG_ALIGN_MASK) == 0 && \
964 (_len & LONG_ALIGN_MASK) == 0 && \
966 _len <= MEMSET_LOOP_LIMIT && \
968 * If MEMSET_LOOP_LIMIT == 0, optimizer should find \
969 * the whole "if" false at compile time. \
971 MEMSET_LOOP_LIMIT != 0) \
973 long *_start = (long *) _vstart; \
974 long *_stop = (long *) ((char *) _start + _len); \
975 while (_start < _stop) \
979 memset(_vstart, _val, _len); \
983 * MemSetAligned is the same as MemSet except it omits the test to see if
984 * "start" is word-aligned. This is okay to use if the caller knows a-priori
985 * that the pointer is suitably aligned (typically, because he just got it
986 * from palloc(), which always delivers a max-aligned pointer).
988 #define MemSetAligned(start, val, len) \
991 long *_start = (long *) (start); \
995 if ((_len & LONG_ALIGN_MASK) == 0 && \
997 _len <= MEMSET_LOOP_LIMIT && \
998 MEMSET_LOOP_LIMIT != 0) \
1000 long *_stop = (long *) ((char *) _start + _len); \
1001 while (_start < _stop) \
1005 memset(_start, _val, _len); \
1010 * MemSetTest/MemSetLoop are a variant version that allow all the tests in
1011 * MemSet to be done at compile time in cases where "val" and "len" are
1012 * constants *and* we know the "start" pointer must be word-aligned.
1013 * If MemSetTest succeeds, then it is okay to use MemSetLoop, otherwise use
1014 * MemSetAligned. Beware of multiple evaluations of the arguments when using
1017 #define MemSetTest(val, len) \
1018 ( ((len) & LONG_ALIGN_MASK) == 0 && \
1019 (len) <= MEMSET_LOOP_LIMIT && \
1020 MEMSET_LOOP_LIMIT != 0 && \
1023 #define MemSetLoop(start, val, len) \
1026 long * _start = (long *) (start); \
1027 long * _stop = (long *) ((char *) _start + (Size) (len)); \
1029 while (_start < _stop) \
1034 /* ----------------------------------------------------------------
1035 * Section 8: random stuff
1036 * ----------------------------------------------------------------
1040 * Invert the sign of a qsort-style comparison result, ie, exchange negative
1041 * and positive integer values, being careful not to get the wrong answer
1042 * for INT_MIN. The argument should be an integral variable.
1044 #define INVERT_COMPARE_RESULT(var) \
1045 ((var) = ((var) < 0) ? 1 : -(var))
1048 * Use this, not "char buf[BLCKSZ]", to declare a field or local variable
1049 * holding a page buffer, if that page might be accessed as a page and not
1050 * just a string of bytes. Otherwise the variable might be under-aligned,
1051 * causing problems on alignment-picky hardware. (In some places, we use
1052 * this to declare buffers even though we only pass them to read() and
1053 * write(), because copying to/from aligned buffers is usually faster than
1054 * using unaligned buffers.) We include both "double" and "int64" in the
1055 * union to ensure that the compiler knows the value must be MAXALIGN'ed
1056 * (cf. configure's computation of MAXIMUM_ALIGNOF).
1058 typedef union PGAlignedBlock
1061 double force_align_d;
1062 int64 force_align_i64;
1065 /* Same, but for an XLOG_BLCKSZ-sized buffer */
1066 typedef union PGAlignedXLogBlock
1068 char data[XLOG_BLCKSZ];
1069 double force_align_d;
1070 int64 force_align_i64;
1071 } PGAlignedXLogBlock;
1074 #define HIGHBIT (0x80)
1075 #define IS_HIGHBIT_SET(ch) ((unsigned char)(ch) & HIGHBIT)
1078 * Support macros for escaping strings. escape_backslash should be true
1079 * if generating a non-standard-conforming string. Prefixing a string
1080 * with ESCAPE_STRING_SYNTAX guarantees it is non-standard-conforming.
1081 * Beware of multiple evaluation of the "ch" argument!
1083 #define SQL_STR_DOUBLE(ch, escape_backslash) \
1084 ((ch) == '\'' || ((ch) == '\\' && (escape_backslash)))
1086 #define ESCAPE_STRING_SYNTAX 'E'
1089 #define STATUS_OK (0)
1090 #define STATUS_ERROR (-1)
1091 #define STATUS_EOF (-2)
1092 #define STATUS_FOUND (1)
1093 #define STATUS_WAITING (2)
1100 /* stuff we'd otherwise get from <libintl.h> */
1101 #define gettext(x) (x)
1102 #define dgettext(d,x) (x)
1103 #define ngettext(s,p,n) ((n) == 1 ? (s) : (p))
1104 #define dngettext(d,s,p,n) ((n) == 1 ? (s) : (p))
1107 #define _(x) gettext(x)
1110 * Use this to mark string constants as needing translation at some later
1111 * time, rather than immediately. This is useful for cases where you need
1112 * access to the original string and translated string, and for cases where
1113 * immediate translation is not possible, like when initializing global
1115 * http://www.gnu.org/software/autoconf/manual/gettext/Special-cases.html
1117 #define gettext_noop(x) (x)
1120 * To better support parallel installations of major PostgreSQL
1121 * versions as well as parallel installations of major library soname
1122 * versions, we mangle the gettext domain name by appending those
1123 * version numbers. The coding rule ought to be that wherever the
1124 * domain name is mentioned as a literal, it must be wrapped into
1125 * PG_TEXTDOMAIN(). The macros below do not work on non-literals; but
1126 * that is somewhat intentional because it avoids having to worry
1127 * about multiple states of premangling and postmangling as the values
1128 * are being passed around.
1130 * Make sure this matches the installation rules in nls-global.mk.
1132 #ifdef SO_MAJOR_VERSION
1133 #define PG_TEXTDOMAIN(domain) (domain CppAsString2(SO_MAJOR_VERSION) "-" PG_MAJORVERSION)
1135 #define PG_TEXTDOMAIN(domain) (domain "-" PG_MAJORVERSION)
1139 * Macro that allows to cast constness and volatile away from an expression, but doesn't
1140 * allow changing the underlying type. Enforcement of the latter
1141 * currently only works for gcc like compilers.
1143 * Please note IT IS NOT SAFE to cast constness away if the result will ever
1144 * be modified (it would be undefined behaviour). Doing so anyway can cause
1145 * compiler misoptimizations or runtime crashes (modifying readonly memory).
1146 * It is only safe to use when the result will not be modified, but API
1147 * design or language restrictions prevent you from declaring that
1148 * (e.g. because a function returns both const and non-const variables).
1150 * Note that this only works in function scope, not for global variables (it'd
1151 * be nice, but not trivial, to improve that).
1153 #if defined(HAVE__BUILTIN_TYPES_COMPATIBLE_P)
1154 #define unconstify(underlying_type, expr) \
1155 (StaticAssertExpr(__builtin_types_compatible_p(__typeof(expr), const underlying_type), \
1157 (underlying_type) (expr))
1158 #define unvolatize(underlying_type, expr) \
1159 (StaticAssertExpr(__builtin_types_compatible_p(__typeof(expr), volatile underlying_type), \
1161 (underlying_type) (expr))
1163 #define unconstify(underlying_type, expr) \
1164 ((underlying_type) (expr))
1165 #define unvolatize(underlying_type, expr) \
1166 ((underlying_type) (expr))
1169 /* ----------------------------------------------------------------
1170 * Section 9: system-specific hacks
1172 * This should be limited to things that absolutely have to be
1173 * included in every source file. The port-specific header file
1174 * is usually a better place for this sort of thing.
1175 * ----------------------------------------------------------------
1179 * NOTE: this is also used for opening text files.
1180 * WIN32 treats Control-Z as EOF in files opened in text mode.
1181 * Therefore, we open files in binary mode on Win32 so we can read
1182 * literal control-Z. The other affect is that we see CRLF, but
1183 * that is OK because we can already handle those cleanly.
1185 #if defined(WIN32) || defined(__CYGWIN__)
1186 #define PG_BINARY O_BINARY
1187 #define PG_BINARY_A "ab"
1188 #define PG_BINARY_R "rb"
1189 #define PG_BINARY_W "wb"
1192 #define PG_BINARY_A "a"
1193 #define PG_BINARY_R "r"
1194 #define PG_BINARY_W "w"
1198 * Provide prototypes for routines not present in a particular machine's
1199 * standard C library.
1202 #if defined(HAVE_FDATASYNC) && !HAVE_DECL_FDATASYNC
1203 extern int fdatasync(int fildes);
1206 #ifdef HAVE_LONG_LONG_INT
1207 /* Older platforms may provide strto[u]ll functionality under other names */
1208 #if !defined(HAVE_STRTOLL) && defined(HAVE___STRTOLL)
1209 #define strtoll __strtoll
1210 #define HAVE_STRTOLL 1
1213 #if !defined(HAVE_STRTOLL) && defined(HAVE_STRTOQ)
1214 #define strtoll strtoq
1215 #define HAVE_STRTOLL 1
1218 #if !defined(HAVE_STRTOULL) && defined(HAVE___STRTOULL)
1219 #define strtoull __strtoull
1220 #define HAVE_STRTOULL 1
1223 #if !defined(HAVE_STRTOULL) && defined(HAVE_STRTOUQ)
1224 #define strtoull strtouq
1225 #define HAVE_STRTOULL 1
1228 #if defined(HAVE_STRTOLL) && !HAVE_DECL_STRTOLL
1229 extern long long strtoll(const char *str, char **endptr, int base);
1232 #if defined(HAVE_STRTOULL) && !HAVE_DECL_STRTOULL
1233 extern unsigned long long strtoull(const char *str, char **endptr, int base);
1235 #endif /* HAVE_LONG_LONG_INT */
1237 #if !defined(HAVE_MEMMOVE) && !defined(memmove)
1238 #define memmove(d, s, c) bcopy(s, d, c)
1241 /* no special DLL markers on most ports */
1250 * The following is used as the arg list for signal handlers. Any ports
1251 * that take something other than an int argument should override this in
1252 * their pg_config_os.h file. Note that variable names are required
1253 * because it is used in both the prototypes as well as the definitions.
1254 * Note also the long name. We expect that this won't collide with
1255 * other names causing compiler warnings.
1259 #define SIGNAL_ARGS int postgres_signal_arg
1263 * When there is no sigsetjmp, its functionality is provided by plain
1264 * setjmp. Incidentally, nothing provides setjmp's functionality in
1265 * that case. We now support the case only on Windows.
1268 #define sigjmp_buf jmp_buf
1269 #define sigsetjmp(x,y) setjmp(x)
1270 #define siglongjmp longjmp
1273 /* EXEC_BACKEND defines */
1275 #define NON_EXEC_STATIC
1277 #define NON_EXEC_STATIC static
1280 /* /port compatibility functions */