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-2011, 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
34 * 6) widely useful macros
36 * 8) system-specific hacks
38 * NOTE: since this file is included by both frontend and backend modules, it's
39 * almost certainly wrong to put an "extern" declaration here. typedefs and
40 * macros are the kind of thing that might go here.
42 *----------------------------------------------------------------
48 * We have to include stdlib.h here because it defines many of these macros
49 * on some platforms, and we only want our definitions used if stdlib.h doesn't
50 * have its own. The same goes for stddef and stdarg if present.
53 #include "pg_config.h"
54 #include "pg_config_manual.h" /* must be after pg_config.h */
55 #if !defined(WIN32) && !defined(__CYGWIN__) /* win32 will include further
57 #include "pg_config_os.h" /* must be before any system header files */
59 #include "postgres_ext.h"
61 #define HAVE_CRTDEFS_H 1
62 #if _MSC_VER >= 1400 || defined(HAVE_CRTDEFS_H)
63 #define errcode __msvc_errcode
79 #include <sys/types.h>
82 #if defined(WIN32) || defined(__CYGWIN__)
83 #include <fcntl.h> /* ensure O_BINARY is available */
85 #ifdef HAVE_SUPPORTDEFS_H
86 #include <SupportDefs.h>
89 #if defined(WIN32) || defined(__CYGWIN__)
90 /* We have to redefine some system functions after they are included above. */
91 #include "pg_config_os.h"
94 /* Must be before gettext() games below */
97 #define _(x) gettext(x)
102 #define gettext(x) (x)
103 #define dgettext(d,x) (x)
104 #define ngettext(s,p,n) ((n) == 1 ? (s) : (p))
105 #define dngettext(d,s,p,n) ((n) == 1 ? (s) : (p))
109 * Use this to mark string constants as needing translation at some later
110 * time, rather than immediately. This is useful for cases where you need
111 * access to the original string and translated string, and for cases where
112 * immediate translation is not possible, like when initializing global
114 * http://www.gnu.org/software/autoconf/manual/gettext/Special-cases.html
116 #define gettext_noop(x) (x)
119 /* ----------------------------------------------------------------
120 * Section 1: hacks to cope with non-ANSI C compilers
122 * type prefixes (const, signed, volatile, inline) are handled in pg_config.h.
123 * ----------------------------------------------------------------
128 * Convert the argument to a string, using the C preprocessor.
130 * Concatenate two arguments together, using the C preprocessor.
132 * Note: the standard Autoconf macro AC_C_STRINGIZE actually only checks
133 * whether #identifier works, but if we have that we likely have ## too.
135 #if defined(HAVE_STRINGIZE)
137 #define CppAsString(identifier) #identifier
138 #define CppConcat(x, y) x##y
139 #else /* !HAVE_STRINGIZE */
141 #define CppAsString(identifier) "identifier"
144 * CppIdentity -- On Reiser based cpp's this is used to concatenate
145 * two tokens. That is
146 * CppIdentity(A)B ==> AB
147 * We renamed it to _private_CppIdentity because it should not
148 * be referenced outside this file. On other cpp's it
151 #define _priv_CppIdentity(x)x
152 #define CppConcat(x, y) _priv_CppIdentity(x)y
153 #endif /* !HAVE_STRINGIZE */
156 * dummyret is used to set return values in macros that use ?: to make
157 * assignments. gcc wants these to be void, other compilers like char
159 #ifdef __GNUC__ /* GNU cc */
160 #define dummyret void
162 #define dummyret char
166 #define __attribute__(_arg_)
169 /* ----------------------------------------------------------------
170 * Section 2: bool, true, false, TRUE, FALSE, NULL
171 * ----------------------------------------------------------------
176 * Boolean value, either true or false.
178 * XXX for C++ compilers, we assume the compiler has a compatible
179 * built-in definition of bool.
189 #define true ((bool) 1)
193 #define false ((bool) 0)
197 typedef bool *BoolPtr;
212 #define NULL ((void *) 0)
216 /* ----------------------------------------------------------------
217 * Section 3: standard system types
218 * ----------------------------------------------------------------
223 * Variable holding address of any memory resident object.
225 * XXX Pointer arithmetic is done with this, so it can't be void *
226 * under "true" ANSI compilers.
228 typedef char *Pointer;
232 * Signed integer, EXACTLY N BITS IN SIZE,
233 * used for numerical computations and the
234 * frontend/backend protocol.
237 typedef signed char int8; /* == 8 bits */
238 typedef signed short int16; /* == 16 bits */
239 typedef signed int int32; /* == 32 bits */
240 #endif /* not HAVE_INT8 */
244 * Unsigned integer, EXACTLY N BITS IN SIZE,
245 * used for numerical computations and the
246 * frontend/backend protocol.
249 typedef unsigned char uint8; /* == 8 bits */
250 typedef unsigned short uint16; /* == 16 bits */
251 typedef unsigned int uint32; /* == 32 bits */
252 #endif /* not HAVE_UINT8 */
256 * Unit of bitwise operation, AT LEAST N BITS IN SIZE.
258 typedef uint8 bits8; /* >= 8 bits */
259 typedef uint16 bits16; /* >= 16 bits */
260 typedef uint32 bits32; /* >= 32 bits */
265 #ifdef HAVE_LONG_INT_64
266 /* Plain "long int" fits, use it */
269 typedef long int int64;
272 typedef unsigned long int uint64;
274 #elif defined(HAVE_LONG_LONG_INT_64)
275 /* We have working support for "long long int", use that */
278 typedef long long int int64;
281 typedef unsigned long long int uint64;
284 /* neither HAVE_LONG_INT_64 nor HAVE_LONG_LONG_INT_64 */
285 #error must have a working 64-bit integer datatype
288 /* Decide if we need to decorate 64-bit constants */
289 #ifdef HAVE_LL_CONSTANTS
290 #define INT64CONST(x) ((int64) x##LL)
291 #define UINT64CONST(x) ((uint64) x##ULL)
293 #define INT64CONST(x) ((int64) x)
294 #define UINT64CONST(x) ((uint64) x)
298 /* Select timestamp representation (float8 or int64) */
299 #ifdef USE_INTEGER_DATETIMES
300 #define HAVE_INT64_TIMESTAMP
303 /* sig_atomic_t is required by ANSI C, but may be missing on old platforms */
304 #ifndef HAVE_SIG_ATOMIC_T
305 typedef int sig_atomic_t;
310 * Size of any memory resident object, as returned by sizeof.
316 * Index into any memory resident array.
319 * Indices are non negative.
321 typedef unsigned int Index;
325 * Offset into any memory resident array.
328 * This differs from an Index in that an Index is always
329 * non negative, whereas Offset may be negative.
331 typedef signed int Offset;
334 * Common Postgres datatype names (as used in the catalogs)
338 typedef float float4;
339 typedef double float8;
342 * Oid, RegProcedure, TransactionId, SubTransactionId, MultiXactId,
346 /* typedef Oid is in postgres_ext.h */
349 * regproc is the type name used in the include/catalog headers, but
350 * RegProcedure is the preferred name in C code.
353 typedef regproc RegProcedure;
355 typedef uint32 TransactionId;
357 typedef uint32 LocalTransactionId;
359 typedef uint32 SubTransactionId;
361 #define InvalidSubTransactionId ((SubTransactionId) 0)
362 #define TopSubTransactionId ((SubTransactionId) 1)
364 /* MultiXactId must be equivalent to TransactionId, to fit in t_xmax */
365 typedef TransactionId MultiXactId;
367 typedef uint32 MultiXactOffset;
369 typedef uint32 CommandId;
371 #define FirstCommandId ((CommandId) 0)
374 * Array indexing support
383 * Variable-length datatypes all share the 'struct varlena' header.
385 * NOTE: for TOASTable types, this is an oversimplification, since the value
386 * may be compressed or moved out-of-line. However datatype-specific routines
387 * are mostly content to deal with de-TOASTed values only, and of course
388 * client-side routines should never see a TOASTed value. But even in a
389 * de-TOASTed value, beware of touching vl_len_ directly, as its representation
390 * is no longer convenient. It's recommended that code always use the VARDATA,
391 * VARSIZE, and SET_VARSIZE macros instead of relying on direct mentions of
392 * the struct fields. See postgres.h for details of the TOASTed form.
397 char vl_len_[4]; /* Do not touch this field directly! */
401 #define VARHDRSZ ((int32) sizeof(int32))
404 * These widely-used datatypes are just a varlena header and the data bytes.
405 * There is no terminating null or anything like that --- the data length is
406 * always VARSIZE(ptr) - VARHDRSZ.
408 typedef struct varlena bytea;
409 typedef struct varlena text;
410 typedef struct varlena BpChar; /* blank-padded char, ie SQL char(n) */
411 typedef struct varlena VarChar; /* var-length char, ie SQL varchar(n) */
414 * Specialized array types. These are physically laid out just the same
415 * as regular arrays (so that the regular array subscripting code works
416 * with them). They exist as distinct types mostly for historical reasons:
417 * they have nonstandard I/O behavior which we don't want to change for fear
418 * of breaking applications that look at the system catalogs. There is also
419 * an implementation issue for oidvector: it's part of the primary key for
420 * pg_proc, and we can't use the normal btree array support routines for that
421 * without circularity.
425 int32 vl_len_; /* these fields must match ArrayType! */
426 int ndim; /* always 1 for int2vector */
427 int32 dataoffset; /* always 0 for int2vector */
431 int2 values[1]; /* VARIABLE LENGTH ARRAY */
432 } int2vector; /* VARIABLE LENGTH STRUCT */
436 int32 vl_len_; /* these fields must match ArrayType! */
437 int ndim; /* always 1 for oidvector */
438 int32 dataoffset; /* always 0 for oidvector */
442 Oid values[1]; /* VARIABLE LENGTH ARRAY */
443 } oidvector; /* VARIABLE LENGTH STRUCT */
446 * Representation of a Name: effectively just a C string, but null-padded to
447 * exactly NAMEDATALEN bytes. The use of a struct is historical.
449 typedef struct nameData
451 char data[NAMEDATALEN];
453 typedef NameData *Name;
455 #define NameStr(name) ((name).data)
458 * Support macros for escaping strings. escape_backslash should be TRUE
459 * if generating a non-standard-conforming string. Prefixing a string
460 * with ESCAPE_STRING_SYNTAX guarantees it is non-standard-conforming.
461 * Beware of multiple evaluation of the "ch" argument!
463 #define SQL_STR_DOUBLE(ch, escape_backslash) \
464 ((ch) == '\'' || ((ch) == '\\' && (escape_backslash)))
466 #define ESCAPE_STRING_SYNTAX 'E'
468 /* ----------------------------------------------------------------
469 * Section 4: IsValid macros for system types
470 * ----------------------------------------------------------------
474 * True iff bool is valid.
476 #define BoolIsValid(boolean) ((boolean) == false || (boolean) == true)
480 * True iff pointer is valid.
482 #define PointerIsValid(pointer) ((void*)(pointer) != NULL)
486 * True iff pointer is properly aligned to point to the given type.
488 #define PointerIsAligned(pointer, type) \
489 (((intptr_t)(pointer) % (sizeof (type))) == 0)
491 #define OidIsValid(objectId) ((bool) ((objectId) != InvalidOid))
493 #define RegProcedureIsValid(p) OidIsValid(p)
496 /* ----------------------------------------------------------------
497 * Section 5: offsetof, lengthof, endof, alignment
498 * ----------------------------------------------------------------
502 * Offset of a structure/union field within that structure/union.
504 * XXX This is supposed to be part of stddef.h, but isn't on
505 * some systems (like SunOS 4).
508 #define offsetof(type, field) ((long) &((type *)0)->field)
509 #endif /* offsetof */
513 * Number of elements in an array.
515 #define lengthof(array) (sizeof (array) / sizeof ((array)[0]))
519 * Address of the element one past the last in an array.
521 #define endof(array) (&(array)[lengthof(array)])
524 * Alignment macros: align a length or address appropriately for a given type.
525 * The fooALIGN() macros round up to a multiple of the required alignment,
526 * while the fooALIGN_DOWN() macros round down. The latter are more useful
527 * for problems like "how many X-sized structures will fit in a page?".
529 * NOTE: TYPEALIGN[_DOWN] will not work if ALIGNVAL is not a power of 2.
530 * That case seems extremely unlikely to be needed in practice, however.
534 #define TYPEALIGN(ALIGNVAL,LEN) \
535 (((intptr_t) (LEN) + ((ALIGNVAL) - 1)) & ~((intptr_t) ((ALIGNVAL) - 1)))
537 #define SHORTALIGN(LEN) TYPEALIGN(ALIGNOF_SHORT, (LEN))
538 #define INTALIGN(LEN) TYPEALIGN(ALIGNOF_INT, (LEN))
539 #define LONGALIGN(LEN) TYPEALIGN(ALIGNOF_LONG, (LEN))
540 #define DOUBLEALIGN(LEN) TYPEALIGN(ALIGNOF_DOUBLE, (LEN))
541 #define MAXALIGN(LEN) TYPEALIGN(MAXIMUM_ALIGNOF, (LEN))
542 /* MAXALIGN covers only built-in types, not buffers */
543 #define BUFFERALIGN(LEN) TYPEALIGN(ALIGNOF_BUFFER, (LEN))
545 #define TYPEALIGN_DOWN(ALIGNVAL,LEN) \
546 (((intptr_t) (LEN)) & ~((intptr_t) ((ALIGNVAL) - 1)))
548 #define SHORTALIGN_DOWN(LEN) TYPEALIGN_DOWN(ALIGNOF_SHORT, (LEN))
549 #define INTALIGN_DOWN(LEN) TYPEALIGN_DOWN(ALIGNOF_INT, (LEN))
550 #define LONGALIGN_DOWN(LEN) TYPEALIGN_DOWN(ALIGNOF_LONG, (LEN))
551 #define DOUBLEALIGN_DOWN(LEN) TYPEALIGN_DOWN(ALIGNOF_DOUBLE, (LEN))
552 #define MAXALIGN_DOWN(LEN) TYPEALIGN_DOWN(MAXIMUM_ALIGNOF, (LEN))
554 /* ----------------------------------------------------------------
555 * Section 6: widely useful macros
556 * ----------------------------------------------------------------
560 * Return the maximum of two numbers.
562 #define Max(x, y) ((x) > (y) ? (x) : (y))
566 * Return the minimum of two numbers.
568 #define Min(x, y) ((x) < (y) ? (x) : (y))
572 * Return the absolute value of the argument.
574 #define Abs(x) ((x) >= 0 ? (x) : -(x))
578 * Like standard library function strncpy(), except that result string
579 * is guaranteed to be null-terminated --- that is, at most N-1 bytes
580 * of the source string will be kept.
581 * Also, the macro returns no result (too hard to do that without
582 * evaluating the arguments multiple times, which seems worse).
584 * BTW: when you need to copy a non-null-terminated string (like a text
585 * datum) and add a null, do not do it with StrNCpy(..., len+1). That
586 * might seem to work, but it fetches one byte more than there is in the
587 * text object. One fine day you'll have a SIGSEGV because there isn't
588 * another byte before the end of memory. Don't laugh, we've had real
589 * live bug reports from real live users over exactly this mistake.
590 * Do it honestly with "memcpy(dst,src,len); dst[len] = '\0';", instead.
592 #define StrNCpy(dst,src,len) \
595 char * _dst = (dst); \
600 strncpy(_dst, (src), _len); \
601 _dst[_len-1] = '\0'; \
606 /* Get a bit mask of the bits set in non-long aligned addresses */
607 #define LONG_ALIGN_MASK (sizeof(long) - 1)
611 * Exactly the same as standard library function memset(), but considerably
612 * faster for zeroing small word-aligned structures (such as parsetree nodes).
613 * This has to be a macro because the main point is to avoid function-call
614 * overhead. However, we have also found that the loop is faster than
615 * native libc memset() on some platforms, even those with assembler
616 * memset() functions. More research needs to be done, perhaps with
617 * MEMSET_LOOP_LIMIT tests in configure.
619 #define MemSet(start, val, len) \
622 /* must be void* because we don't know if it is integer aligned yet */ \
623 void *_vstart = (void *) (start); \
627 if ((((intptr_t) _vstart) & LONG_ALIGN_MASK) == 0 && \
628 (_len & LONG_ALIGN_MASK) == 0 && \
630 _len <= MEMSET_LOOP_LIMIT && \
632 * If MEMSET_LOOP_LIMIT == 0, optimizer should find \
633 * the whole "if" false at compile time. \
635 MEMSET_LOOP_LIMIT != 0) \
637 long *_start = (long *) _vstart; \
638 long *_stop = (long *) ((char *) _start + _len); \
639 while (_start < _stop) \
643 memset(_vstart, _val, _len); \
647 * MemSetAligned is the same as MemSet except it omits the test to see if
648 * "start" is word-aligned. This is okay to use if the caller knows a-priori
649 * that the pointer is suitably aligned (typically, because he just got it
650 * from palloc(), which always delivers a max-aligned pointer).
652 #define MemSetAligned(start, val, len) \
655 long *_start = (long *) (start); \
659 if ((_len & LONG_ALIGN_MASK) == 0 && \
661 _len <= MEMSET_LOOP_LIMIT && \
662 MEMSET_LOOP_LIMIT != 0) \
664 long *_stop = (long *) ((char *) _start + _len); \
665 while (_start < _stop) \
669 memset(_start, _val, _len); \
674 * MemSetTest/MemSetLoop are a variant version that allow all the tests in
675 * MemSet to be done at compile time in cases where "val" and "len" are
676 * constants *and* we know the "start" pointer must be word-aligned.
677 * If MemSetTest succeeds, then it is okay to use MemSetLoop, otherwise use
678 * MemSetAligned. Beware of multiple evaluations of the arguments when using
681 #define MemSetTest(val, len) \
682 ( ((len) & LONG_ALIGN_MASK) == 0 && \
683 (len) <= MEMSET_LOOP_LIMIT && \
684 MEMSET_LOOP_LIMIT != 0 && \
687 #define MemSetLoop(start, val, len) \
690 long * _start = (long *) (start); \
691 long * _stop = (long *) ((char *) _start + (Size) (len)); \
693 while (_start < _stop) \
698 /* ----------------------------------------------------------------
699 * Section 7: random stuff
700 * ----------------------------------------------------------------
704 #define HIGHBIT (0x80)
705 #define IS_HIGHBIT_SET(ch) ((unsigned char)(ch) & HIGHBIT)
707 #define STATUS_OK (0)
708 #define STATUS_ERROR (-1)
709 #define STATUS_EOF (-2)
710 #define STATUS_FOUND (1)
711 #define STATUS_WAITING (2)
714 /* gettext domain name mangling */
717 * To better support parallel installations of major PostgeSQL
718 * versions as well as parallel installations of major library soname
719 * versions, we mangle the gettext domain name by appending those
720 * version numbers. The coding rule ought to be that whereever the
721 * domain name is mentioned as a literal, it must be wrapped into
722 * PG_TEXTDOMAIN(). The macros below do not work on non-literals; but
723 * that is somewhat intentional because it avoids having to worry
724 * about multiple states of premangling and postmangling as the values
725 * are being passed around.
727 * Make sure this matches the installation rules in nls-global.mk.
730 /* need a second indirection because we want to stringize the macro value, not the name */
731 #define CppAsString2(x) CppAsString(x)
733 #ifdef SO_MAJOR_VERSION
734 #define PG_TEXTDOMAIN(domain) (domain CppAsString2(SO_MAJOR_VERSION) "-" PG_MAJORVERSION)
736 #define PG_TEXTDOMAIN(domain) (domain "-" PG_MAJORVERSION)
740 /* ----------------------------------------------------------------
741 * Section 8: system-specific hacks
743 * This should be limited to things that absolutely have to be
744 * included in every source file. The port-specific header file
745 * is usually a better place for this sort of thing.
746 * ----------------------------------------------------------------
750 * NOTE: this is also used for opening text files.
751 * WIN32 treats Control-Z as EOF in files opened in text mode.
752 * Therefore, we open files in binary mode on Win32 so we can read
753 * literal control-Z. The other affect is that we see CRLF, but
754 * that is OK because we can already handle those cleanly.
756 #if defined(WIN32) || defined(__CYGWIN__)
757 #define PG_BINARY O_BINARY
758 #define PG_BINARY_A "ab"
759 #define PG_BINARY_R "rb"
760 #define PG_BINARY_W "wb"
763 #define PG_BINARY_A "a"
764 #define PG_BINARY_R "r"
765 #define PG_BINARY_W "w"
769 * Provide prototypes for routines not present in a particular machine's
770 * standard C library.
773 #if !HAVE_DECL_SNPRINTF
775 snprintf(char *str, size_t count, const char *fmt,...)
776 /* This extension allows gcc to check the format string */
777 __attribute__((format(PG_PRINTF_ATTRIBUTE, 3, 4)));
780 #if !HAVE_DECL_VSNPRINTF
781 extern int vsnprintf(char *str, size_t count, const char *fmt, va_list args);
784 #if !defined(HAVE_MEMMOVE) && !defined(memmove)
785 #define memmove(d, s, c) bcopy(s, d, c)
788 /* no special DLL markers on most ports */
797 * The following is used as the arg list for signal handlers. Any ports
798 * that take something other than an int argument should override this in
799 * their pg_config_os.h file. Note that variable names are required
800 * because it is used in both the prototypes as well as the definitions.
801 * Note also the long name. We expect that this won't collide with
802 * other names causing compiler warnings.
806 #define SIGNAL_ARGS int postgres_signal_arg
810 * When there is no sigsetjmp, its functionality is provided by plain
811 * setjmp. Incidentally, nothing provides setjmp's functionality in
814 #ifndef HAVE_SIGSETJMP
815 #define sigjmp_buf jmp_buf
816 #define sigsetjmp(x,y) setjmp(x)
817 #define siglongjmp longjmp
820 #if defined(HAVE_FDATASYNC) && !HAVE_DECL_FDATASYNC
821 extern int fdatasync(int fildes);
824 /* If strtoq() exists, rename it to the more standard strtoll() */
825 #if defined(HAVE_LONG_LONG_INT_64) && !defined(HAVE_STRTOLL) && defined(HAVE_STRTOQ)
826 #define strtoll strtoq
827 #define HAVE_STRTOLL 1
830 /* If strtouq() exists, rename it to the more standard strtoull() */
831 #if defined(HAVE_LONG_LONG_INT_64) && !defined(HAVE_STRTOULL) && defined(HAVE_STRTOUQ)
832 #define strtoull strtouq
833 #define HAVE_STRTOULL 1
837 * We assume if we have these two functions, we have their friends too, and
838 * can use the wide-character functions.
840 #if defined(HAVE_WCSTOMBS) && defined(HAVE_TOWLOWER)
841 #define USE_WIDE_UPPER_LOWER
844 /* EXEC_BACKEND defines */
846 #define NON_EXEC_STATIC
848 #define NON_EXEC_STATIC static
851 /* /port compatibility functions */