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 */
255 #ifdef HAVE_LONG_INT_64
256 /* Plain "long int" fits, use it */
259 typedef long int int64;
262 typedef unsigned long int uint64;
264 #elif defined(HAVE_LONG_LONG_INT_64)
265 /* We have working support for "long long int", use that */
268 typedef long long int int64;
271 typedef unsigned long long int uint64;
274 /* neither HAVE_LONG_INT_64 nor HAVE_LONG_LONG_INT_64 */
275 #error must have a working 64-bit integer datatype
278 /* Decide if we need to decorate 64-bit constants */
279 #ifdef HAVE_LL_CONSTANTS
280 #define INT64CONST(x) ((int64) x##LL)
281 #define UINT64CONST(x) ((uint64) x##ULL)
283 #define INT64CONST(x) ((int64) x)
284 #define UINT64CONST(x) ((uint64) x)
287 /* snprintf format strings to use for 64-bit integers */
288 #define INT64_FORMAT "%" INT64_MODIFIER "d"
289 #define UINT64_FORMAT "%" INT64_MODIFIER "u"
292 * 128-bit signed and unsigned integers
293 * There currently is only a limited support for the type. E.g. 128bit
294 * literals and snprintf are not supported; but math is.
296 #if defined(PG_INT128_TYPE)
298 typedef PG_INT128_TYPE int128;
299 typedef unsigned PG_INT128_TYPE uint128;
303 * stdint.h limits aren't guaranteed to be present and aren't guaranteed to
304 * have compatible types with our fixed width types. So just define our own.
306 #define PG_INT8_MIN (-0x7F-1)
307 #define PG_INT8_MAX (0x7F)
308 #define PG_UINT8_MAX (0xFF)
309 #define PG_INT16_MIN (-0x7FFF-1)
310 #define PG_INT16_MAX (0x7FFF)
311 #define PG_UINT16_MAX (0xFFFF)
312 #define PG_INT32_MIN (-0x7FFFFFFF-1)
313 #define PG_INT32_MAX (0x7FFFFFFF)
314 #define PG_UINT32_MAX (0xFFFFFFFF)
315 #define PG_INT64_MIN (-INT64CONST(0x7FFFFFFFFFFFFFFF) - 1)
316 #define PG_INT64_MAX INT64CONST(0x7FFFFFFFFFFFFFFF)
317 #define PG_UINT64_MAX UINT64CONST(0xFFFFFFFFFFFFFFFF)
319 /* Select timestamp representation (float8 or int64) */
320 #ifdef USE_INTEGER_DATETIMES
321 #define HAVE_INT64_TIMESTAMP
324 /* sig_atomic_t is required by ANSI C, but may be missing on old platforms */
325 #ifndef HAVE_SIG_ATOMIC_T
326 typedef int sig_atomic_t;
331 * Size of any memory resident object, as returned by sizeof.
337 * Index into any memory resident array.
340 * Indices are non negative.
342 typedef unsigned int Index;
346 * Offset into any memory resident array.
349 * This differs from an Index in that an Index is always
350 * non negative, whereas Offset may be negative.
352 typedef signed int Offset;
355 * Common Postgres datatype names (as used in the catalogs)
357 typedef float float4;
358 typedef double float8;
361 * Oid, RegProcedure, TransactionId, SubTransactionId, MultiXactId,
365 /* typedef Oid is in postgres_ext.h */
368 * regproc is the type name used in the include/catalog headers, but
369 * RegProcedure is the preferred name in C code.
372 typedef regproc RegProcedure;
374 typedef uint32 TransactionId;
376 typedef uint32 LocalTransactionId;
378 typedef uint32 SubTransactionId;
380 #define InvalidSubTransactionId ((SubTransactionId) 0)
381 #define TopSubTransactionId ((SubTransactionId) 1)
383 /* MultiXactId must be equivalent to TransactionId, to fit in t_xmax */
384 typedef TransactionId MultiXactId;
386 typedef uint32 MultiXactOffset;
388 typedef uint32 CommandId;
390 #define FirstCommandId ((CommandId) 0)
391 #define InvalidCommandId (~(CommandId)0)
394 * Array indexing support
403 * Variable-length datatypes all share the 'struct varlena' header.
405 * NOTE: for TOASTable types, this is an oversimplification, since the value
406 * may be compressed or moved out-of-line. However datatype-specific routines
407 * are mostly content to deal with de-TOASTed values only, and of course
408 * client-side routines should never see a TOASTed value. But even in a
409 * de-TOASTed value, beware of touching vl_len_ directly, as its representation
410 * is no longer convenient. It's recommended that code always use the VARDATA,
411 * VARSIZE, and SET_VARSIZE macros instead of relying on direct mentions of
412 * the struct fields. See postgres.h for details of the TOASTed form.
417 char vl_len_[4]; /* Do not touch this field directly! */
418 char vl_dat[FLEXIBLE_ARRAY_MEMBER]; /* Data content is here */
421 #define VARHDRSZ ((int32) sizeof(int32))
424 * These widely-used datatypes are just a varlena header and the data bytes.
425 * There is no terminating null or anything like that --- the data length is
426 * always VARSIZE(ptr) - VARHDRSZ.
428 typedef struct varlena bytea;
429 typedef struct varlena text;
430 typedef struct varlena BpChar; /* blank-padded char, ie SQL char(n) */
431 typedef struct varlena VarChar; /* var-length char, ie SQL varchar(n) */
434 * Specialized array types. These are physically laid out just the same
435 * as regular arrays (so that the regular array subscripting code works
436 * with them). They exist as distinct types mostly for historical reasons:
437 * they have nonstandard I/O behavior which we don't want to change for fear
438 * of breaking applications that look at the system catalogs. There is also
439 * an implementation issue for oidvector: it's part of the primary key for
440 * pg_proc, and we can't use the normal btree array support routines for that
441 * without circularity.
445 int32 vl_len_; /* these fields must match ArrayType! */
446 int ndim; /* always 1 for int2vector */
447 int32 dataoffset; /* always 0 for int2vector */
451 int16 values[FLEXIBLE_ARRAY_MEMBER];
456 int32 vl_len_; /* these fields must match ArrayType! */
457 int ndim; /* always 1 for oidvector */
458 int32 dataoffset; /* always 0 for oidvector */
462 Oid values[FLEXIBLE_ARRAY_MEMBER];
466 * Representation of a Name: effectively just a C string, but null-padded to
467 * exactly NAMEDATALEN bytes. The use of a struct is historical.
469 typedef struct nameData
471 char data[NAMEDATALEN];
473 typedef NameData *Name;
475 #define NameStr(name) ((name).data)
478 * Support macros for escaping strings. escape_backslash should be TRUE
479 * if generating a non-standard-conforming string. Prefixing a string
480 * with ESCAPE_STRING_SYNTAX guarantees it is non-standard-conforming.
481 * Beware of multiple evaluation of the "ch" argument!
483 #define SQL_STR_DOUBLE(ch, escape_backslash) \
484 ((ch) == '\'' || ((ch) == '\\' && (escape_backslash)))
486 #define ESCAPE_STRING_SYNTAX 'E'
488 /* ----------------------------------------------------------------
489 * Section 4: IsValid macros for system types
490 * ----------------------------------------------------------------
494 * True iff bool is valid.
496 #define BoolIsValid(boolean) ((boolean) == false || (boolean) == true)
500 * True iff pointer is valid.
502 #define PointerIsValid(pointer) ((const void*)(pointer) != NULL)
506 * True iff pointer is properly aligned to point to the given type.
508 #define PointerIsAligned(pointer, type) \
509 (((uintptr_t)(pointer) % (sizeof (type))) == 0)
511 #define OidIsValid(objectId) ((bool) ((objectId) != InvalidOid))
513 #define RegProcedureIsValid(p) OidIsValid(p)
516 /* ----------------------------------------------------------------
517 * Section 5: offsetof, lengthof, endof, alignment
518 * ----------------------------------------------------------------
522 * Offset of a structure/union field within that structure/union.
524 * XXX This is supposed to be part of stddef.h, but isn't on
525 * some systems (like SunOS 4).
528 #define offsetof(type, field) ((long) &((type *)0)->field)
529 #endif /* offsetof */
533 * Number of elements in an array.
535 #define lengthof(array) (sizeof (array) / sizeof ((array)[0]))
539 * Address of the element one past the last in an array.
541 #define endof(array) (&(array)[lengthof(array)])
544 * Alignment macros: align a length or address appropriately for a given type.
545 * The fooALIGN() macros round up to a multiple of the required alignment,
546 * while the fooALIGN_DOWN() macros round down. The latter are more useful
547 * for problems like "how many X-sized structures will fit in a page?".
549 * NOTE: TYPEALIGN[_DOWN] will not work if ALIGNVAL is not a power of 2.
550 * That case seems extremely unlikely to be needed in practice, however.
554 #define TYPEALIGN(ALIGNVAL,LEN) \
555 (((uintptr_t) (LEN) + ((ALIGNVAL) - 1)) & ~((uintptr_t) ((ALIGNVAL) - 1)))
557 #define SHORTALIGN(LEN) TYPEALIGN(ALIGNOF_SHORT, (LEN))
558 #define INTALIGN(LEN) TYPEALIGN(ALIGNOF_INT, (LEN))
559 #define LONGALIGN(LEN) TYPEALIGN(ALIGNOF_LONG, (LEN))
560 #define DOUBLEALIGN(LEN) TYPEALIGN(ALIGNOF_DOUBLE, (LEN))
561 #define MAXALIGN(LEN) TYPEALIGN(MAXIMUM_ALIGNOF, (LEN))
562 /* MAXALIGN covers only built-in types, not buffers */
563 #define BUFFERALIGN(LEN) TYPEALIGN(ALIGNOF_BUFFER, (LEN))
564 #define CACHELINEALIGN(LEN) TYPEALIGN(PG_CACHE_LINE_SIZE, (LEN))
566 #define TYPEALIGN_DOWN(ALIGNVAL,LEN) \
567 (((uintptr_t) (LEN)) & ~((uintptr_t) ((ALIGNVAL) - 1)))
569 #define SHORTALIGN_DOWN(LEN) TYPEALIGN_DOWN(ALIGNOF_SHORT, (LEN))
570 #define INTALIGN_DOWN(LEN) TYPEALIGN_DOWN(ALIGNOF_INT, (LEN))
571 #define LONGALIGN_DOWN(LEN) TYPEALIGN_DOWN(ALIGNOF_LONG, (LEN))
572 #define DOUBLEALIGN_DOWN(LEN) TYPEALIGN_DOWN(ALIGNOF_DOUBLE, (LEN))
573 #define MAXALIGN_DOWN(LEN) TYPEALIGN_DOWN(MAXIMUM_ALIGNOF, (LEN))
576 * The above macros will not work with types wider than uintptr_t, like with
577 * uint64 on 32-bit platforms. That's not problem for the usual use where a
578 * pointer or a length is aligned, but for the odd case that you need to
579 * align something (potentially) wider, use TYPEALIGN64.
581 #define TYPEALIGN64(ALIGNVAL,LEN) \
582 (((uint64) (LEN) + ((ALIGNVAL) - 1)) & ~((uint64) ((ALIGNVAL) - 1)))
584 /* we don't currently need wider versions of the other ALIGN macros */
585 #define MAXALIGN64(LEN) TYPEALIGN64(MAXIMUM_ALIGNOF, (LEN))
590 * GCC: https://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
591 * GCC: https://gcc.gnu.org/onlinedocs/gcc/Type-Attributes.html
592 * Sunpro: https://docs.oracle.com/cd/E18659_01/html/821-1384/gjzke.html
593 * XLC: http://www-01.ibm.com/support/knowledgecenter/SSGH2K_11.1.0/com.ibm.xlc111.aix.doc/language_ref/function_attributes.html
594 * XLC: http://www-01.ibm.com/support/knowledgecenter/SSGH2K_11.1.0/com.ibm.xlc111.aix.doc/language_ref/type_attrib.html
598 /* only GCC supports the unused attribute */
600 #define pg_attribute_unused() __attribute__((unused))
602 #define pg_attribute_unused()
605 /* GCC and XLC support format attributes */
606 #if defined(__GNUC__) || defined(__IBMC__)
607 #define pg_attribute_format_arg(a) __attribute__((format_arg(a)))
608 #define pg_attribute_printf(f,a) __attribute__((format(PG_PRINTF_ATTRIBUTE, f, a)))
610 #define pg_attribute_format_arg(a)
611 #define pg_attribute_printf(f,a)
614 /* GCC, Sunpro and XLC support aligned, packed and noreturn */
615 #if defined(__GNUC__) || defined(__SUNPRO_C) || defined(__IBMC__)
616 #define pg_attribute_aligned(a) __attribute__((aligned(a)))
617 #define pg_attribute_noreturn() __attribute__((noreturn))
618 #define pg_attribute_packed() __attribute__((packed))
619 #define HAVE_PG_ATTRIBUTE_NORETURN 1
622 * NB: aligned and packed are not given default definitions because they
623 * affect code functionality; they *must* be implemented by the compiler
624 * if they are to be used.
626 #define pg_attribute_noreturn()
629 /* ----------------------------------------------------------------
630 * Section 6: assertions
631 * ----------------------------------------------------------------
635 * USE_ASSERT_CHECKING, if defined, turns on all the assertions.
638 * It should _NOT_ be defined in releases or in benchmark copies
642 * Assert() can be used in both frontend and backend code. In frontend code it
643 * just calls the standard assert, if it's available. If use of assertions is
644 * not configured, it does nothing.
646 #ifndef USE_ASSERT_CHECKING
648 #define Assert(condition) ((void)true)
649 #define AssertMacro(condition) ((void)true)
650 #define AssertArg(condition) ((void)true)
651 #define AssertState(condition) ((void)true)
652 #define AssertPointerAlignment(ptr, bndr) ((void)true)
653 #define Trap(condition, errorType) ((void)true)
654 #define TrapMacro(condition, errorType) (true)
656 #elif defined(FRONTEND)
659 #define Assert(p) assert(p)
660 #define AssertMacro(p) ((void) assert(p))
661 #define AssertArg(condition) assert(condition)
662 #define AssertState(condition) assert(condition)
663 #define AssertPointerAlignment(ptr, bndr) ((void)true)
664 #else /* USE_ASSERT_CHECKING && !FRONTEND */
668 * Generates an exception if the given condition is true.
670 #define Trap(condition, errorType) \
673 ExceptionalCondition(CppAsString(condition), (errorType), \
674 __FILE__, __LINE__); \
678 * TrapMacro is the same as Trap but it's intended for use in macros:
680 * #define foo(x) (AssertMacro(x != 0), bar(x))
684 #define TrapMacro(condition, errorType) \
685 ((bool) (! (condition) || \
686 (ExceptionalCondition(CppAsString(condition), (errorType), \
687 __FILE__, __LINE__), 0)))
689 #define Assert(condition) \
690 Trap(!(condition), "FailedAssertion")
692 #define AssertMacro(condition) \
693 ((void) TrapMacro(!(condition), "FailedAssertion"))
695 #define AssertArg(condition) \
696 Trap(!(condition), "BadArgument")
698 #define AssertState(condition) \
699 Trap(!(condition), "BadState")
702 * Check that `ptr' is `bndr' aligned.
704 #define AssertPointerAlignment(ptr, bndr) \
705 Trap(TYPEALIGN(bndr, (uintptr_t)(ptr)) != (uintptr_t)(ptr), \
708 #endif /* USE_ASSERT_CHECKING && !FRONTEND */
711 * Macros to support compile-time assertion checks.
713 * If the "condition" (a compile-time-constant expression) evaluates to false,
714 * throw a compile error using the "errmessage" (a string literal).
716 * gcc 4.6 and up supports _Static_assert(), but there are bizarre syntactic
717 * placement restrictions. These macros make it safe to use as a statement
718 * or in an expression, respectively.
720 * Otherwise we fall back on a kluge that assumes the compiler will complain
721 * about a negative width for a struct bit-field. This will not include a
722 * helpful error message, but it beats not getting an error at all.
724 #ifdef HAVE__STATIC_ASSERT
725 #define StaticAssertStmt(condition, errmessage) \
726 do { _Static_assert(condition, errmessage); } while(0)
727 #define StaticAssertExpr(condition, errmessage) \
728 ({ StaticAssertStmt(condition, errmessage); true; })
729 #else /* !HAVE__STATIC_ASSERT */
730 #define StaticAssertStmt(condition, errmessage) \
731 ((void) sizeof(struct { int static_assert_failure : (condition) ? 1 : -1; }))
732 #define StaticAssertExpr(condition, errmessage) \
733 StaticAssertStmt(condition, errmessage)
734 #endif /* HAVE__STATIC_ASSERT */
738 * Compile-time checks that a variable (or expression) has the specified type.
740 * AssertVariableIsOfType() can be used as a statement.
741 * AssertVariableIsOfTypeMacro() is intended for use in macros, eg
742 * #define foo(x) (AssertVariableIsOfTypeMacro(x, int), bar(x))
744 * If we don't have __builtin_types_compatible_p, we can still assert that
745 * the types have the same size. This is far from ideal (especially on 32-bit
746 * platforms) but it provides at least some coverage.
748 #ifdef HAVE__BUILTIN_TYPES_COMPATIBLE_P
749 #define AssertVariableIsOfType(varname, typename) \
750 StaticAssertStmt(__builtin_types_compatible_p(__typeof__(varname), typename), \
751 CppAsString(varname) " does not have type " CppAsString(typename))
752 #define AssertVariableIsOfTypeMacro(varname, typename) \
753 ((void) StaticAssertExpr(__builtin_types_compatible_p(__typeof__(varname), typename), \
754 CppAsString(varname) " does not have type " CppAsString(typename)))
755 #else /* !HAVE__BUILTIN_TYPES_COMPATIBLE_P */
756 #define AssertVariableIsOfType(varname, typename) \
757 StaticAssertStmt(sizeof(varname) == sizeof(typename), \
758 CppAsString(varname) " does not have type " CppAsString(typename))
759 #define AssertVariableIsOfTypeMacro(varname, typename) \
760 ((void) StaticAssertExpr(sizeof(varname) == sizeof(typename), \
761 CppAsString(varname) " does not have type " CppAsString(typename)))
762 #endif /* HAVE__BUILTIN_TYPES_COMPATIBLE_P */
765 /* ----------------------------------------------------------------
766 * Section 7: widely useful macros
767 * ----------------------------------------------------------------
771 * Return the maximum of two numbers.
773 #define Max(x, y) ((x) > (y) ? (x) : (y))
777 * Return the minimum of two numbers.
779 #define Min(x, y) ((x) < (y) ? (x) : (y))
783 * Return the absolute value of the argument.
785 #define Abs(x) ((x) >= 0 ? (x) : -(x))
789 * Like standard library function strncpy(), except that result string
790 * is guaranteed to be null-terminated --- that is, at most N-1 bytes
791 * of the source string will be kept.
792 * Also, the macro returns no result (too hard to do that without
793 * evaluating the arguments multiple times, which seems worse).
795 * BTW: when you need to copy a non-null-terminated string (like a text
796 * datum) and add a null, do not do it with StrNCpy(..., len+1). That
797 * might seem to work, but it fetches one byte more than there is in the
798 * text object. One fine day you'll have a SIGSEGV because there isn't
799 * another byte before the end of memory. Don't laugh, we've had real
800 * live bug reports from real live users over exactly this mistake.
801 * Do it honestly with "memcpy(dst,src,len); dst[len] = '\0';", instead.
803 #define StrNCpy(dst,src,len) \
806 char * _dst = (dst); \
811 strncpy(_dst, (src), _len); \
812 _dst[_len-1] = '\0'; \
817 /* Get a bit mask of the bits set in non-long aligned addresses */
818 #define LONG_ALIGN_MASK (sizeof(long) - 1)
822 * Exactly the same as standard library function memset(), but considerably
823 * faster for zeroing small word-aligned structures (such as parsetree nodes).
824 * This has to be a macro because the main point is to avoid function-call
825 * overhead. However, we have also found that the loop is faster than
826 * native libc memset() on some platforms, even those with assembler
827 * memset() functions. More research needs to be done, perhaps with
828 * MEMSET_LOOP_LIMIT tests in configure.
830 #define MemSet(start, val, len) \
833 /* must be void* because we don't know if it is integer aligned yet */ \
834 void *_vstart = (void *) (start); \
838 if ((((uintptr_t) _vstart) & LONG_ALIGN_MASK) == 0 && \
839 (_len & LONG_ALIGN_MASK) == 0 && \
841 _len <= MEMSET_LOOP_LIMIT && \
843 * If MEMSET_LOOP_LIMIT == 0, optimizer should find \
844 * the whole "if" false at compile time. \
846 MEMSET_LOOP_LIMIT != 0) \
848 long *_start = (long *) _vstart; \
849 long *_stop = (long *) ((char *) _start + _len); \
850 while (_start < _stop) \
854 memset(_vstart, _val, _len); \
858 * MemSetAligned is the same as MemSet except it omits the test to see if
859 * "start" is word-aligned. This is okay to use if the caller knows a-priori
860 * that the pointer is suitably aligned (typically, because he just got it
861 * from palloc(), which always delivers a max-aligned pointer).
863 #define MemSetAligned(start, val, len) \
866 long *_start = (long *) (start); \
870 if ((_len & LONG_ALIGN_MASK) == 0 && \
872 _len <= MEMSET_LOOP_LIMIT && \
873 MEMSET_LOOP_LIMIT != 0) \
875 long *_stop = (long *) ((char *) _start + _len); \
876 while (_start < _stop) \
880 memset(_start, _val, _len); \
885 * MemSetTest/MemSetLoop are a variant version that allow all the tests in
886 * MemSet to be done at compile time in cases where "val" and "len" are
887 * constants *and* we know the "start" pointer must be word-aligned.
888 * If MemSetTest succeeds, then it is okay to use MemSetLoop, otherwise use
889 * MemSetAligned. Beware of multiple evaluations of the arguments when using
892 #define MemSetTest(val, len) \
893 ( ((len) & LONG_ALIGN_MASK) == 0 && \
894 (len) <= MEMSET_LOOP_LIMIT && \
895 MEMSET_LOOP_LIMIT != 0 && \
898 #define MemSetLoop(start, val, len) \
901 long * _start = (long *) (start); \
902 long * _stop = (long *) ((char *) _start + (Size) (len)); \
904 while (_start < _stop) \
910 * Mark a point as unreachable in a portable fashion. This should preferably
911 * be something that the compiler understands, to aid code generation.
912 * In assert-enabled builds, we prefer abort() for debugging reasons.
914 #if defined(HAVE__BUILTIN_UNREACHABLE) && !defined(USE_ASSERT_CHECKING)
915 #define pg_unreachable() __builtin_unreachable()
916 #elif defined(_MSC_VER) && !defined(USE_ASSERT_CHECKING)
917 #define pg_unreachable() __assume(0)
919 #define pg_unreachable() abort()
924 * Function inlining support -- Allow modules to define functions that may be
925 * inlined, if the compiler supports it.
927 * The function bodies must be defined in the module header prefixed by
928 * STATIC_IF_INLINE, protected by a cpp symbol that the module's .c file must
929 * define. If the compiler doesn't support inline functions, the function
930 * definitions are pulled in by the .c file as regular (not inline) symbols.
932 * The header must also declare the functions' prototypes, protected by
936 /* declarations which are only visible when not inlining and in the .c file */
938 #define STATIC_IF_INLINE static inline
940 #define STATIC_IF_INLINE
941 #endif /* PG_USE_INLINE */
943 /* declarations which are marked inline when inlining, extern otherwise */
945 #define STATIC_IF_INLINE_DECLARE static inline
947 #define STATIC_IF_INLINE_DECLARE extern
948 #endif /* PG_USE_INLINE */
951 /* ----------------------------------------------------------------
952 * Section 8: random stuff
953 * ----------------------------------------------------------------
957 #define HIGHBIT (0x80)
958 #define IS_HIGHBIT_SET(ch) ((unsigned char)(ch) & HIGHBIT)
960 #define STATUS_OK (0)
961 #define STATUS_ERROR (-1)
962 #define STATUS_EOF (-2)
963 #define STATUS_FOUND (1)
964 #define STATUS_WAITING (2)
968 * Append PG_USED_FOR_ASSERTS_ONLY to definitions of variables that are only
969 * used in assert-enabled builds, to avoid compiler warnings about unused
970 * variables in assert-disabled builds.
972 #ifdef USE_ASSERT_CHECKING
973 #define PG_USED_FOR_ASSERTS_ONLY
975 #define PG_USED_FOR_ASSERTS_ONLY pg_attribute_unused()
979 /* gettext domain name mangling */
982 * To better support parallel installations of major PostgeSQL
983 * versions as well as parallel installations of major library soname
984 * versions, we mangle the gettext domain name by appending those
985 * version numbers. The coding rule ought to be that wherever the
986 * domain name is mentioned as a literal, it must be wrapped into
987 * PG_TEXTDOMAIN(). The macros below do not work on non-literals; but
988 * that is somewhat intentional because it avoids having to worry
989 * about multiple states of premangling and postmangling as the values
990 * are being passed around.
992 * Make sure this matches the installation rules in nls-global.mk.
995 /* need a second indirection because we want to stringize the macro value, not the name */
996 #define CppAsString2(x) CppAsString(x)
998 #ifdef SO_MAJOR_VERSION
999 #define PG_TEXTDOMAIN(domain) (domain CppAsString2(SO_MAJOR_VERSION) "-" PG_MAJORVERSION)
1001 #define PG_TEXTDOMAIN(domain) (domain "-" PG_MAJORVERSION)
1005 /* ----------------------------------------------------------------
1006 * Section 9: system-specific hacks
1008 * This should be limited to things that absolutely have to be
1009 * included in every source file. The port-specific header file
1010 * is usually a better place for this sort of thing.
1011 * ----------------------------------------------------------------
1015 * NOTE: this is also used for opening text files.
1016 * WIN32 treats Control-Z as EOF in files opened in text mode.
1017 * Therefore, we open files in binary mode on Win32 so we can read
1018 * literal control-Z. The other affect is that we see CRLF, but
1019 * that is OK because we can already handle those cleanly.
1021 #if defined(WIN32) || defined(__CYGWIN__)
1022 #define PG_BINARY O_BINARY
1023 #define PG_BINARY_A "ab"
1024 #define PG_BINARY_R "rb"
1025 #define PG_BINARY_W "wb"
1028 #define PG_BINARY_A "a"
1029 #define PG_BINARY_R "r"
1030 #define PG_BINARY_W "w"
1034 * Provide prototypes for routines not present in a particular machine's
1035 * standard C library.
1038 #if !HAVE_DECL_SNPRINTF
1039 extern int snprintf(char *str, size_t count, const char *fmt,...) pg_attribute_printf(3, 4);
1042 #if !HAVE_DECL_VSNPRINTF
1043 extern int vsnprintf(char *str, size_t count, const char *fmt, va_list args);
1046 #if !defined(HAVE_MEMMOVE) && !defined(memmove)
1047 #define memmove(d, s, c) bcopy(s, d, c)
1050 /* no special DLL markers on most ports */
1059 * The following is used as the arg list for signal handlers. Any ports
1060 * that take something other than an int argument should override this in
1061 * their pg_config_os.h file. Note that variable names are required
1062 * because it is used in both the prototypes as well as the definitions.
1063 * Note also the long name. We expect that this won't collide with
1064 * other names causing compiler warnings.
1068 #define SIGNAL_ARGS int postgres_signal_arg
1072 * When there is no sigsetjmp, its functionality is provided by plain
1073 * setjmp. Incidentally, nothing provides setjmp's functionality in
1076 #ifndef HAVE_SIGSETJMP
1077 #define sigjmp_buf jmp_buf
1078 #define sigsetjmp(x,y) setjmp(x)
1079 #define siglongjmp longjmp
1082 #if defined(HAVE_FDATASYNC) && !HAVE_DECL_FDATASYNC
1083 extern int fdatasync(int fildes);
1086 /* If strtoq() exists, rename it to the more standard strtoll() */
1087 #if defined(HAVE_LONG_LONG_INT_64) && !defined(HAVE_STRTOLL) && defined(HAVE_STRTOQ)
1088 #define strtoll strtoq
1089 #define HAVE_STRTOLL 1
1092 /* If strtouq() exists, rename it to the more standard strtoull() */
1093 #if defined(HAVE_LONG_LONG_INT_64) && !defined(HAVE_STRTOULL) && defined(HAVE_STRTOUQ)
1094 #define strtoull strtouq
1095 #define HAVE_STRTOULL 1
1099 * We assume if we have these two functions, we have their friends too, and
1100 * can use the wide-character functions.
1102 #if defined(HAVE_WCSTOMBS) && defined(HAVE_TOWLOWER)
1103 #define USE_WIDE_UPPER_LOWER
1106 /* EXEC_BACKEND defines */
1108 #define NON_EXEC_STATIC
1110 #define NON_EXEC_STATIC static
1113 /* /port compatibility functions */