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 * Force disable inlining if PG_FORCE_DISABLE_INLINE is defined. This is used
58 * to work around compiler bugs and might also be useful for investigatory
61 * This is done early (in slightly the wrong section) for two reasons: a) we
62 * don't want to include headers with different settings of this b)
63 * functionality later in this file might want to rely on inline functions.
65 #ifdef PG_FORCE_DISABLE_INLINE
71 * We always rely on the WIN32 macro being set by our build system,
72 * but _WIN32 is the compiler pre-defined macro. So make sure we define
73 * WIN32 whenever _WIN32 is set, to facilitate standalone building.
75 #if defined(_WIN32) && !defined(WIN32)
79 #if !defined(WIN32) && !defined(__CYGWIN__) /* win32 includes further down */
80 #include "pg_config_os.h" /* must be before any system header files */
83 #if _MSC_VER >= 1400 || defined(HAVE_CRTDEFS_H)
84 #define errcode __msvc_errcode
90 * We have to include stdlib.h here because it defines many of these macros
91 * on some platforms, and we only want our definitions used if stdlib.h doesn't
92 * have its own. The same goes for stddef and stdarg if present.
100 #ifdef HAVE_STRINGS_H
106 #include <sys/types.h>
109 #if defined(WIN32) || defined(__CYGWIN__)
110 #include <fcntl.h> /* ensure O_BINARY is available */
113 #if defined(WIN32) || defined(__CYGWIN__)
114 /* We have to redefine some system functions after they are included above. */
115 #include "pg_config_os.h"
118 /* Must be before gettext() games below */
121 #define _(x) gettext(x)
126 #define gettext(x) (x)
127 #define dgettext(d,x) (x)
128 #define ngettext(s,p,n) ((n) == 1 ? (s) : (p))
129 #define dngettext(d,s,p,n) ((n) == 1 ? (s) : (p))
133 * Use this to mark string constants as needing translation at some later
134 * time, rather than immediately. This is useful for cases where you need
135 * access to the original string and translated string, and for cases where
136 * immediate translation is not possible, like when initializing global
138 * http://www.gnu.org/software/autoconf/manual/gettext/Special-cases.html
140 #define gettext_noop(x) (x)
143 /* ----------------------------------------------------------------
144 * Section 1: hacks to cope with non-ANSI C compilers
146 * type prefixes (const, signed, volatile, inline) are handled in pg_config.h.
147 * ----------------------------------------------------------------
152 * Convert the argument to a string, using the C preprocessor.
154 * Concatenate two arguments together, using the C preprocessor.
156 * Note: There used to be support here for pre-ANSI C compilers that didn't
157 * support # and ##. Nowadays, these macros are just for clarity and/or
158 * backward compatibility with existing PostgreSQL code.
160 #define CppAsString(identifier) #identifier
161 #define CppConcat(x, y) x##y
164 * dummyret is used to set return values in macros that use ?: to make
165 * assignments. gcc wants these to be void, other compilers like char
167 #ifdef __GNUC__ /* GNU cc */
168 #define dummyret void
170 #define dummyret char
173 /* ----------------------------------------------------------------
174 * Section 2: bool, true, false, TRUE, FALSE, NULL
175 * ----------------------------------------------------------------
180 * Boolean value, either true or false.
182 * XXX for C++ compilers, we assume the compiler has a compatible
183 * built-in definition of bool.
193 #define true ((bool) 1)
197 #define false ((bool) 0)
201 typedef bool *BoolPtr;
216 #define NULL ((void *) 0)
220 /* ----------------------------------------------------------------
221 * Section 3: standard system types
222 * ----------------------------------------------------------------
227 * Variable holding address of any memory resident object.
229 * XXX Pointer arithmetic is done with this, so it can't be void *
230 * under "true" ANSI compilers.
232 typedef char *Pointer;
236 * Signed integer, EXACTLY N BITS IN SIZE,
237 * used for numerical computations and the
238 * frontend/backend protocol.
241 typedef signed char int8; /* == 8 bits */
242 typedef signed short int16; /* == 16 bits */
243 typedef signed int int32; /* == 32 bits */
244 #endif /* not HAVE_INT8 */
248 * Unsigned integer, EXACTLY N BITS IN SIZE,
249 * used for numerical computations and the
250 * frontend/backend protocol.
253 typedef unsigned char uint8; /* == 8 bits */
254 typedef unsigned short uint16; /* == 16 bits */
255 typedef unsigned int uint32; /* == 32 bits */
256 #endif /* not HAVE_UINT8 */
260 * Unit of bitwise operation, AT LEAST N BITS IN SIZE.
262 typedef uint8 bits8; /* >= 8 bits */
263 typedef uint16 bits16; /* >= 16 bits */
264 typedef uint32 bits32; /* >= 32 bits */
269 #ifdef HAVE_LONG_INT_64
270 /* Plain "long int" fits, use it */
273 typedef long int int64;
276 typedef unsigned long int uint64;
278 #elif defined(HAVE_LONG_LONG_INT_64)
279 /* We have working support for "long long int", use that */
282 typedef long long int int64;
285 typedef unsigned long long int uint64;
288 /* neither HAVE_LONG_INT_64 nor HAVE_LONG_LONG_INT_64 */
289 #error must have a working 64-bit integer datatype
292 /* Decide if we need to decorate 64-bit constants */
293 #ifdef HAVE_LL_CONSTANTS
294 #define INT64CONST(x) ((int64) x##LL)
295 #define UINT64CONST(x) ((uint64) x##ULL)
297 #define INT64CONST(x) ((int64) x)
298 #define UINT64CONST(x) ((uint64) x)
301 /* snprintf format strings to use for 64-bit integers */
302 #define INT64_FORMAT "%" INT64_MODIFIER "d"
303 #define UINT64_FORMAT "%" INT64_MODIFIER "u"
306 * 128-bit signed and unsigned integers
307 * There currently is only a limited support for the type. E.g. 128bit
308 * literals and snprintf are not supported; but math is.
310 #if defined(PG_INT128_TYPE)
312 typedef PG_INT128_TYPE int128;
313 typedef unsigned PG_INT128_TYPE uint128;
317 * stdint.h limits aren't guaranteed to be present and aren't guaranteed to
318 * have compatible types with our fixed width types. So just define our own.
320 #define PG_INT8_MIN (-0x7F-1)
321 #define PG_INT8_MAX (0x7F)
322 #define PG_UINT8_MAX (0xFF)
323 #define PG_INT16_MIN (-0x7FFF-1)
324 #define PG_INT16_MAX (0x7FFF)
325 #define PG_UINT16_MAX (0xFFFF)
326 #define PG_INT32_MIN (-0x7FFFFFFF-1)
327 #define PG_INT32_MAX (0x7FFFFFFF)
328 #define PG_UINT32_MAX (0xFFFFFFFF)
329 #define PG_INT64_MIN (-INT64CONST(0x7FFFFFFFFFFFFFFF) - 1)
330 #define PG_INT64_MAX INT64CONST(0x7FFFFFFFFFFFFFFF)
331 #define PG_UINT64_MAX UINT64CONST(0xFFFFFFFFFFFFFFFF)
333 /* Select timestamp representation (float8 or int64) */
334 #ifdef USE_INTEGER_DATETIMES
335 #define HAVE_INT64_TIMESTAMP
338 /* sig_atomic_t is required by ANSI C, but may be missing on old platforms */
339 #ifndef HAVE_SIG_ATOMIC_T
340 typedef int sig_atomic_t;
345 * Size of any memory resident object, as returned by sizeof.
351 * Index into any memory resident array.
354 * Indices are non negative.
356 typedef unsigned int Index;
360 * Offset into any memory resident array.
363 * This differs from an Index in that an Index is always
364 * non negative, whereas Offset may be negative.
366 typedef signed int Offset;
369 * Common Postgres datatype names (as used in the catalogs)
371 typedef float float4;
372 typedef double float8;
375 * Oid, RegProcedure, TransactionId, SubTransactionId, MultiXactId,
379 /* typedef Oid is in postgres_ext.h */
382 * regproc is the type name used in the include/catalog headers, but
383 * RegProcedure is the preferred name in C code.
386 typedef regproc RegProcedure;
388 typedef uint32 TransactionId;
390 typedef uint32 LocalTransactionId;
392 typedef uint32 SubTransactionId;
394 #define InvalidSubTransactionId ((SubTransactionId) 0)
395 #define TopSubTransactionId ((SubTransactionId) 1)
397 /* MultiXactId must be equivalent to TransactionId, to fit in t_xmax */
398 typedef TransactionId MultiXactId;
400 typedef uint32 MultiXactOffset;
402 typedef uint32 CommandId;
404 #define FirstCommandId ((CommandId) 0)
405 #define InvalidCommandId (~(CommandId)0)
408 * Array indexing support
417 * Variable-length datatypes all share the 'struct varlena' header.
419 * NOTE: for TOASTable types, this is an oversimplification, since the value
420 * may be compressed or moved out-of-line. However datatype-specific routines
421 * are mostly content to deal with de-TOASTed values only, and of course
422 * client-side routines should never see a TOASTed value. But even in a
423 * de-TOASTed value, beware of touching vl_len_ directly, as its representation
424 * is no longer convenient. It's recommended that code always use the VARDATA,
425 * VARSIZE, and SET_VARSIZE macros instead of relying on direct mentions of
426 * the struct fields. See postgres.h for details of the TOASTed form.
431 char vl_len_[4]; /* Do not touch this field directly! */
432 char vl_dat[FLEXIBLE_ARRAY_MEMBER]; /* Data content is here */
435 #define VARHDRSZ ((int32) sizeof(int32))
438 * These widely-used datatypes are just a varlena header and the data bytes.
439 * There is no terminating null or anything like that --- the data length is
440 * always VARSIZE(ptr) - VARHDRSZ.
442 typedef struct varlena bytea;
443 typedef struct varlena text;
444 typedef struct varlena BpChar; /* blank-padded char, ie SQL char(n) */
445 typedef struct varlena VarChar; /* var-length char, ie SQL varchar(n) */
448 * Specialized array types. These are physically laid out just the same
449 * as regular arrays (so that the regular array subscripting code works
450 * with them). They exist as distinct types mostly for historical reasons:
451 * they have nonstandard I/O behavior which we don't want to change for fear
452 * of breaking applications that look at the system catalogs. There is also
453 * an implementation issue for oidvector: it's part of the primary key for
454 * pg_proc, and we can't use the normal btree array support routines for that
455 * without circularity.
459 int32 vl_len_; /* these fields must match ArrayType! */
460 int ndim; /* always 1 for int2vector */
461 int32 dataoffset; /* always 0 for int2vector */
465 int16 values[FLEXIBLE_ARRAY_MEMBER];
470 int32 vl_len_; /* these fields must match ArrayType! */
471 int ndim; /* always 1 for oidvector */
472 int32 dataoffset; /* always 0 for oidvector */
476 Oid values[FLEXIBLE_ARRAY_MEMBER];
480 * Representation of a Name: effectively just a C string, but null-padded to
481 * exactly NAMEDATALEN bytes. The use of a struct is historical.
483 typedef struct nameData
485 char data[NAMEDATALEN];
487 typedef NameData *Name;
489 #define NameStr(name) ((name).data)
492 * Support macros for escaping strings. escape_backslash should be TRUE
493 * if generating a non-standard-conforming string. Prefixing a string
494 * with ESCAPE_STRING_SYNTAX guarantees it is non-standard-conforming.
495 * Beware of multiple evaluation of the "ch" argument!
497 #define SQL_STR_DOUBLE(ch, escape_backslash) \
498 ((ch) == '\'' || ((ch) == '\\' && (escape_backslash)))
500 #define ESCAPE_STRING_SYNTAX 'E'
502 /* ----------------------------------------------------------------
503 * Section 4: IsValid macros for system types
504 * ----------------------------------------------------------------
508 * True iff bool is valid.
510 #define BoolIsValid(boolean) ((boolean) == false || (boolean) == true)
514 * True iff pointer is valid.
516 #define PointerIsValid(pointer) ((const void*)(pointer) != NULL)
520 * True iff pointer is properly aligned to point to the given type.
522 #define PointerIsAligned(pointer, type) \
523 (((uintptr_t)(pointer) % (sizeof (type))) == 0)
525 #define OidIsValid(objectId) ((bool) ((objectId) != InvalidOid))
527 #define RegProcedureIsValid(p) OidIsValid(p)
530 /* ----------------------------------------------------------------
531 * Section 5: offsetof, lengthof, endof, alignment
532 * ----------------------------------------------------------------
536 * Offset of a structure/union field within that structure/union.
538 * XXX This is supposed to be part of stddef.h, but isn't on
539 * some systems (like SunOS 4).
542 #define offsetof(type, field) ((long) &((type *)0)->field)
543 #endif /* offsetof */
547 * Number of elements in an array.
549 #define lengthof(array) (sizeof (array) / sizeof ((array)[0]))
553 * Address of the element one past the last in an array.
555 #define endof(array) (&(array)[lengthof(array)])
558 * Alignment macros: align a length or address appropriately for a given type.
559 * The fooALIGN() macros round up to a multiple of the required alignment,
560 * while the fooALIGN_DOWN() macros round down. The latter are more useful
561 * for problems like "how many X-sized structures will fit in a page?".
563 * NOTE: TYPEALIGN[_DOWN] will not work if ALIGNVAL is not a power of 2.
564 * That case seems extremely unlikely to be needed in practice, however.
568 #define TYPEALIGN(ALIGNVAL,LEN) \
569 (((uintptr_t) (LEN) + ((ALIGNVAL) - 1)) & ~((uintptr_t) ((ALIGNVAL) - 1)))
571 #define SHORTALIGN(LEN) TYPEALIGN(ALIGNOF_SHORT, (LEN))
572 #define INTALIGN(LEN) TYPEALIGN(ALIGNOF_INT, (LEN))
573 #define LONGALIGN(LEN) TYPEALIGN(ALIGNOF_LONG, (LEN))
574 #define DOUBLEALIGN(LEN) TYPEALIGN(ALIGNOF_DOUBLE, (LEN))
575 #define MAXALIGN(LEN) TYPEALIGN(MAXIMUM_ALIGNOF, (LEN))
576 /* MAXALIGN covers only built-in types, not buffers */
577 #define BUFFERALIGN(LEN) TYPEALIGN(ALIGNOF_BUFFER, (LEN))
578 #define CACHELINEALIGN(LEN) TYPEALIGN(PG_CACHE_LINE_SIZE, (LEN))
580 #define TYPEALIGN_DOWN(ALIGNVAL,LEN) \
581 (((uintptr_t) (LEN)) & ~((uintptr_t) ((ALIGNVAL) - 1)))
583 #define SHORTALIGN_DOWN(LEN) TYPEALIGN_DOWN(ALIGNOF_SHORT, (LEN))
584 #define INTALIGN_DOWN(LEN) TYPEALIGN_DOWN(ALIGNOF_INT, (LEN))
585 #define LONGALIGN_DOWN(LEN) TYPEALIGN_DOWN(ALIGNOF_LONG, (LEN))
586 #define DOUBLEALIGN_DOWN(LEN) TYPEALIGN_DOWN(ALIGNOF_DOUBLE, (LEN))
587 #define MAXALIGN_DOWN(LEN) TYPEALIGN_DOWN(MAXIMUM_ALIGNOF, (LEN))
590 * The above macros will not work with types wider than uintptr_t, like with
591 * uint64 on 32-bit platforms. That's not problem for the usual use where a
592 * pointer or a length is aligned, but for the odd case that you need to
593 * align something (potentially) wider, use TYPEALIGN64.
595 #define TYPEALIGN64(ALIGNVAL,LEN) \
596 (((uint64) (LEN) + ((ALIGNVAL) - 1)) & ~((uint64) ((ALIGNVAL) - 1)))
598 /* we don't currently need wider versions of the other ALIGN macros */
599 #define MAXALIGN64(LEN) TYPEALIGN64(MAXIMUM_ALIGNOF, (LEN))
604 * GCC: https://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
605 * GCC: https://gcc.gnu.org/onlinedocs/gcc/Type-Attributes.html
606 * Sunpro: https://docs.oracle.com/cd/E18659_01/html/821-1384/gjzke.html
607 * XLC: http://www-01.ibm.com/support/knowledgecenter/SSGH2K_11.1.0/com.ibm.xlc111.aix.doc/language_ref/function_attributes.html
608 * XLC: http://www-01.ibm.com/support/knowledgecenter/SSGH2K_11.1.0/com.ibm.xlc111.aix.doc/language_ref/type_attrib.html
612 /* only GCC supports the unused attribute */
614 #define pg_attribute_unused() __attribute__((unused))
616 #define pg_attribute_unused()
619 /* GCC and XLC support format attributes */
620 #if defined(__GNUC__) || defined(__IBMC__)
621 #define pg_attribute_format_arg(a) __attribute__((format_arg(a)))
622 #define pg_attribute_printf(f,a) __attribute__((format(PG_PRINTF_ATTRIBUTE, f, a)))
624 #define pg_attribute_format_arg(a)
625 #define pg_attribute_printf(f,a)
628 /* GCC, Sunpro and XLC support aligned, packed and noreturn */
629 #if defined(__GNUC__) || defined(__SUNPRO_C) || defined(__IBMC__)
630 #define pg_attribute_aligned(a) __attribute__((aligned(a)))
631 #define pg_attribute_noreturn() __attribute__((noreturn))
632 #define pg_attribute_packed() __attribute__((packed))
633 #define HAVE_PG_ATTRIBUTE_NORETURN 1
636 * NB: aligned and packed are not given default definitions because they
637 * affect code functionality; they *must* be implemented by the compiler
638 * if they are to be used.
640 #define pg_attribute_noreturn()
643 /* ----------------------------------------------------------------
644 * Section 6: assertions
645 * ----------------------------------------------------------------
649 * USE_ASSERT_CHECKING, if defined, turns on all the assertions.
652 * It should _NOT_ be defined in releases or in benchmark copies
656 * Assert() can be used in both frontend and backend code. In frontend code it
657 * just calls the standard assert, if it's available. If use of assertions is
658 * not configured, it does nothing.
660 #ifndef USE_ASSERT_CHECKING
662 #define Assert(condition) ((void)true)
663 #define AssertMacro(condition) ((void)true)
664 #define AssertArg(condition) ((void)true)
665 #define AssertState(condition) ((void)true)
666 #define AssertPointerAlignment(ptr, bndr) ((void)true)
667 #define Trap(condition, errorType) ((void)true)
668 #define TrapMacro(condition, errorType) (true)
670 #elif defined(FRONTEND)
673 #define Assert(p) assert(p)
674 #define AssertMacro(p) ((void) assert(p))
675 #define AssertArg(condition) assert(condition)
676 #define AssertState(condition) assert(condition)
677 #define AssertPointerAlignment(ptr, bndr) ((void)true)
678 #else /* USE_ASSERT_CHECKING && !FRONTEND */
682 * Generates an exception if the given condition is true.
684 #define Trap(condition, errorType) \
687 ExceptionalCondition(CppAsString(condition), (errorType), \
688 __FILE__, __LINE__); \
692 * TrapMacro is the same as Trap but it's intended for use in macros:
694 * #define foo(x) (AssertMacro(x != 0), bar(x))
698 #define TrapMacro(condition, errorType) \
699 ((bool) (! (condition) || \
700 (ExceptionalCondition(CppAsString(condition), (errorType), \
701 __FILE__, __LINE__), 0)))
703 #define Assert(condition) \
704 Trap(!(condition), "FailedAssertion")
706 #define AssertMacro(condition) \
707 ((void) TrapMacro(!(condition), "FailedAssertion"))
709 #define AssertArg(condition) \
710 Trap(!(condition), "BadArgument")
712 #define AssertState(condition) \
713 Trap(!(condition), "BadState")
716 * Check that `ptr' is `bndr' aligned.
718 #define AssertPointerAlignment(ptr, bndr) \
719 Trap(TYPEALIGN(bndr, (uintptr_t)(ptr)) != (uintptr_t)(ptr), \
722 #endif /* USE_ASSERT_CHECKING && !FRONTEND */
725 * Macros to support compile-time assertion checks.
727 * If the "condition" (a compile-time-constant expression) evaluates to false,
728 * throw a compile error using the "errmessage" (a string literal).
730 * gcc 4.6 and up supports _Static_assert(), but there are bizarre syntactic
731 * placement restrictions. These macros make it safe to use as a statement
732 * or in an expression, respectively.
734 * Otherwise we fall back on a kluge that assumes the compiler will complain
735 * about a negative width for a struct bit-field. This will not include a
736 * helpful error message, but it beats not getting an error at all.
738 #ifdef HAVE__STATIC_ASSERT
739 #define StaticAssertStmt(condition, errmessage) \
740 do { _Static_assert(condition, errmessage); } while(0)
741 #define StaticAssertExpr(condition, errmessage) \
742 ({ StaticAssertStmt(condition, errmessage); true; })
743 #else /* !HAVE__STATIC_ASSERT */
744 #define StaticAssertStmt(condition, errmessage) \
745 ((void) sizeof(struct { int static_assert_failure : (condition) ? 1 : -1; }))
746 #define StaticAssertExpr(condition, errmessage) \
747 StaticAssertStmt(condition, errmessage)
748 #endif /* HAVE__STATIC_ASSERT */
752 * Compile-time checks that a variable (or expression) has the specified type.
754 * AssertVariableIsOfType() can be used as a statement.
755 * AssertVariableIsOfTypeMacro() is intended for use in macros, eg
756 * #define foo(x) (AssertVariableIsOfTypeMacro(x, int), bar(x))
758 * If we don't have __builtin_types_compatible_p, we can still assert that
759 * the types have the same size. This is far from ideal (especially on 32-bit
760 * platforms) but it provides at least some coverage.
762 #ifdef HAVE__BUILTIN_TYPES_COMPATIBLE_P
763 #define AssertVariableIsOfType(varname, typename) \
764 StaticAssertStmt(__builtin_types_compatible_p(__typeof__(varname), typename), \
765 CppAsString(varname) " does not have type " CppAsString(typename))
766 #define AssertVariableIsOfTypeMacro(varname, typename) \
767 ((void) StaticAssertExpr(__builtin_types_compatible_p(__typeof__(varname), typename), \
768 CppAsString(varname) " does not have type " CppAsString(typename)))
769 #else /* !HAVE__BUILTIN_TYPES_COMPATIBLE_P */
770 #define AssertVariableIsOfType(varname, typename) \
771 StaticAssertStmt(sizeof(varname) == sizeof(typename), \
772 CppAsString(varname) " does not have type " CppAsString(typename))
773 #define AssertVariableIsOfTypeMacro(varname, typename) \
774 ((void) StaticAssertExpr(sizeof(varname) == sizeof(typename), \
775 CppAsString(varname) " does not have type " CppAsString(typename)))
776 #endif /* HAVE__BUILTIN_TYPES_COMPATIBLE_P */
779 /* ----------------------------------------------------------------
780 * Section 7: widely useful macros
781 * ----------------------------------------------------------------
785 * Return the maximum of two numbers.
787 #define Max(x, y) ((x) > (y) ? (x) : (y))
791 * Return the minimum of two numbers.
793 #define Min(x, y) ((x) < (y) ? (x) : (y))
797 * Return the absolute value of the argument.
799 #define Abs(x) ((x) >= 0 ? (x) : -(x))
803 * Like standard library function strncpy(), except that result string
804 * is guaranteed to be null-terminated --- that is, at most N-1 bytes
805 * of the source string will be kept.
806 * Also, the macro returns no result (too hard to do that without
807 * evaluating the arguments multiple times, which seems worse).
809 * BTW: when you need to copy a non-null-terminated string (like a text
810 * datum) and add a null, do not do it with StrNCpy(..., len+1). That
811 * might seem to work, but it fetches one byte more than there is in the
812 * text object. One fine day you'll have a SIGSEGV because there isn't
813 * another byte before the end of memory. Don't laugh, we've had real
814 * live bug reports from real live users over exactly this mistake.
815 * Do it honestly with "memcpy(dst,src,len); dst[len] = '\0';", instead.
817 #define StrNCpy(dst,src,len) \
820 char * _dst = (dst); \
825 strncpy(_dst, (src), _len); \
826 _dst[_len-1] = '\0'; \
831 /* Get a bit mask of the bits set in non-long aligned addresses */
832 #define LONG_ALIGN_MASK (sizeof(long) - 1)
836 * Exactly the same as standard library function memset(), but considerably
837 * faster for zeroing small word-aligned structures (such as parsetree nodes).
838 * This has to be a macro because the main point is to avoid function-call
839 * overhead. However, we have also found that the loop is faster than
840 * native libc memset() on some platforms, even those with assembler
841 * memset() functions. More research needs to be done, perhaps with
842 * MEMSET_LOOP_LIMIT tests in configure.
844 #define MemSet(start, val, len) \
847 /* must be void* because we don't know if it is integer aligned yet */ \
848 void *_vstart = (void *) (start); \
852 if ((((uintptr_t) _vstart) & LONG_ALIGN_MASK) == 0 && \
853 (_len & LONG_ALIGN_MASK) == 0 && \
855 _len <= MEMSET_LOOP_LIMIT && \
857 * If MEMSET_LOOP_LIMIT == 0, optimizer should find \
858 * the whole "if" false at compile time. \
860 MEMSET_LOOP_LIMIT != 0) \
862 long *_start = (long *) _vstart; \
863 long *_stop = (long *) ((char *) _start + _len); \
864 while (_start < _stop) \
868 memset(_vstart, _val, _len); \
872 * MemSetAligned is the same as MemSet except it omits the test to see if
873 * "start" is word-aligned. This is okay to use if the caller knows a-priori
874 * that the pointer is suitably aligned (typically, because he just got it
875 * from palloc(), which always delivers a max-aligned pointer).
877 #define MemSetAligned(start, val, len) \
880 long *_start = (long *) (start); \
884 if ((_len & LONG_ALIGN_MASK) == 0 && \
886 _len <= MEMSET_LOOP_LIMIT && \
887 MEMSET_LOOP_LIMIT != 0) \
889 long *_stop = (long *) ((char *) _start + _len); \
890 while (_start < _stop) \
894 memset(_start, _val, _len); \
899 * MemSetTest/MemSetLoop are a variant version that allow all the tests in
900 * MemSet to be done at compile time in cases where "val" and "len" are
901 * constants *and* we know the "start" pointer must be word-aligned.
902 * If MemSetTest succeeds, then it is okay to use MemSetLoop, otherwise use
903 * MemSetAligned. Beware of multiple evaluations of the arguments when using
906 #define MemSetTest(val, len) \
907 ( ((len) & LONG_ALIGN_MASK) == 0 && \
908 (len) <= MEMSET_LOOP_LIMIT && \
909 MEMSET_LOOP_LIMIT != 0 && \
912 #define MemSetLoop(start, val, len) \
915 long * _start = (long *) (start); \
916 long * _stop = (long *) ((char *) _start + (Size) (len)); \
918 while (_start < _stop) \
924 * Mark a point as unreachable in a portable fashion. This should preferably
925 * be something that the compiler understands, to aid code generation.
926 * In assert-enabled builds, we prefer abort() for debugging reasons.
928 #if defined(HAVE__BUILTIN_UNREACHABLE) && !defined(USE_ASSERT_CHECKING)
929 #define pg_unreachable() __builtin_unreachable()
930 #elif defined(_MSC_VER) && !defined(USE_ASSERT_CHECKING)
931 #define pg_unreachable() __assume(0)
933 #define pg_unreachable() abort()
937 /* ----------------------------------------------------------------
938 * Section 8: random stuff
939 * ----------------------------------------------------------------
943 #define HIGHBIT (0x80)
944 #define IS_HIGHBIT_SET(ch) ((unsigned char)(ch) & HIGHBIT)
946 #define STATUS_OK (0)
947 #define STATUS_ERROR (-1)
948 #define STATUS_EOF (-2)
949 #define STATUS_FOUND (1)
950 #define STATUS_WAITING (2)
954 * Append PG_USED_FOR_ASSERTS_ONLY to definitions of variables that are only
955 * used in assert-enabled builds, to avoid compiler warnings about unused
956 * variables in assert-disabled builds.
958 #ifdef USE_ASSERT_CHECKING
959 #define PG_USED_FOR_ASSERTS_ONLY
961 #define PG_USED_FOR_ASSERTS_ONLY pg_attribute_unused()
965 /* gettext domain name mangling */
968 * To better support parallel installations of major PostgeSQL
969 * versions as well as parallel installations of major library soname
970 * versions, we mangle the gettext domain name by appending those
971 * version numbers. The coding rule ought to be that wherever the
972 * domain name is mentioned as a literal, it must be wrapped into
973 * PG_TEXTDOMAIN(). The macros below do not work on non-literals; but
974 * that is somewhat intentional because it avoids having to worry
975 * about multiple states of premangling and postmangling as the values
976 * are being passed around.
978 * Make sure this matches the installation rules in nls-global.mk.
981 /* need a second indirection because we want to stringize the macro value, not the name */
982 #define CppAsString2(x) CppAsString(x)
984 #ifdef SO_MAJOR_VERSION
985 #define PG_TEXTDOMAIN(domain) (domain CppAsString2(SO_MAJOR_VERSION) "-" PG_MAJORVERSION)
987 #define PG_TEXTDOMAIN(domain) (domain "-" PG_MAJORVERSION)
991 /* ----------------------------------------------------------------
992 * Section 9: system-specific hacks
994 * This should be limited to things that absolutely have to be
995 * included in every source file. The port-specific header file
996 * is usually a better place for this sort of thing.
997 * ----------------------------------------------------------------
1001 * NOTE: this is also used for opening text files.
1002 * WIN32 treats Control-Z as EOF in files opened in text mode.
1003 * Therefore, we open files in binary mode on Win32 so we can read
1004 * literal control-Z. The other affect is that we see CRLF, but
1005 * that is OK because we can already handle those cleanly.
1007 #if defined(WIN32) || defined(__CYGWIN__)
1008 #define PG_BINARY O_BINARY
1009 #define PG_BINARY_A "ab"
1010 #define PG_BINARY_R "rb"
1011 #define PG_BINARY_W "wb"
1014 #define PG_BINARY_A "a"
1015 #define PG_BINARY_R "r"
1016 #define PG_BINARY_W "w"
1020 * Provide prototypes for routines not present in a particular machine's
1021 * standard C library.
1024 #if !HAVE_DECL_SNPRINTF
1025 extern int snprintf(char *str, size_t count, const char *fmt,...) pg_attribute_printf(3, 4);
1028 #if !HAVE_DECL_VSNPRINTF
1029 extern int vsnprintf(char *str, size_t count, const char *fmt, va_list args);
1032 #if !defined(HAVE_MEMMOVE) && !defined(memmove)
1033 #define memmove(d, s, c) bcopy(s, d, c)
1036 /* no special DLL markers on most ports */
1045 * The following is used as the arg list for signal handlers. Any ports
1046 * that take something other than an int argument should override this in
1047 * their pg_config_os.h file. Note that variable names are required
1048 * because it is used in both the prototypes as well as the definitions.
1049 * Note also the long name. We expect that this won't collide with
1050 * other names causing compiler warnings.
1054 #define SIGNAL_ARGS int postgres_signal_arg
1058 * When there is no sigsetjmp, its functionality is provided by plain
1059 * setjmp. Incidentally, nothing provides setjmp's functionality in
1062 #ifndef HAVE_SIGSETJMP
1063 #define sigjmp_buf jmp_buf
1064 #define sigsetjmp(x,y) setjmp(x)
1065 #define siglongjmp longjmp
1068 #if defined(HAVE_FDATASYNC) && !HAVE_DECL_FDATASYNC
1069 extern int fdatasync(int fildes);
1072 /* If strtoq() exists, rename it to the more standard strtoll() */
1073 #if defined(HAVE_LONG_LONG_INT_64) && !defined(HAVE_STRTOLL) && defined(HAVE_STRTOQ)
1074 #define strtoll strtoq
1075 #define HAVE_STRTOLL 1
1078 /* If strtouq() exists, rename it to the more standard strtoull() */
1079 #if defined(HAVE_LONG_LONG_INT_64) && !defined(HAVE_STRTOULL) && defined(HAVE_STRTOUQ)
1080 #define strtoull strtouq
1081 #define HAVE_STRTOULL 1
1085 * We assume if we have these two functions, we have their friends too, and
1086 * can use the wide-character functions.
1088 #if defined(HAVE_WCSTOMBS) && defined(HAVE_TOWLOWER)
1089 #define USE_WIDE_UPPER_LOWER
1092 /* EXEC_BACKEND defines */
1094 #define NON_EXEC_STATIC
1096 #define NON_EXEC_STATIC static
1099 /* /port compatibility functions */