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-2015, 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"
104 /* Must be before gettext() games below */
107 #define _(x) gettext(x)
112 #define gettext(x) (x)
113 #define dgettext(d,x) (x)
114 #define ngettext(s,p,n) ((n) == 1 ? (s) : (p))
115 #define dngettext(d,s,p,n) ((n) == 1 ? (s) : (p))
119 * Use this to mark string constants as needing translation at some later
120 * time, rather than immediately. This is useful for cases where you need
121 * access to the original string and translated string, and for cases where
122 * immediate translation is not possible, like when initializing global
124 * http://www.gnu.org/software/autoconf/manual/gettext/Special-cases.html
126 #define gettext_noop(x) (x)
129 /* ----------------------------------------------------------------
130 * Section 1: hacks to cope with non-ANSI C compilers
132 * type prefixes (const, signed, volatile, inline) are handled in pg_config.h.
133 * ----------------------------------------------------------------
138 * Convert the argument to a string, using the C preprocessor.
140 * Concatenate two arguments together, using the C preprocessor.
142 * Note: There used to be support here for pre-ANSI C compilers that didn't
143 * support # and ##. Nowadays, these macros are just for clarity and/or
144 * backward compatibility with existing PostgreSQL code.
146 #define CppAsString(identifier) #identifier
147 #define CppConcat(x, y) x##y
150 * dummyret is used to set return values in macros that use ?: to make
151 * assignments. gcc wants these to be void, other compilers like char
153 #ifdef __GNUC__ /* GNU cc */
154 #define dummyret void
156 #define dummyret char
159 /* ----------------------------------------------------------------
160 * Section 2: bool, true, false, TRUE, FALSE, NULL
161 * ----------------------------------------------------------------
166 * Boolean value, either true or false.
168 * XXX for C++ compilers, we assume the compiler has a compatible
169 * built-in definition of bool.
179 #define true ((bool) 1)
183 #define false ((bool) 0)
187 typedef bool *BoolPtr;
202 #define NULL ((void *) 0)
206 /* ----------------------------------------------------------------
207 * Section 3: standard system types
208 * ----------------------------------------------------------------
213 * Variable holding address of any memory resident object.
215 * XXX Pointer arithmetic is done with this, so it can't be void *
216 * under "true" ANSI compilers.
218 typedef char *Pointer;
222 * Signed integer, EXACTLY N BITS IN SIZE,
223 * used for numerical computations and the
224 * frontend/backend protocol.
227 typedef signed char int8; /* == 8 bits */
228 typedef signed short int16; /* == 16 bits */
229 typedef signed int int32; /* == 32 bits */
230 #endif /* not HAVE_INT8 */
234 * Unsigned integer, EXACTLY N BITS IN SIZE,
235 * used for numerical computations and the
236 * frontend/backend protocol.
239 typedef unsigned char uint8; /* == 8 bits */
240 typedef unsigned short uint16; /* == 16 bits */
241 typedef unsigned int uint32; /* == 32 bits */
242 #endif /* not HAVE_UINT8 */
246 * Unit of bitwise operation, AT LEAST N BITS IN SIZE.
248 typedef uint8 bits8; /* >= 8 bits */
249 typedef uint16 bits16; /* >= 16 bits */
250 typedef uint32 bits32; /* >= 32 bits */
252 /* should be defined in stdint.h, but we guarantee them here */
254 #define INT8_MIN (-0x7F-1)
257 #define INT8_MAX (0x7F)
260 #define INT16_MIN (-0x7FFF-1)
263 #define INT16_MAX (0x7FFF)
266 #define INT32_MIN (-0x7FFFFFFF-1)
269 #define INT32_MAX (0x7FFFFFFF)
273 #define UINT8_MAX (0xFF)
276 #define UINT16_MAX (0xFFFF)
279 #define UINT32_MAX (0xFFFFFFFF)
285 #ifdef HAVE_LONG_INT_64
286 /* Plain "long int" fits, use it */
289 typedef long int int64;
292 typedef unsigned long int uint64;
294 #elif defined(HAVE_LONG_LONG_INT_64)
295 /* We have working support for "long long int", use that */
298 typedef long long int int64;
301 typedef unsigned long long int uint64;
304 /* neither HAVE_LONG_INT_64 nor HAVE_LONG_LONG_INT_64 */
305 #error must have a working 64-bit integer datatype
308 /* Decide if we need to decorate 64-bit constants */
309 #ifdef HAVE_LL_CONSTANTS
310 #define INT64CONST(x) ((int64) x##LL)
311 #define UINT64CONST(x) ((uint64) x##ULL)
313 #define INT64CONST(x) ((int64) x)
314 #define UINT64CONST(x) ((uint64) x)
317 /* should be defined in stdint.h, but we guarantee them here */
319 #define INT64_MIN (-INT64CONST(0x7FFFFFFFFFFFFFFF) - 1)
322 #define INT64_MAX INT64CONST(0x7FFFFFFFFFFFFFFF)
325 #define UINT64_MAX UINT64CONST(0xFFFFFFFFFFFFFFFF)
328 /* snprintf format strings to use for 64-bit integers */
329 #define INT64_FORMAT "%" INT64_MODIFIER "d"
330 #define UINT64_FORMAT "%" INT64_MODIFIER "u"
332 /* Select timestamp representation (float8 or int64) */
333 #ifdef USE_INTEGER_DATETIMES
334 #define HAVE_INT64_TIMESTAMP
338 * 128-bit signed and unsigned integers
339 * There currently is only a limited support for the type. E.g. 128bit
340 * literals and snprintf are not supported; but math is.
342 #if defined(PG_INT128_TYPE)
344 typedef PG_INT128_TYPE int128;
345 typedef unsigned PG_INT128_TYPE uint128;
348 /* sig_atomic_t is required by ANSI C, but may be missing on old platforms */
349 #ifndef HAVE_SIG_ATOMIC_T
350 typedef int sig_atomic_t;
355 * Size of any memory resident object, as returned by sizeof.
361 * Index into any memory resident array.
364 * Indices are non negative.
366 typedef unsigned int Index;
370 * Offset into any memory resident array.
373 * This differs from an Index in that an Index is always
374 * non negative, whereas Offset may be negative.
376 typedef signed int Offset;
379 * Common Postgres datatype names (as used in the catalogs)
381 typedef float float4;
382 typedef double float8;
385 * Oid, RegProcedure, TransactionId, SubTransactionId, MultiXactId,
389 /* typedef Oid is in postgres_ext.h */
392 * regproc is the type name used in the include/catalog headers, but
393 * RegProcedure is the preferred name in C code.
396 typedef regproc RegProcedure;
398 typedef uint32 TransactionId;
400 typedef uint32 LocalTransactionId;
402 typedef uint32 SubTransactionId;
404 #define InvalidSubTransactionId ((SubTransactionId) 0)
405 #define TopSubTransactionId ((SubTransactionId) 1)
407 /* MultiXactId must be equivalent to TransactionId, to fit in t_xmax */
408 typedef TransactionId MultiXactId;
410 typedef uint32 MultiXactOffset;
412 typedef uint32 CommandId;
414 #define FirstCommandId ((CommandId) 0)
415 #define InvalidCommandId (~(CommandId)0)
418 * Array indexing support
427 * Variable-length datatypes all share the 'struct varlena' header.
429 * NOTE: for TOASTable types, this is an oversimplification, since the value
430 * may be compressed or moved out-of-line. However datatype-specific routines
431 * are mostly content to deal with de-TOASTed values only, and of course
432 * client-side routines should never see a TOASTed value. But even in a
433 * de-TOASTed value, beware of touching vl_len_ directly, as its representation
434 * is no longer convenient. It's recommended that code always use the VARDATA,
435 * VARSIZE, and SET_VARSIZE macros instead of relying on direct mentions of
436 * the struct fields. See postgres.h for details of the TOASTed form.
441 char vl_len_[4]; /* Do not touch this field directly! */
442 char vl_dat[FLEXIBLE_ARRAY_MEMBER]; /* Data content is here */
445 #define VARHDRSZ ((int32) sizeof(int32))
448 * These widely-used datatypes are just a varlena header and the data bytes.
449 * There is no terminating null or anything like that --- the data length is
450 * always VARSIZE(ptr) - VARHDRSZ.
452 typedef struct varlena bytea;
453 typedef struct varlena text;
454 typedef struct varlena BpChar; /* blank-padded char, ie SQL char(n) */
455 typedef struct varlena VarChar; /* var-length char, ie SQL varchar(n) */
458 * Specialized array types. These are physically laid out just the same
459 * as regular arrays (so that the regular array subscripting code works
460 * with them). They exist as distinct types mostly for historical reasons:
461 * they have nonstandard I/O behavior which we don't want to change for fear
462 * of breaking applications that look at the system catalogs. There is also
463 * an implementation issue for oidvector: it's part of the primary key for
464 * pg_proc, and we can't use the normal btree array support routines for that
465 * without circularity.
469 int32 vl_len_; /* these fields must match ArrayType! */
470 int ndim; /* always 1 for int2vector */
471 int32 dataoffset; /* always 0 for int2vector */
475 int16 values[FLEXIBLE_ARRAY_MEMBER];
480 int32 vl_len_; /* these fields must match ArrayType! */
481 int ndim; /* always 1 for oidvector */
482 int32 dataoffset; /* always 0 for oidvector */
486 Oid values[FLEXIBLE_ARRAY_MEMBER];
490 * Representation of a Name: effectively just a C string, but null-padded to
491 * exactly NAMEDATALEN bytes. The use of a struct is historical.
493 typedef struct nameData
495 char data[NAMEDATALEN];
497 typedef NameData *Name;
499 #define NameStr(name) ((name).data)
502 * Support macros for escaping strings. escape_backslash should be TRUE
503 * if generating a non-standard-conforming string. Prefixing a string
504 * with ESCAPE_STRING_SYNTAX guarantees it is non-standard-conforming.
505 * Beware of multiple evaluation of the "ch" argument!
507 #define SQL_STR_DOUBLE(ch, escape_backslash) \
508 ((ch) == '\'' || ((ch) == '\\' && (escape_backslash)))
510 #define ESCAPE_STRING_SYNTAX 'E'
512 /* ----------------------------------------------------------------
513 * Section 4: IsValid macros for system types
514 * ----------------------------------------------------------------
518 * True iff bool is valid.
520 #define BoolIsValid(boolean) ((boolean) == false || (boolean) == true)
524 * True iff pointer is valid.
526 #define PointerIsValid(pointer) ((const void*)(pointer) != NULL)
530 * True iff pointer is properly aligned to point to the given type.
532 #define PointerIsAligned(pointer, type) \
533 (((uintptr_t)(pointer) % (sizeof (type))) == 0)
535 #define OidIsValid(objectId) ((bool) ((objectId) != InvalidOid))
537 #define RegProcedureIsValid(p) OidIsValid(p)
540 /* ----------------------------------------------------------------
541 * Section 5: offsetof, lengthof, endof, alignment
542 * ----------------------------------------------------------------
546 * Offset of a structure/union field within that structure/union.
548 * XXX This is supposed to be part of stddef.h, but isn't on
549 * some systems (like SunOS 4).
552 #define offsetof(type, field) ((long) &((type *)0)->field)
553 #endif /* offsetof */
557 * Number of elements in an array.
559 #define lengthof(array) (sizeof (array) / sizeof ((array)[0]))
563 * Address of the element one past the last in an array.
565 #define endof(array) (&(array)[lengthof(array)])
568 * Alignment macros: align a length or address appropriately for a given type.
569 * The fooALIGN() macros round up to a multiple of the required alignment,
570 * while the fooALIGN_DOWN() macros round down. The latter are more useful
571 * for problems like "how many X-sized structures will fit in a page?".
573 * NOTE: TYPEALIGN[_DOWN] will not work if ALIGNVAL is not a power of 2.
574 * That case seems extremely unlikely to be needed in practice, however.
578 #define TYPEALIGN(ALIGNVAL,LEN) \
579 (((uintptr_t) (LEN) + ((ALIGNVAL) - 1)) & ~((uintptr_t) ((ALIGNVAL) - 1)))
581 #define SHORTALIGN(LEN) TYPEALIGN(ALIGNOF_SHORT, (LEN))
582 #define INTALIGN(LEN) TYPEALIGN(ALIGNOF_INT, (LEN))
583 #define LONGALIGN(LEN) TYPEALIGN(ALIGNOF_LONG, (LEN))
584 #define DOUBLEALIGN(LEN) TYPEALIGN(ALIGNOF_DOUBLE, (LEN))
585 #define MAXALIGN(LEN) TYPEALIGN(MAXIMUM_ALIGNOF, (LEN))
586 /* MAXALIGN covers only built-in types, not buffers */
587 #define BUFFERALIGN(LEN) TYPEALIGN(ALIGNOF_BUFFER, (LEN))
588 #define CACHELINEALIGN(LEN) TYPEALIGN(PG_CACHE_LINE_SIZE, (LEN))
590 #define TYPEALIGN_DOWN(ALIGNVAL,LEN) \
591 (((uintptr_t) (LEN)) & ~((uintptr_t) ((ALIGNVAL) - 1)))
593 #define SHORTALIGN_DOWN(LEN) TYPEALIGN_DOWN(ALIGNOF_SHORT, (LEN))
594 #define INTALIGN_DOWN(LEN) TYPEALIGN_DOWN(ALIGNOF_INT, (LEN))
595 #define LONGALIGN_DOWN(LEN) TYPEALIGN_DOWN(ALIGNOF_LONG, (LEN))
596 #define DOUBLEALIGN_DOWN(LEN) TYPEALIGN_DOWN(ALIGNOF_DOUBLE, (LEN))
597 #define MAXALIGN_DOWN(LEN) TYPEALIGN_DOWN(MAXIMUM_ALIGNOF, (LEN))
600 * The above macros will not work with types wider than uintptr_t, like with
601 * uint64 on 32-bit platforms. That's not problem for the usual use where a
602 * pointer or a length is aligned, but for the odd case that you need to
603 * align something (potentially) wider, use TYPEALIGN64.
605 #define TYPEALIGN64(ALIGNVAL,LEN) \
606 (((uint64) (LEN) + ((ALIGNVAL) - 1)) & ~((uint64) ((ALIGNVAL) - 1)))
608 /* we don't currently need wider versions of the other ALIGN macros */
609 #define MAXALIGN64(LEN) TYPEALIGN64(MAXIMUM_ALIGNOF, (LEN))
614 * GCC: https://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
615 * GCC: https://gcc.gnu.org/onlinedocs/gcc/Type-Attributes.html
616 * Sunpro: https://docs.oracle.com/cd/E18659_01/html/821-1384/gjzke.html
617 * XLC: http://www-01.ibm.com/support/knowledgecenter/SSGH2K_11.1.0/com.ibm.xlc111.aix.doc/language_ref/function_attributes.html
618 * XLC: http://www-01.ibm.com/support/knowledgecenter/SSGH2K_11.1.0/com.ibm.xlc111.aix.doc/language_ref/type_attrib.html
622 /* only GCC supports the unused attribute */
624 #define pg_attribute_unused() __attribute__((unused))
626 #define pg_attribute_unused()
629 /* GCC and XLC support format attributes */
630 #if defined(__GNUC__) || defined(__IBMC__)
631 #define pg_attribute_format_arg(a) __attribute__((format_arg(a)))
632 #define pg_attribute_printf(f,a) __attribute__((format(PG_PRINTF_ATTRIBUTE, f, a)))
634 #define pg_attribute_format_arg(a)
635 #define pg_attribute_printf(f,a)
638 /* GCC, Sunpro and XLC support aligned, packed and noreturn */
639 #if defined(__GNUC__) || defined(__SUNPRO_C) || defined(__IBMC__)
640 #define pg_attribute_aligned(a) __attribute__((aligned(a)))
641 #define pg_attribute_noreturn() __attribute__((noreturn))
642 #define pg_attribute_packed() __attribute__((packed))
643 #define HAVE_PG_ATTRIBUTE_NORETURN 1
646 * NB: aligned and packed are not given default definitions because they
647 * affect code functionality; they *must* be implemented by the compiler
648 * if they are to be used.
650 #define pg_attribute_noreturn()
653 /* ----------------------------------------------------------------
654 * Section 6: assertions
655 * ----------------------------------------------------------------
659 * USE_ASSERT_CHECKING, if defined, turns on all the assertions.
662 * It should _NOT_ be defined in releases or in benchmark copies
666 * Assert() can be used in both frontend and backend code. In frontend code it
667 * just calls the standard assert, if it's available. If use of assertions is
668 * not configured, it does nothing.
670 #ifndef USE_ASSERT_CHECKING
672 #define Assert(condition) ((void)true)
673 #define AssertMacro(condition) ((void)true)
674 #define AssertArg(condition) ((void)true)
675 #define AssertState(condition) ((void)true)
676 #define AssertPointerAlignment(ptr, bndr) ((void)true)
677 #define Trap(condition, errorType) ((void)true)
678 #define TrapMacro(condition, errorType) (true)
680 #elif defined(FRONTEND)
683 #define Assert(p) assert(p)
684 #define AssertMacro(p) ((void) assert(p))
685 #define AssertArg(condition) assert(condition)
686 #define AssertState(condition) assert(condition)
687 #define AssertPointerAlignment(ptr, bndr) ((void)true)
688 #else /* USE_ASSERT_CHECKING && !FRONTEND */
692 * Generates an exception if the given condition is true.
694 #define Trap(condition, errorType) \
697 ExceptionalCondition(CppAsString(condition), (errorType), \
698 __FILE__, __LINE__); \
702 * TrapMacro is the same as Trap but it's intended for use in macros:
704 * #define foo(x) (AssertMacro(x != 0), bar(x))
708 #define TrapMacro(condition, errorType) \
709 ((bool) (! (condition) || \
710 (ExceptionalCondition(CppAsString(condition), (errorType), \
711 __FILE__, __LINE__), 0)))
713 #define Assert(condition) \
714 Trap(!(condition), "FailedAssertion")
716 #define AssertMacro(condition) \
717 ((void) TrapMacro(!(condition), "FailedAssertion"))
719 #define AssertArg(condition) \
720 Trap(!(condition), "BadArgument")
722 #define AssertState(condition) \
723 Trap(!(condition), "BadState")
726 * Check that `ptr' is `bndr' aligned.
728 #define AssertPointerAlignment(ptr, bndr) \
729 Trap(TYPEALIGN(bndr, (uintptr_t)(ptr)) != (uintptr_t)(ptr), \
732 #endif /* USE_ASSERT_CHECKING && !FRONTEND */
735 * Macros to support compile-time assertion checks.
737 * If the "condition" (a compile-time-constant expression) evaluates to false,
738 * throw a compile error using the "errmessage" (a string literal).
740 * gcc 4.6 and up supports _Static_assert(), but there are bizarre syntactic
741 * placement restrictions. These macros make it safe to use as a statement
742 * or in an expression, respectively.
744 * Otherwise we fall back on a kluge that assumes the compiler will complain
745 * about a negative width for a struct bit-field. This will not include a
746 * helpful error message, but it beats not getting an error at all.
748 #ifdef HAVE__STATIC_ASSERT
749 #define StaticAssertStmt(condition, errmessage) \
750 do { _Static_assert(condition, errmessage); } while(0)
751 #define StaticAssertExpr(condition, errmessage) \
752 ({ StaticAssertStmt(condition, errmessage); true; })
753 #else /* !HAVE__STATIC_ASSERT */
754 #define StaticAssertStmt(condition, errmessage) \
755 ((void) sizeof(struct { int static_assert_failure : (condition) ? 1 : -1; }))
756 #define StaticAssertExpr(condition, errmessage) \
757 StaticAssertStmt(condition, errmessage)
758 #endif /* HAVE__STATIC_ASSERT */
762 * Compile-time checks that a variable (or expression) has the specified type.
764 * AssertVariableIsOfType() can be used as a statement.
765 * AssertVariableIsOfTypeMacro() is intended for use in macros, eg
766 * #define foo(x) (AssertVariableIsOfTypeMacro(x, int), bar(x))
768 * If we don't have __builtin_types_compatible_p, we can still assert that
769 * the types have the same size. This is far from ideal (especially on 32-bit
770 * platforms) but it provides at least some coverage.
772 #ifdef HAVE__BUILTIN_TYPES_COMPATIBLE_P
773 #define AssertVariableIsOfType(varname, typename) \
774 StaticAssertStmt(__builtin_types_compatible_p(__typeof__(varname), typename), \
775 CppAsString(varname) " does not have type " CppAsString(typename))
776 #define AssertVariableIsOfTypeMacro(varname, typename) \
777 ((void) StaticAssertExpr(__builtin_types_compatible_p(__typeof__(varname), typename), \
778 CppAsString(varname) " does not have type " CppAsString(typename)))
779 #else /* !HAVE__BUILTIN_TYPES_COMPATIBLE_P */
780 #define AssertVariableIsOfType(varname, typename) \
781 StaticAssertStmt(sizeof(varname) == sizeof(typename), \
782 CppAsString(varname) " does not have type " CppAsString(typename))
783 #define AssertVariableIsOfTypeMacro(varname, typename) \
784 ((void) StaticAssertExpr(sizeof(varname) == sizeof(typename), \
785 CppAsString(varname) " does not have type " CppAsString(typename)))
786 #endif /* HAVE__BUILTIN_TYPES_COMPATIBLE_P */
789 /* ----------------------------------------------------------------
790 * Section 7: widely useful macros
791 * ----------------------------------------------------------------
795 * Return the maximum of two numbers.
797 #define Max(x, y) ((x) > (y) ? (x) : (y))
801 * Return the minimum of two numbers.
803 #define Min(x, y) ((x) < (y) ? (x) : (y))
807 * Return the absolute value of the argument.
809 #define Abs(x) ((x) >= 0 ? (x) : -(x))
813 * Like standard library function strncpy(), except that result string
814 * is guaranteed to be null-terminated --- that is, at most N-1 bytes
815 * of the source string will be kept.
816 * Also, the macro returns no result (too hard to do that without
817 * evaluating the arguments multiple times, which seems worse).
819 * BTW: when you need to copy a non-null-terminated string (like a text
820 * datum) and add a null, do not do it with StrNCpy(..., len+1). That
821 * might seem to work, but it fetches one byte more than there is in the
822 * text object. One fine day you'll have a SIGSEGV because there isn't
823 * another byte before the end of memory. Don't laugh, we've had real
824 * live bug reports from real live users over exactly this mistake.
825 * Do it honestly with "memcpy(dst,src,len); dst[len] = '\0';", instead.
827 #define StrNCpy(dst,src,len) \
830 char * _dst = (dst); \
835 strncpy(_dst, (src), _len); \
836 _dst[_len-1] = '\0'; \
841 /* Get a bit mask of the bits set in non-long aligned addresses */
842 #define LONG_ALIGN_MASK (sizeof(long) - 1)
846 * Exactly the same as standard library function memset(), but considerably
847 * faster for zeroing small word-aligned structures (such as parsetree nodes).
848 * This has to be a macro because the main point is to avoid function-call
849 * overhead. However, we have also found that the loop is faster than
850 * native libc memset() on some platforms, even those with assembler
851 * memset() functions. More research needs to be done, perhaps with
852 * MEMSET_LOOP_LIMIT tests in configure.
854 #define MemSet(start, val, len) \
857 /* must be void* because we don't know if it is integer aligned yet */ \
858 void *_vstart = (void *) (start); \
862 if ((((uintptr_t) _vstart) & LONG_ALIGN_MASK) == 0 && \
863 (_len & LONG_ALIGN_MASK) == 0 && \
865 _len <= MEMSET_LOOP_LIMIT && \
867 * If MEMSET_LOOP_LIMIT == 0, optimizer should find \
868 * the whole "if" false at compile time. \
870 MEMSET_LOOP_LIMIT != 0) \
872 long *_start = (long *) _vstart; \
873 long *_stop = (long *) ((char *) _start + _len); \
874 while (_start < _stop) \
878 memset(_vstart, _val, _len); \
882 * MemSetAligned is the same as MemSet except it omits the test to see if
883 * "start" is word-aligned. This is okay to use if the caller knows a-priori
884 * that the pointer is suitably aligned (typically, because he just got it
885 * from palloc(), which always delivers a max-aligned pointer).
887 #define MemSetAligned(start, val, len) \
890 long *_start = (long *) (start); \
894 if ((_len & LONG_ALIGN_MASK) == 0 && \
896 _len <= MEMSET_LOOP_LIMIT && \
897 MEMSET_LOOP_LIMIT != 0) \
899 long *_stop = (long *) ((char *) _start + _len); \
900 while (_start < _stop) \
904 memset(_start, _val, _len); \
909 * MemSetTest/MemSetLoop are a variant version that allow all the tests in
910 * MemSet to be done at compile time in cases where "val" and "len" are
911 * constants *and* we know the "start" pointer must be word-aligned.
912 * If MemSetTest succeeds, then it is okay to use MemSetLoop, otherwise use
913 * MemSetAligned. Beware of multiple evaluations of the arguments when using
916 #define MemSetTest(val, len) \
917 ( ((len) & LONG_ALIGN_MASK) == 0 && \
918 (len) <= MEMSET_LOOP_LIMIT && \
919 MEMSET_LOOP_LIMIT != 0 && \
922 #define MemSetLoop(start, val, len) \
925 long * _start = (long *) (start); \
926 long * _stop = (long *) ((char *) _start + (Size) (len)); \
928 while (_start < _stop) \
934 * Mark a point as unreachable in a portable fashion. This should preferably
935 * be something that the compiler understands, to aid code generation.
936 * In assert-enabled builds, we prefer abort() for debugging reasons.
938 #if defined(HAVE__BUILTIN_UNREACHABLE) && !defined(USE_ASSERT_CHECKING)
939 #define pg_unreachable() __builtin_unreachable()
940 #elif defined(_MSC_VER) && !defined(USE_ASSERT_CHECKING)
941 #define pg_unreachable() __assume(0)
943 #define pg_unreachable() abort()
948 * Function inlining support -- Allow modules to define functions that may be
949 * inlined, if the compiler supports it.
951 * The function bodies must be defined in the module header prefixed by
952 * STATIC_IF_INLINE, protected by a cpp symbol that the module's .c file must
953 * define. If the compiler doesn't support inline functions, the function
954 * definitions are pulled in by the .c file as regular (not inline) symbols.
956 * The header must also declare the functions' prototypes, protected by
960 /* declarations which are only visible when not inlining and in the .c file */
962 #define STATIC_IF_INLINE static inline
964 #define STATIC_IF_INLINE
965 #endif /* PG_USE_INLINE */
967 /* declarations which are marked inline when inlining, extern otherwise */
969 #define STATIC_IF_INLINE_DECLARE static inline
971 #define STATIC_IF_INLINE_DECLARE extern
972 #endif /* PG_USE_INLINE */
975 /* ----------------------------------------------------------------
976 * Section 8: random stuff
977 * ----------------------------------------------------------------
981 #define HIGHBIT (0x80)
982 #define IS_HIGHBIT_SET(ch) ((unsigned char)(ch) & HIGHBIT)
984 #define STATUS_OK (0)
985 #define STATUS_ERROR (-1)
986 #define STATUS_EOF (-2)
987 #define STATUS_FOUND (1)
988 #define STATUS_WAITING (2)
992 * Append PG_USED_FOR_ASSERTS_ONLY to definitions of variables that are only
993 * used in assert-enabled builds, to avoid compiler warnings about unused
994 * variables in assert-disabled builds.
996 #ifdef USE_ASSERT_CHECKING
997 #define PG_USED_FOR_ASSERTS_ONLY
999 #define PG_USED_FOR_ASSERTS_ONLY pg_attribute_unused()
1003 /* gettext domain name mangling */
1006 * To better support parallel installations of major PostgeSQL
1007 * versions as well as parallel installations of major library soname
1008 * versions, we mangle the gettext domain name by appending those
1009 * version numbers. The coding rule ought to be that whereever the
1010 * domain name is mentioned as a literal, it must be wrapped into
1011 * PG_TEXTDOMAIN(). The macros below do not work on non-literals; but
1012 * that is somewhat intentional because it avoids having to worry
1013 * about multiple states of premangling and postmangling as the values
1014 * are being passed around.
1016 * Make sure this matches the installation rules in nls-global.mk.
1019 /* need a second indirection because we want to stringize the macro value, not the name */
1020 #define CppAsString2(x) CppAsString(x)
1022 #ifdef SO_MAJOR_VERSION
1023 #define PG_TEXTDOMAIN(domain) (domain CppAsString2(SO_MAJOR_VERSION) "-" PG_MAJORVERSION)
1025 #define PG_TEXTDOMAIN(domain) (domain "-" PG_MAJORVERSION)
1029 /* ----------------------------------------------------------------
1030 * Section 9: system-specific hacks
1032 * This should be limited to things that absolutely have to be
1033 * included in every source file. The port-specific header file
1034 * is usually a better place for this sort of thing.
1035 * ----------------------------------------------------------------
1039 * NOTE: this is also used for opening text files.
1040 * WIN32 treats Control-Z as EOF in files opened in text mode.
1041 * Therefore, we open files in binary mode on Win32 so we can read
1042 * literal control-Z. The other affect is that we see CRLF, but
1043 * that is OK because we can already handle those cleanly.
1045 #if defined(WIN32) || defined(__CYGWIN__)
1046 #define PG_BINARY O_BINARY
1047 #define PG_BINARY_A "ab"
1048 #define PG_BINARY_R "rb"
1049 #define PG_BINARY_W "wb"
1052 #define PG_BINARY_A "a"
1053 #define PG_BINARY_R "r"
1054 #define PG_BINARY_W "w"
1058 * Provide prototypes for routines not present in a particular machine's
1059 * standard C library.
1062 #if !HAVE_DECL_SNPRINTF
1063 extern int snprintf(char *str, size_t count, const char *fmt,...) pg_attribute_printf(3, 4);
1066 #if !HAVE_DECL_VSNPRINTF
1067 extern int vsnprintf(char *str, size_t count, const char *fmt, va_list args);
1070 #if !defined(HAVE_MEMMOVE) && !defined(memmove)
1071 #define memmove(d, s, c) bcopy(s, d, c)
1074 /* no special DLL markers on most ports */
1083 * The following is used as the arg list for signal handlers. Any ports
1084 * that take something other than an int argument should override this in
1085 * their pg_config_os.h file. Note that variable names are required
1086 * because it is used in both the prototypes as well as the definitions.
1087 * Note also the long name. We expect that this won't collide with
1088 * other names causing compiler warnings.
1092 #define SIGNAL_ARGS int postgres_signal_arg
1096 * When there is no sigsetjmp, its functionality is provided by plain
1097 * setjmp. Incidentally, nothing provides setjmp's functionality in
1100 #ifndef HAVE_SIGSETJMP
1101 #define sigjmp_buf jmp_buf
1102 #define sigsetjmp(x,y) setjmp(x)
1103 #define siglongjmp longjmp
1106 #if defined(HAVE_FDATASYNC) && !HAVE_DECL_FDATASYNC
1107 extern int fdatasync(int fildes);
1110 /* If strtoq() exists, rename it to the more standard strtoll() */
1111 #if defined(HAVE_LONG_LONG_INT_64) && !defined(HAVE_STRTOLL) && defined(HAVE_STRTOQ)
1112 #define strtoll strtoq
1113 #define HAVE_STRTOLL 1
1116 /* If strtouq() exists, rename it to the more standard strtoull() */
1117 #if defined(HAVE_LONG_LONG_INT_64) && !defined(HAVE_STRTOULL) && defined(HAVE_STRTOUQ)
1118 #define strtoull strtouq
1119 #define HAVE_STRTOULL 1
1123 * We assume if we have these two functions, we have their friends too, and
1124 * can use the wide-character functions.
1126 #if defined(HAVE_WCSTOMBS) && defined(HAVE_TOWLOWER)
1127 #define USE_WIDE_UPPER_LOWER
1130 /* EXEC_BACKEND defines */
1132 #define NON_EXEC_STATIC
1134 #define NON_EXEC_STATIC static
1137 /* /port compatibility functions */