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"
105 * Force disable inlining if PG_FORCE_DISABLE_INLINE is defined. This is used
106 * to work around compiler bugs and might also be useful for investigatory
107 * purposes by defining the symbol in the platform's header..
109 * This is done early (in slightly the wrong section) as functionality later
110 * in this file might want to rely on inline functions.
112 #ifdef PG_FORCE_DISABLE_INLINE
117 /* Must be before gettext() games below */
120 #define _(x) gettext(x)
125 #define gettext(x) (x)
126 #define dgettext(d,x) (x)
127 #define ngettext(s,p,n) ((n) == 1 ? (s) : (p))
128 #define dngettext(d,s,p,n) ((n) == 1 ? (s) : (p))
132 * Use this to mark string constants as needing translation at some later
133 * time, rather than immediately. This is useful for cases where you need
134 * access to the original string and translated string, and for cases where
135 * immediate translation is not possible, like when initializing global
137 * http://www.gnu.org/software/autoconf/manual/gettext/Special-cases.html
139 #define gettext_noop(x) (x)
142 /* ----------------------------------------------------------------
143 * Section 1: hacks to cope with non-ANSI C compilers
145 * type prefixes (const, signed, volatile, inline) are handled in pg_config.h.
146 * ----------------------------------------------------------------
151 * Convert the argument to a string, using the C preprocessor.
153 * Concatenate two arguments together, using the C preprocessor.
155 * Note: There used to be support here for pre-ANSI C compilers that didn't
156 * support # and ##. Nowadays, these macros are just for clarity and/or
157 * backward compatibility with existing PostgreSQL code.
159 #define CppAsString(identifier) #identifier
160 #define CppConcat(x, y) x##y
163 * dummyret is used to set return values in macros that use ?: to make
164 * assignments. gcc wants these to be void, other compilers like char
166 #ifdef __GNUC__ /* GNU cc */
167 #define dummyret void
169 #define dummyret char
172 /* ----------------------------------------------------------------
173 * Section 2: bool, true, false, TRUE, FALSE, NULL
174 * ----------------------------------------------------------------
179 * Boolean value, either true or false.
181 * XXX for C++ compilers, we assume the compiler has a compatible
182 * built-in definition of bool.
192 #define true ((bool) 1)
196 #define false ((bool) 0)
200 typedef bool *BoolPtr;
215 #define NULL ((void *) 0)
219 /* ----------------------------------------------------------------
220 * Section 3: standard system types
221 * ----------------------------------------------------------------
226 * Variable holding address of any memory resident object.
228 * XXX Pointer arithmetic is done with this, so it can't be void *
229 * under "true" ANSI compilers.
231 typedef char *Pointer;
235 * Signed integer, EXACTLY N BITS IN SIZE,
236 * used for numerical computations and the
237 * frontend/backend protocol.
240 typedef signed char int8; /* == 8 bits */
241 typedef signed short int16; /* == 16 bits */
242 typedef signed int int32; /* == 32 bits */
243 #endif /* not HAVE_INT8 */
247 * Unsigned integer, EXACTLY N BITS IN SIZE,
248 * used for numerical computations and the
249 * frontend/backend protocol.
252 typedef unsigned char uint8; /* == 8 bits */
253 typedef unsigned short uint16; /* == 16 bits */
254 typedef unsigned int uint32; /* == 32 bits */
255 #endif /* not HAVE_UINT8 */
259 * Unit of bitwise operation, AT LEAST N BITS IN SIZE.
261 typedef uint8 bits8; /* >= 8 bits */
262 typedef uint16 bits16; /* >= 16 bits */
263 typedef uint32 bits32; /* >= 32 bits */
268 #ifdef HAVE_LONG_INT_64
269 /* Plain "long int" fits, use it */
272 typedef long int int64;
275 typedef unsigned long int uint64;
277 #elif defined(HAVE_LONG_LONG_INT_64)
278 /* We have working support for "long long int", use that */
281 typedef long long int int64;
284 typedef unsigned long long int uint64;
287 /* neither HAVE_LONG_INT_64 nor HAVE_LONG_LONG_INT_64 */
288 #error must have a working 64-bit integer datatype
291 /* Decide if we need to decorate 64-bit constants */
292 #ifdef HAVE_LL_CONSTANTS
293 #define INT64CONST(x) ((int64) x##LL)
294 #define UINT64CONST(x) ((uint64) x##ULL)
296 #define INT64CONST(x) ((int64) x)
297 #define UINT64CONST(x) ((uint64) x)
300 /* snprintf format strings to use for 64-bit integers */
301 #define INT64_FORMAT "%" INT64_MODIFIER "d"
302 #define UINT64_FORMAT "%" INT64_MODIFIER "u"
305 * 128-bit signed and unsigned integers
306 * There currently is only a limited support for the type. E.g. 128bit
307 * literals and snprintf are not supported; but math is.
309 #if defined(PG_INT128_TYPE)
311 typedef PG_INT128_TYPE int128;
312 typedef unsigned PG_INT128_TYPE uint128;
316 * stdint.h limits aren't guaranteed to be present and aren't guaranteed to
317 * have compatible types with our fixed width types. So just define our own.
319 #define PG_INT8_MIN (-0x7F-1)
320 #define PG_INT8_MAX (0x7F)
321 #define PG_UINT8_MAX (0xFF)
322 #define PG_INT16_MIN (-0x7FFF-1)
323 #define PG_INT16_MAX (0x7FFF)
324 #define PG_UINT16_MAX (0xFFFF)
325 #define PG_INT32_MIN (-0x7FFFFFFF-1)
326 #define PG_INT32_MAX (0x7FFFFFFF)
327 #define PG_UINT32_MAX (0xFFFFFFFF)
328 #define PG_INT64_MIN (-INT64CONST(0x7FFFFFFFFFFFFFFF) - 1)
329 #define PG_INT64_MAX INT64CONST(0x7FFFFFFFFFFFFFFF)
330 #define PG_UINT64_MAX UINT64CONST(0xFFFFFFFFFFFFFFFF)
332 /* Select timestamp representation (float8 or int64) */
333 #ifdef USE_INTEGER_DATETIMES
334 #define HAVE_INT64_TIMESTAMP
339 * Size of any memory resident object, as returned by sizeof.
345 * Index into any memory resident array.
348 * Indices are non negative.
350 typedef unsigned int Index;
354 * Offset into any memory resident array.
357 * This differs from an Index in that an Index is always
358 * non negative, whereas Offset may be negative.
360 typedef signed int Offset;
363 * Common Postgres datatype names (as used in the catalogs)
365 typedef float float4;
366 typedef double float8;
369 * Oid, RegProcedure, TransactionId, SubTransactionId, MultiXactId,
373 /* typedef Oid is in postgres_ext.h */
376 * regproc is the type name used in the include/catalog headers, but
377 * RegProcedure is the preferred name in C code.
380 typedef regproc RegProcedure;
382 typedef uint32 TransactionId;
384 typedef uint32 LocalTransactionId;
386 typedef uint32 SubTransactionId;
388 #define InvalidSubTransactionId ((SubTransactionId) 0)
389 #define TopSubTransactionId ((SubTransactionId) 1)
391 /* MultiXactId must be equivalent to TransactionId, to fit in t_xmax */
392 typedef TransactionId MultiXactId;
394 typedef uint32 MultiXactOffset;
396 typedef uint32 CommandId;
398 #define FirstCommandId ((CommandId) 0)
399 #define InvalidCommandId (~(CommandId)0)
402 * Array indexing support
411 * Variable-length datatypes all share the 'struct varlena' header.
413 * NOTE: for TOASTable types, this is an oversimplification, since the value
414 * may be compressed or moved out-of-line. However datatype-specific routines
415 * are mostly content to deal with de-TOASTed values only, and of course
416 * client-side routines should never see a TOASTed value. But even in a
417 * de-TOASTed value, beware of touching vl_len_ directly, as its representation
418 * is no longer convenient. It's recommended that code always use the VARDATA,
419 * VARSIZE, and SET_VARSIZE macros instead of relying on direct mentions of
420 * the struct fields. See postgres.h for details of the TOASTed form.
425 char vl_len_[4]; /* Do not touch this field directly! */
426 char vl_dat[FLEXIBLE_ARRAY_MEMBER]; /* Data content is here */
429 #define VARHDRSZ ((int32) sizeof(int32))
432 * These widely-used datatypes are just a varlena header and the data bytes.
433 * There is no terminating null or anything like that --- the data length is
434 * always VARSIZE(ptr) - VARHDRSZ.
436 typedef struct varlena bytea;
437 typedef struct varlena text;
438 typedef struct varlena BpChar; /* blank-padded char, ie SQL char(n) */
439 typedef struct varlena VarChar; /* var-length char, ie SQL varchar(n) */
442 * Specialized array types. These are physically laid out just the same
443 * as regular arrays (so that the regular array subscripting code works
444 * with them). They exist as distinct types mostly for historical reasons:
445 * they have nonstandard I/O behavior which we don't want to change for fear
446 * of breaking applications that look at the system catalogs. There is also
447 * an implementation issue for oidvector: it's part of the primary key for
448 * pg_proc, and we can't use the normal btree array support routines for that
449 * without circularity.
453 int32 vl_len_; /* these fields must match ArrayType! */
454 int ndim; /* always 1 for int2vector */
455 int32 dataoffset; /* always 0 for int2vector */
459 int16 values[FLEXIBLE_ARRAY_MEMBER];
464 int32 vl_len_; /* these fields must match ArrayType! */
465 int ndim; /* always 1 for oidvector */
466 int32 dataoffset; /* always 0 for oidvector */
470 Oid values[FLEXIBLE_ARRAY_MEMBER];
474 * Representation of a Name: effectively just a C string, but null-padded to
475 * exactly NAMEDATALEN bytes. The use of a struct is historical.
477 typedef struct nameData
479 char data[NAMEDATALEN];
481 typedef NameData *Name;
483 #define NameStr(name) ((name).data)
486 * Support macros for escaping strings. escape_backslash should be TRUE
487 * if generating a non-standard-conforming string. Prefixing a string
488 * with ESCAPE_STRING_SYNTAX guarantees it is non-standard-conforming.
489 * Beware of multiple evaluation of the "ch" argument!
491 #define SQL_STR_DOUBLE(ch, escape_backslash) \
492 ((ch) == '\'' || ((ch) == '\\' && (escape_backslash)))
494 #define ESCAPE_STRING_SYNTAX 'E'
496 /* ----------------------------------------------------------------
497 * Section 4: IsValid macros for system types
498 * ----------------------------------------------------------------
502 * True iff bool is valid.
504 #define BoolIsValid(boolean) ((boolean) == false || (boolean) == true)
508 * True iff pointer is valid.
510 #define PointerIsValid(pointer) ((const void*)(pointer) != NULL)
514 * True iff pointer is properly aligned to point to the given type.
516 #define PointerIsAligned(pointer, type) \
517 (((uintptr_t)(pointer) % (sizeof (type))) == 0)
519 #define OidIsValid(objectId) ((bool) ((objectId) != InvalidOid))
521 #define RegProcedureIsValid(p) OidIsValid(p)
524 /* ----------------------------------------------------------------
525 * Section 5: offsetof, lengthof, endof, alignment
526 * ----------------------------------------------------------------
530 * Offset of a structure/union field within that structure/union.
532 * XXX This is supposed to be part of stddef.h, but isn't on
533 * some systems (like SunOS 4).
536 #define offsetof(type, field) ((long) &((type *)0)->field)
537 #endif /* offsetof */
541 * Number of elements in an array.
543 #define lengthof(array) (sizeof (array) / sizeof ((array)[0]))
547 * Address of the element one past the last in an array.
549 #define endof(array) (&(array)[lengthof(array)])
552 * Alignment macros: align a length or address appropriately for a given type.
553 * The fooALIGN() macros round up to a multiple of the required alignment,
554 * while the fooALIGN_DOWN() macros round down. The latter are more useful
555 * for problems like "how many X-sized structures will fit in a page?".
557 * NOTE: TYPEALIGN[_DOWN] will not work if ALIGNVAL is not a power of 2.
558 * That case seems extremely unlikely to be needed in practice, however.
562 #define TYPEALIGN(ALIGNVAL,LEN) \
563 (((uintptr_t) (LEN) + ((ALIGNVAL) - 1)) & ~((uintptr_t) ((ALIGNVAL) - 1)))
565 #define SHORTALIGN(LEN) TYPEALIGN(ALIGNOF_SHORT, (LEN))
566 #define INTALIGN(LEN) TYPEALIGN(ALIGNOF_INT, (LEN))
567 #define LONGALIGN(LEN) TYPEALIGN(ALIGNOF_LONG, (LEN))
568 #define DOUBLEALIGN(LEN) TYPEALIGN(ALIGNOF_DOUBLE, (LEN))
569 #define MAXALIGN(LEN) TYPEALIGN(MAXIMUM_ALIGNOF, (LEN))
570 /* MAXALIGN covers only built-in types, not buffers */
571 #define BUFFERALIGN(LEN) TYPEALIGN(ALIGNOF_BUFFER, (LEN))
572 #define CACHELINEALIGN(LEN) TYPEALIGN(PG_CACHE_LINE_SIZE, (LEN))
574 #define TYPEALIGN_DOWN(ALIGNVAL,LEN) \
575 (((uintptr_t) (LEN)) & ~((uintptr_t) ((ALIGNVAL) - 1)))
577 #define SHORTALIGN_DOWN(LEN) TYPEALIGN_DOWN(ALIGNOF_SHORT, (LEN))
578 #define INTALIGN_DOWN(LEN) TYPEALIGN_DOWN(ALIGNOF_INT, (LEN))
579 #define LONGALIGN_DOWN(LEN) TYPEALIGN_DOWN(ALIGNOF_LONG, (LEN))
580 #define DOUBLEALIGN_DOWN(LEN) TYPEALIGN_DOWN(ALIGNOF_DOUBLE, (LEN))
581 #define MAXALIGN_DOWN(LEN) TYPEALIGN_DOWN(MAXIMUM_ALIGNOF, (LEN))
584 * The above macros will not work with types wider than uintptr_t, like with
585 * uint64 on 32-bit platforms. That's not problem for the usual use where a
586 * pointer or a length is aligned, but for the odd case that you need to
587 * align something (potentially) wider, use TYPEALIGN64.
589 #define TYPEALIGN64(ALIGNVAL,LEN) \
590 (((uint64) (LEN) + ((ALIGNVAL) - 1)) & ~((uint64) ((ALIGNVAL) - 1)))
592 /* we don't currently need wider versions of the other ALIGN macros */
593 #define MAXALIGN64(LEN) TYPEALIGN64(MAXIMUM_ALIGNOF, (LEN))
598 * GCC: https://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
599 * GCC: https://gcc.gnu.org/onlinedocs/gcc/Type-Attributes.html
600 * Sunpro: https://docs.oracle.com/cd/E18659_01/html/821-1384/gjzke.html
601 * XLC: http://www-01.ibm.com/support/knowledgecenter/SSGH2K_11.1.0/com.ibm.xlc111.aix.doc/language_ref/function_attributes.html
602 * XLC: http://www-01.ibm.com/support/knowledgecenter/SSGH2K_11.1.0/com.ibm.xlc111.aix.doc/language_ref/type_attrib.html
606 /* only GCC supports the unused attribute */
608 #define pg_attribute_unused() __attribute__((unused))
610 #define pg_attribute_unused()
613 /* GCC and XLC support format attributes */
614 #if defined(__GNUC__) || defined(__IBMC__)
615 #define pg_attribute_format_arg(a) __attribute__((format_arg(a)))
616 #define pg_attribute_printf(f,a) __attribute__((format(PG_PRINTF_ATTRIBUTE, f, a)))
618 #define pg_attribute_format_arg(a)
619 #define pg_attribute_printf(f,a)
622 /* GCC, Sunpro and XLC support aligned, packed and noreturn */
623 #if defined(__GNUC__) || defined(__SUNPRO_C) || defined(__IBMC__)
624 #define pg_attribute_aligned(a) __attribute__((aligned(a)))
625 #define pg_attribute_noreturn() __attribute__((noreturn))
626 #define pg_attribute_packed() __attribute__((packed))
627 #define HAVE_PG_ATTRIBUTE_NORETURN 1
630 * NB: aligned and packed are not given default definitions because they
631 * affect code functionality; they *must* be implemented by the compiler
632 * if they are to be used.
634 #define pg_attribute_noreturn()
637 /* ----------------------------------------------------------------
638 * Section 6: assertions
639 * ----------------------------------------------------------------
643 * USE_ASSERT_CHECKING, if defined, turns on all the assertions.
646 * It should _NOT_ be defined in releases or in benchmark copies
650 * Assert() can be used in both frontend and backend code. In frontend code it
651 * just calls the standard assert, if it's available. If use of assertions is
652 * not configured, it does nothing.
654 #ifndef USE_ASSERT_CHECKING
656 #define Assert(condition) ((void)true)
657 #define AssertMacro(condition) ((void)true)
658 #define AssertArg(condition) ((void)true)
659 #define AssertState(condition) ((void)true)
660 #define AssertPointerAlignment(ptr, bndr) ((void)true)
661 #define Trap(condition, errorType) ((void)true)
662 #define TrapMacro(condition, errorType) (true)
664 #elif defined(FRONTEND)
667 #define Assert(p) assert(p)
668 #define AssertMacro(p) ((void) assert(p))
669 #define AssertArg(condition) assert(condition)
670 #define AssertState(condition) assert(condition)
671 #define AssertPointerAlignment(ptr, bndr) ((void)true)
672 #else /* USE_ASSERT_CHECKING && !FRONTEND */
676 * Generates an exception if the given condition is true.
678 #define Trap(condition, errorType) \
681 ExceptionalCondition(CppAsString(condition), (errorType), \
682 __FILE__, __LINE__); \
686 * TrapMacro is the same as Trap but it's intended for use in macros:
688 * #define foo(x) (AssertMacro(x != 0), bar(x))
692 #define TrapMacro(condition, errorType) \
693 ((bool) (! (condition) || \
694 (ExceptionalCondition(CppAsString(condition), (errorType), \
695 __FILE__, __LINE__), 0)))
697 #define Assert(condition) \
698 Trap(!(condition), "FailedAssertion")
700 #define AssertMacro(condition) \
701 ((void) TrapMacro(!(condition), "FailedAssertion"))
703 #define AssertArg(condition) \
704 Trap(!(condition), "BadArgument")
706 #define AssertState(condition) \
707 Trap(!(condition), "BadState")
710 * Check that `ptr' is `bndr' aligned.
712 #define AssertPointerAlignment(ptr, bndr) \
713 Trap(TYPEALIGN(bndr, (uintptr_t)(ptr)) != (uintptr_t)(ptr), \
716 #endif /* USE_ASSERT_CHECKING && !FRONTEND */
719 * Macros to support compile-time assertion checks.
721 * If the "condition" (a compile-time-constant expression) evaluates to false,
722 * throw a compile error using the "errmessage" (a string literal).
724 * gcc 4.6 and up supports _Static_assert(), but there are bizarre syntactic
725 * placement restrictions. These macros make it safe to use as a statement
726 * or in an expression, respectively.
728 * Otherwise we fall back on a kluge that assumes the compiler will complain
729 * about a negative width for a struct bit-field. This will not include a
730 * helpful error message, but it beats not getting an error at all.
732 #ifdef HAVE__STATIC_ASSERT
733 #define StaticAssertStmt(condition, errmessage) \
734 do { _Static_assert(condition, errmessage); } while(0)
735 #define StaticAssertExpr(condition, errmessage) \
736 ({ StaticAssertStmt(condition, errmessage); true; })
737 #else /* !HAVE__STATIC_ASSERT */
738 #define StaticAssertStmt(condition, errmessage) \
739 ((void) sizeof(struct { int static_assert_failure : (condition) ? 1 : -1; }))
740 #define StaticAssertExpr(condition, errmessage) \
741 StaticAssertStmt(condition, errmessage)
742 #endif /* HAVE__STATIC_ASSERT */
746 * Compile-time checks that a variable (or expression) has the specified type.
748 * AssertVariableIsOfType() can be used as a statement.
749 * AssertVariableIsOfTypeMacro() is intended for use in macros, eg
750 * #define foo(x) (AssertVariableIsOfTypeMacro(x, int), bar(x))
752 * If we don't have __builtin_types_compatible_p, we can still assert that
753 * the types have the same size. This is far from ideal (especially on 32-bit
754 * platforms) but it provides at least some coverage.
756 #ifdef HAVE__BUILTIN_TYPES_COMPATIBLE_P
757 #define AssertVariableIsOfType(varname, typename) \
758 StaticAssertStmt(__builtin_types_compatible_p(__typeof__(varname), typename), \
759 CppAsString(varname) " does not have type " CppAsString(typename))
760 #define AssertVariableIsOfTypeMacro(varname, typename) \
761 ((void) StaticAssertExpr(__builtin_types_compatible_p(__typeof__(varname), typename), \
762 CppAsString(varname) " does not have type " CppAsString(typename)))
763 #else /* !HAVE__BUILTIN_TYPES_COMPATIBLE_P */
764 #define AssertVariableIsOfType(varname, typename) \
765 StaticAssertStmt(sizeof(varname) == sizeof(typename), \
766 CppAsString(varname) " does not have type " CppAsString(typename))
767 #define AssertVariableIsOfTypeMacro(varname, typename) \
768 ((void) StaticAssertExpr(sizeof(varname) == sizeof(typename), \
769 CppAsString(varname) " does not have type " CppAsString(typename)))
770 #endif /* HAVE__BUILTIN_TYPES_COMPATIBLE_P */
773 /* ----------------------------------------------------------------
774 * Section 7: widely useful macros
775 * ----------------------------------------------------------------
779 * Return the maximum of two numbers.
781 #define Max(x, y) ((x) > (y) ? (x) : (y))
785 * Return the minimum of two numbers.
787 #define Min(x, y) ((x) < (y) ? (x) : (y))
791 * Return the absolute value of the argument.
793 #define Abs(x) ((x) >= 0 ? (x) : -(x))
797 * Like standard library function strncpy(), except that result string
798 * is guaranteed to be null-terminated --- that is, at most N-1 bytes
799 * of the source string will be kept.
800 * Also, the macro returns no result (too hard to do that without
801 * evaluating the arguments multiple times, which seems worse).
803 * BTW: when you need to copy a non-null-terminated string (like a text
804 * datum) and add a null, do not do it with StrNCpy(..., len+1). That
805 * might seem to work, but it fetches one byte more than there is in the
806 * text object. One fine day you'll have a SIGSEGV because there isn't
807 * another byte before the end of memory. Don't laugh, we've had real
808 * live bug reports from real live users over exactly this mistake.
809 * Do it honestly with "memcpy(dst,src,len); dst[len] = '\0';", instead.
811 #define StrNCpy(dst,src,len) \
814 char * _dst = (dst); \
819 strncpy(_dst, (src), _len); \
820 _dst[_len-1] = '\0'; \
825 /* Get a bit mask of the bits set in non-long aligned addresses */
826 #define LONG_ALIGN_MASK (sizeof(long) - 1)
830 * Exactly the same as standard library function memset(), but considerably
831 * faster for zeroing small word-aligned structures (such as parsetree nodes).
832 * This has to be a macro because the main point is to avoid function-call
833 * overhead. However, we have also found that the loop is faster than
834 * native libc memset() on some platforms, even those with assembler
835 * memset() functions. More research needs to be done, perhaps with
836 * MEMSET_LOOP_LIMIT tests in configure.
838 #define MemSet(start, val, len) \
841 /* must be void* because we don't know if it is integer aligned yet */ \
842 void *_vstart = (void *) (start); \
846 if ((((uintptr_t) _vstart) & LONG_ALIGN_MASK) == 0 && \
847 (_len & LONG_ALIGN_MASK) == 0 && \
849 _len <= MEMSET_LOOP_LIMIT && \
851 * If MEMSET_LOOP_LIMIT == 0, optimizer should find \
852 * the whole "if" false at compile time. \
854 MEMSET_LOOP_LIMIT != 0) \
856 long *_start = (long *) _vstart; \
857 long *_stop = (long *) ((char *) _start + _len); \
858 while (_start < _stop) \
862 memset(_vstart, _val, _len); \
866 * MemSetAligned is the same as MemSet except it omits the test to see if
867 * "start" is word-aligned. This is okay to use if the caller knows a-priori
868 * that the pointer is suitably aligned (typically, because he just got it
869 * from palloc(), which always delivers a max-aligned pointer).
871 #define MemSetAligned(start, val, len) \
874 long *_start = (long *) (start); \
878 if ((_len & LONG_ALIGN_MASK) == 0 && \
880 _len <= MEMSET_LOOP_LIMIT && \
881 MEMSET_LOOP_LIMIT != 0) \
883 long *_stop = (long *) ((char *) _start + _len); \
884 while (_start < _stop) \
888 memset(_start, _val, _len); \
893 * MemSetTest/MemSetLoop are a variant version that allow all the tests in
894 * MemSet to be done at compile time in cases where "val" and "len" are
895 * constants *and* we know the "start" pointer must be word-aligned.
896 * If MemSetTest succeeds, then it is okay to use MemSetLoop, otherwise use
897 * MemSetAligned. Beware of multiple evaluations of the arguments when using
900 #define MemSetTest(val, len) \
901 ( ((len) & LONG_ALIGN_MASK) == 0 && \
902 (len) <= MEMSET_LOOP_LIMIT && \
903 MEMSET_LOOP_LIMIT != 0 && \
906 #define MemSetLoop(start, val, len) \
909 long * _start = (long *) (start); \
910 long * _stop = (long *) ((char *) _start + (Size) (len)); \
912 while (_start < _stop) \
918 * Mark a point as unreachable in a portable fashion. This should preferably
919 * be something that the compiler understands, to aid code generation.
920 * In assert-enabled builds, we prefer abort() for debugging reasons.
922 #if defined(HAVE__BUILTIN_UNREACHABLE) && !defined(USE_ASSERT_CHECKING)
923 #define pg_unreachable() __builtin_unreachable()
924 #elif defined(_MSC_VER) && !defined(USE_ASSERT_CHECKING)
925 #define pg_unreachable() __assume(0)
927 #define pg_unreachable() abort()
931 /* ----------------------------------------------------------------
932 * Section 8: random stuff
933 * ----------------------------------------------------------------
937 #define HIGHBIT (0x80)
938 #define IS_HIGHBIT_SET(ch) ((unsigned char)(ch) & HIGHBIT)
940 #define STATUS_OK (0)
941 #define STATUS_ERROR (-1)
942 #define STATUS_EOF (-2)
943 #define STATUS_FOUND (1)
944 #define STATUS_WAITING (2)
948 * Append PG_USED_FOR_ASSERTS_ONLY to definitions of variables that are only
949 * used in assert-enabled builds, to avoid compiler warnings about unused
950 * variables in assert-disabled builds.
952 #ifdef USE_ASSERT_CHECKING
953 #define PG_USED_FOR_ASSERTS_ONLY
955 #define PG_USED_FOR_ASSERTS_ONLY pg_attribute_unused()
959 /* gettext domain name mangling */
962 * To better support parallel installations of major PostgeSQL
963 * versions as well as parallel installations of major library soname
964 * versions, we mangle the gettext domain name by appending those
965 * version numbers. The coding rule ought to be that wherever the
966 * domain name is mentioned as a literal, it must be wrapped into
967 * PG_TEXTDOMAIN(). The macros below do not work on non-literals; but
968 * that is somewhat intentional because it avoids having to worry
969 * about multiple states of premangling and postmangling as the values
970 * are being passed around.
972 * Make sure this matches the installation rules in nls-global.mk.
975 /* need a second indirection because we want to stringize the macro value, not the name */
976 #define CppAsString2(x) CppAsString(x)
978 #ifdef SO_MAJOR_VERSION
979 #define PG_TEXTDOMAIN(domain) (domain CppAsString2(SO_MAJOR_VERSION) "-" PG_MAJORVERSION)
981 #define PG_TEXTDOMAIN(domain) (domain "-" PG_MAJORVERSION)
985 /* ----------------------------------------------------------------
986 * Section 9: system-specific hacks
988 * This should be limited to things that absolutely have to be
989 * included in every source file. The port-specific header file
990 * is usually a better place for this sort of thing.
991 * ----------------------------------------------------------------
995 * NOTE: this is also used for opening text files.
996 * WIN32 treats Control-Z as EOF in files opened in text mode.
997 * Therefore, we open files in binary mode on Win32 so we can read
998 * literal control-Z. The other affect is that we see CRLF, but
999 * that is OK because we can already handle those cleanly.
1001 #if defined(WIN32) || defined(__CYGWIN__)
1002 #define PG_BINARY O_BINARY
1003 #define PG_BINARY_A "ab"
1004 #define PG_BINARY_R "rb"
1005 #define PG_BINARY_W "wb"
1008 #define PG_BINARY_A "a"
1009 #define PG_BINARY_R "r"
1010 #define PG_BINARY_W "w"
1014 * Provide prototypes for routines not present in a particular machine's
1015 * standard C library.
1018 #if !HAVE_DECL_SNPRINTF
1019 extern int snprintf(char *str, size_t count, const char *fmt,...) pg_attribute_printf(3, 4);
1022 #if !HAVE_DECL_VSNPRINTF
1023 extern int vsnprintf(char *str, size_t count, const char *fmt, va_list args);
1026 #if !defined(HAVE_MEMMOVE) && !defined(memmove)
1027 #define memmove(d, s, c) bcopy(s, d, c)
1030 /* no special DLL markers on most ports */
1039 * The following is used as the arg list for signal handlers. Any ports
1040 * that take something other than an int argument should override this in
1041 * their pg_config_os.h file. Note that variable names are required
1042 * because it is used in both the prototypes as well as the definitions.
1043 * Note also the long name. We expect that this won't collide with
1044 * other names causing compiler warnings.
1048 #define SIGNAL_ARGS int postgres_signal_arg
1052 * When there is no sigsetjmp, its functionality is provided by plain
1053 * setjmp. Incidentally, nothing provides setjmp's functionality in
1054 * that case. We now support the case only on Windows.
1057 #define sigjmp_buf jmp_buf
1058 #define sigsetjmp(x,y) setjmp(x)
1059 #define siglongjmp longjmp
1062 #if defined(HAVE_FDATASYNC) && !HAVE_DECL_FDATASYNC
1063 extern int fdatasync(int fildes);
1066 /* If strtoq() exists, rename it to the more standard strtoll() */
1067 #if defined(HAVE_LONG_LONG_INT_64) && !defined(HAVE_STRTOLL) && defined(HAVE_STRTOQ)
1068 #define strtoll strtoq
1069 #define HAVE_STRTOLL 1
1072 /* If strtouq() exists, rename it to the more standard strtoull() */
1073 #if defined(HAVE_LONG_LONG_INT_64) && !defined(HAVE_STRTOULL) && defined(HAVE_STRTOUQ)
1074 #define strtoull strtouq
1075 #define HAVE_STRTOULL 1
1079 * We assume if we have these two functions, we have their friends too, and
1080 * can use the wide-character functions.
1082 #if defined(HAVE_WCSTOMBS) && defined(HAVE_TOWLOWER)
1083 #define USE_WIDE_UPPER_LOWER
1086 /* EXEC_BACKEND defines */
1088 #define NON_EXEC_STATIC
1090 #define NON_EXEC_STATIC static
1093 /* /port compatibility functions */