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-2008, PostgreSQL Global Development Group
13 * Portions Copyright (c) 1994, Regents of the University of California
15 * $PostgreSQL: pgsql/src/include/c.h,v 1.232 2008/12/11 09:17:07 petere Exp $
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"
62 #define errcode __msvc_errcode
75 #include <sys/types.h>
78 #if defined(WIN32) || defined(__CYGWIN__)
79 #include <fcntl.h> /* ensure O_BINARY is available */
81 #ifdef HAVE_SUPPORTDEFS_H
82 #include <SupportDefs.h>
85 #if defined(WIN32) || defined(__CYGWIN__)
86 /* We have to redefine some system functions after they are included above. */
87 #include "pg_config_os.h"
90 /* Must be before gettext() games below */
93 #define _(x) gettext(x)
98 #define gettext(x) (x)
99 #define dgettext(d,x) (x)
103 * Use this to mark string constants as needing translation at some later
104 * time, rather than immediately. This is useful for cases where you need
105 * access to the original string and translated string, and for cases where
106 * immediate translation is not possible, like when initializing global
108 * http://www.gnu.org/software/autoconf/manual/gettext/Special-cases.html
110 #define gettext_noop(x) (x)
113 /* ----------------------------------------------------------------
114 * Section 1: hacks to cope with non-ANSI C compilers
116 * type prefixes (const, signed, volatile, inline) are handled in pg_config.h.
117 * ----------------------------------------------------------------
122 * Convert the argument to a string, using the C preprocessor.
124 * Concatenate two arguments together, using the C preprocessor.
126 * Note: the standard Autoconf macro AC_C_STRINGIZE actually only checks
127 * whether #identifier works, but if we have that we likely have ## too.
129 #if defined(HAVE_STRINGIZE)
131 #define CppAsString(identifier) #identifier
132 #define CppConcat(x, y) x##y
133 #else /* !HAVE_STRINGIZE */
135 #define CppAsString(identifier) "identifier"
138 * CppIdentity -- On Reiser based cpp's this is used to concatenate
139 * two tokens. That is
140 * CppIdentity(A)B ==> AB
141 * We renamed it to _private_CppIdentity because it should not
142 * be referenced outside this file. On other cpp's it
145 #define _priv_CppIdentity(x)x
146 #define CppConcat(x, y) _priv_CppIdentity(x)y
147 #endif /* !HAVE_STRINGIZE */
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
160 #define __attribute__(_arg_)
163 /* ----------------------------------------------------------------
164 * Section 2: bool, true, false, TRUE, FALSE, NULL
165 * ----------------------------------------------------------------
170 * Boolean value, either true or false.
172 * XXX for C++ compilers, we assume the compiler has a compatible
173 * built-in definition of bool.
183 #define true ((bool) 1)
187 #define false ((bool) 0)
191 typedef bool *BoolPtr;
206 #define NULL ((void *) 0)
210 /* ----------------------------------------------------------------
211 * Section 3: standard system types
212 * ----------------------------------------------------------------
217 * Variable holding address of any memory resident object.
219 * XXX Pointer arithmetic is done with this, so it can't be void *
220 * under "true" ANSI compilers.
222 typedef char *Pointer;
226 * Signed integer, EXACTLY N BITS IN SIZE,
227 * used for numerical computations and the
228 * frontend/backend protocol.
231 typedef signed char int8; /* == 8 bits */
232 typedef signed short int16; /* == 16 bits */
233 typedef signed int int32; /* == 32 bits */
234 #endif /* not HAVE_INT8 */
238 * Unsigned integer, EXACTLY N BITS IN SIZE,
239 * used for numerical computations and the
240 * frontend/backend protocol.
243 typedef unsigned char uint8; /* == 8 bits */
244 typedef unsigned short uint16; /* == 16 bits */
245 typedef unsigned int uint32; /* == 32 bits */
246 #endif /* not HAVE_UINT8 */
250 * Unit of bitwise operation, AT LEAST N BITS IN SIZE.
252 typedef uint8 bits8; /* >= 8 bits */
253 typedef uint16 bits16; /* >= 16 bits */
254 typedef uint32 bits32; /* >= 32 bits */
259 #ifdef HAVE_LONG_INT_64
260 /* Plain "long int" fits, use it */
263 typedef long int int64;
266 typedef unsigned long int uint64;
268 #elif defined(HAVE_LONG_LONG_INT_64)
269 /* We have working support for "long long int", use that */
272 typedef long long int int64;
275 typedef unsigned long long int uint64;
277 #else /* not HAVE_LONG_INT_64 and not
278 * HAVE_LONG_LONG_INT_64 */
280 /* Won't actually work, but fall back to long int so that code compiles */
282 typedef long int int64;
285 typedef unsigned long int uint64;
288 #define INT64_IS_BUSTED
289 #endif /* not HAVE_LONG_INT_64 and not
290 * HAVE_LONG_LONG_INT_64 */
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)
302 /* Select timestamp representation (float8 or int64) */
303 #if defined(USE_INTEGER_DATETIMES) && !defined(INT64_IS_BUSTED)
304 #define HAVE_INT64_TIMESTAMP
307 /* sig_atomic_t is required by ANSI C, but may be missing on old platforms */
308 #ifndef HAVE_SIG_ATOMIC_T
309 typedef int sig_atomic_t;
314 * Size of any memory resident object, as returned by sizeof.
320 * Index into any memory resident array.
323 * Indices are non negative.
325 typedef unsigned int Index;
329 * Offset into any memory resident array.
332 * This differs from an Index in that an Index is always
333 * non negative, whereas Offset may be negative.
335 typedef signed int Offset;
338 * Common Postgres datatype names (as used in the catalogs)
342 typedef float float4;
343 typedef double float8;
346 * Oid, RegProcedure, TransactionId, SubTransactionId, MultiXactId,
350 /* typedef Oid is in postgres_ext.h */
353 * regproc is the type name used in the include/catalog headers, but
354 * RegProcedure is the preferred name in C code.
357 typedef regproc RegProcedure;
359 typedef uint32 TransactionId;
361 typedef uint32 LocalTransactionId;
363 typedef uint32 SubTransactionId;
365 #define InvalidSubTransactionId ((SubTransactionId) 0)
366 #define TopSubTransactionId ((SubTransactionId) 1)
368 /* MultiXactId must be equivalent to TransactionId, to fit in t_xmax */
369 typedef TransactionId MultiXactId;
371 typedef uint32 MultiXactOffset;
373 typedef uint32 CommandId;
375 #define FirstCommandId ((CommandId) 0)
378 * Array indexing support
387 * Variable-length datatypes all share the 'struct varlena' header.
389 * NOTE: for TOASTable types, this is an oversimplification, since the value
390 * may be compressed or moved out-of-line. However datatype-specific routines
391 * are mostly content to deal with de-TOASTed values only, and of course
392 * client-side routines should never see a TOASTed value. But even in a
393 * de-TOASTed value, beware of touching vl_len_ directly, as its representation
394 * is no longer convenient. It's recommended that code always use the VARDATA,
395 * VARSIZE, and SET_VARSIZE macros instead of relying on direct mentions of
396 * the struct fields. See postgres.h for details of the TOASTed form.
401 char vl_len_[4]; /* Do not touch this field directly! */
405 #define VARHDRSZ ((int32) sizeof(int32))
408 * These widely-used datatypes are just a varlena header and the data bytes.
409 * There is no terminating null or anything like that --- the data length is
410 * always VARSIZE(ptr) - VARHDRSZ.
412 typedef struct varlena bytea;
413 typedef struct varlena text;
414 typedef struct varlena BpChar; /* blank-padded char, ie SQL char(n) */
415 typedef struct varlena VarChar; /* var-length char, ie SQL varchar(n) */
418 * Specialized array types. These are physically laid out just the same
419 * as regular arrays (so that the regular array subscripting code works
420 * with them). They exist as distinct types mostly for historical reasons:
421 * they have nonstandard I/O behavior which we don't want to change for fear
422 * of breaking applications that look at the system catalogs. There is also
423 * an implementation issue for oidvector: it's part of the primary key for
424 * pg_proc, and we can't use the normal btree array support routines for that
425 * without circularity.
429 int32 vl_len_; /* these fields must match ArrayType! */
430 int ndim; /* always 1 for int2vector */
431 int32 dataoffset; /* always 0 for int2vector */
435 int2 values[1]; /* VARIABLE LENGTH ARRAY */
436 } int2vector; /* VARIABLE LENGTH STRUCT */
440 int32 vl_len_; /* these fields must match ArrayType! */
441 int ndim; /* always 1 for oidvector */
442 int32 dataoffset; /* always 0 for oidvector */
446 Oid values[1]; /* VARIABLE LENGTH ARRAY */
447 } oidvector; /* VARIABLE LENGTH STRUCT */
450 * Representation of a Name: effectively just a C string, but null-padded to
451 * exactly NAMEDATALEN bytes. The use of a struct is historical.
453 typedef struct nameData
455 char data[NAMEDATALEN];
457 typedef NameData *Name;
459 #define NameStr(name) ((name).data)
462 * Support macros for escaping strings. escape_backslash should be TRUE
463 * if generating a non-standard-conforming string. Prefixing a string
464 * with ESCAPE_STRING_SYNTAX guarantees it is non-standard-conforming.
465 * Beware of multiple evaluation of the "ch" argument!
467 #define SQL_STR_DOUBLE(ch, escape_backslash) \
468 ((ch) == '\'' || ((ch) == '\\' && (escape_backslash)))
470 #define ESCAPE_STRING_SYNTAX 'E'
472 /* ----------------------------------------------------------------
473 * Section 4: IsValid macros for system types
474 * ----------------------------------------------------------------
478 * True iff bool is valid.
480 #define BoolIsValid(boolean) ((boolean) == false || (boolean) == true)
484 * True iff pointer is valid.
486 #define PointerIsValid(pointer) ((void*)(pointer) != NULL)
490 * True iff pointer is properly aligned to point to the given type.
492 #define PointerIsAligned(pointer, type) \
493 (((long)(pointer) % (sizeof (type))) == 0)
495 #define OidIsValid(objectId) ((bool) ((objectId) != InvalidOid))
497 #define RegProcedureIsValid(p) OidIsValid(p)
500 /* ----------------------------------------------------------------
501 * Section 5: offsetof, lengthof, endof, alignment
502 * ----------------------------------------------------------------
506 * Offset of a structure/union field within that structure/union.
508 * XXX This is supposed to be part of stddef.h, but isn't on
509 * some systems (like SunOS 4).
512 #define offsetof(type, field) ((long) &((type *)0)->field)
513 #endif /* offsetof */
517 * Number of elements in an array.
519 #define lengthof(array) (sizeof (array) / sizeof ((array)[0]))
523 * Address of the element one past the last in an array.
525 #define endof(array) (&(array)[lengthof(array)])
528 * Alignment macros: align a length or address appropriately for a given type.
529 * The fooALIGN() macros round up to a multiple of the required alignment,
530 * while the fooALIGN_DOWN() macros round down. The latter are more useful
531 * for problems like "how many X-sized structures will fit in a page?".
533 * NOTE: TYPEALIGN[_DOWN] will not work if ALIGNVAL is not a power of 2.
534 * That case seems extremely unlikely to be needed in practice, however.
538 #define TYPEALIGN(ALIGNVAL,LEN) \
539 (((long) (LEN) + ((ALIGNVAL) - 1)) & ~((long) ((ALIGNVAL) - 1)))
541 #define SHORTALIGN(LEN) TYPEALIGN(ALIGNOF_SHORT, (LEN))
542 #define INTALIGN(LEN) TYPEALIGN(ALIGNOF_INT, (LEN))
543 #define LONGALIGN(LEN) TYPEALIGN(ALIGNOF_LONG, (LEN))
544 #define DOUBLEALIGN(LEN) TYPEALIGN(ALIGNOF_DOUBLE, (LEN))
545 #define MAXALIGN(LEN) TYPEALIGN(MAXIMUM_ALIGNOF, (LEN))
546 /* MAXALIGN covers only built-in types, not buffers */
547 #define BUFFERALIGN(LEN) TYPEALIGN(ALIGNOF_BUFFER, (LEN))
549 #define TYPEALIGN_DOWN(ALIGNVAL,LEN) \
550 (((long) (LEN)) & ~((long) ((ALIGNVAL) - 1)))
552 #define SHORTALIGN_DOWN(LEN) TYPEALIGN_DOWN(ALIGNOF_SHORT, (LEN))
553 #define INTALIGN_DOWN(LEN) TYPEALIGN_DOWN(ALIGNOF_INT, (LEN))
554 #define LONGALIGN_DOWN(LEN) TYPEALIGN_DOWN(ALIGNOF_LONG, (LEN))
555 #define DOUBLEALIGN_DOWN(LEN) TYPEALIGN_DOWN(ALIGNOF_DOUBLE, (LEN))
556 #define MAXALIGN_DOWN(LEN) TYPEALIGN_DOWN(MAXIMUM_ALIGNOF, (LEN))
558 /* ----------------------------------------------------------------
559 * Section 6: widely useful macros
560 * ----------------------------------------------------------------
564 * Return the maximum of two numbers.
566 #define Max(x, y) ((x) > (y) ? (x) : (y))
570 * Return the minimum of two numbers.
572 #define Min(x, y) ((x) < (y) ? (x) : (y))
576 * Return the absolute value of the argument.
578 #define Abs(x) ((x) >= 0 ? (x) : -(x))
582 * Like standard library function strncpy(), except that result string
583 * is guaranteed to be null-terminated --- that is, at most N-1 bytes
584 * of the source string will be kept.
585 * Also, the macro returns no result (too hard to do that without
586 * evaluating the arguments multiple times, which seems worse).
588 * BTW: when you need to copy a non-null-terminated string (like a text
589 * datum) and add a null, do not do it with StrNCpy(..., len+1). That
590 * might seem to work, but it fetches one byte more than there is in the
591 * text object. One fine day you'll have a SIGSEGV because there isn't
592 * another byte before the end of memory. Don't laugh, we've had real
593 * live bug reports from real live users over exactly this mistake.
594 * Do it honestly with "memcpy(dst,src,len); dst[len] = '\0';", instead.
596 #define StrNCpy(dst,src,len) \
599 char * _dst = (dst); \
604 strncpy(_dst, (src), _len); \
605 _dst[_len-1] = '\0'; \
610 /* Get a bit mask of the bits set in non-long aligned addresses */
611 #define LONG_ALIGN_MASK (sizeof(long) - 1)
615 * Exactly the same as standard library function memset(), but considerably
616 * faster for zeroing small word-aligned structures (such as parsetree nodes).
617 * This has to be a macro because the main point is to avoid function-call
618 * overhead. However, we have also found that the loop is faster than
619 * native libc memset() on some platforms, even those with assembler
620 * memset() functions. More research needs to be done, perhaps with
621 * MEMSET_LOOP_LIMIT tests in configure.
623 #define MemSet(start, val, len) \
626 /* must be void* because we don't know if it is integer aligned yet */ \
627 void *_vstart = (void *) (start); \
631 if ((((long) _vstart) & LONG_ALIGN_MASK) == 0 && \
632 (_len & LONG_ALIGN_MASK) == 0 && \
634 _len <= MEMSET_LOOP_LIMIT && \
636 * If MEMSET_LOOP_LIMIT == 0, optimizer should find \
637 * the whole "if" false at compile time. \
639 MEMSET_LOOP_LIMIT != 0) \
641 long *_start = (long *) _vstart; \
642 long *_stop = (long *) ((char *) _start + _len); \
643 while (_start < _stop) \
647 memset(_vstart, _val, _len); \
651 * MemSetAligned is the same as MemSet except it omits the test to see if
652 * "start" is word-aligned. This is okay to use if the caller knows a-priori
653 * that the pointer is suitably aligned (typically, because he just got it
654 * from palloc(), which always delivers a max-aligned pointer).
656 #define MemSetAligned(start, val, len) \
659 long *_start = (long *) (start); \
663 if ((_len & LONG_ALIGN_MASK) == 0 && \
665 _len <= MEMSET_LOOP_LIMIT && \
666 MEMSET_LOOP_LIMIT != 0) \
668 long *_stop = (long *) ((char *) _start + _len); \
669 while (_start < _stop) \
673 memset(_start, _val, _len); \
678 * MemSetTest/MemSetLoop are a variant version that allow all the tests in
679 * MemSet to be done at compile time in cases where "val" and "len" are
680 * constants *and* we know the "start" pointer must be word-aligned.
681 * If MemSetTest succeeds, then it is okay to use MemSetLoop, otherwise use
682 * MemSetAligned. Beware of multiple evaluations of the arguments when using
685 #define MemSetTest(val, len) \
686 ( ((len) & LONG_ALIGN_MASK) == 0 && \
687 (len) <= MEMSET_LOOP_LIMIT && \
688 MEMSET_LOOP_LIMIT != 0 && \
691 #define MemSetLoop(start, val, len) \
694 long * _start = (long *) (start); \
695 long * _stop = (long *) ((char *) _start + (Size) (len)); \
697 while (_start < _stop) \
702 /* ----------------------------------------------------------------
703 * Section 7: random stuff
704 * ----------------------------------------------------------------
708 #define HIGHBIT (0x80)
709 #define IS_HIGHBIT_SET(ch) ((unsigned char)(ch) & HIGHBIT)
711 #define STATUS_OK (0)
712 #define STATUS_ERROR (-1)
713 #define STATUS_EOF (-2)
714 #define STATUS_FOUND (1)
715 #define STATUS_WAITING (2)
718 /* gettext domain name mangling */
721 * To better support parallel installations of major PostgeSQL
722 * versions as well as parallel installations of major library soname
723 * versions, we mangle the gettext domain name by appending those
724 * version numbers. The coding rule ought to be that whereever the
725 * domain name is mentioned as a literal, it must be wrapped into
726 * PG_TEXTDOMAIN(). The macros below do not work on non-literals; but
727 * that is somewhat intentional because it avoids having to worry
728 * about multiple states of premangling and postmangling as the values
729 * are being passed around.
731 * Make sure this matches the installation rules in nls-global.mk.
734 /* need a second indirection because we want to stringize the macro value, not the name */
735 #define CppAsString2(x) CppAsString(x)
737 #ifdef SO_MAJOR_VERSION
738 # define PG_TEXTDOMAIN(domain) (domain CppAsString2(SO_MAJOR_VERSION) "-" PG_MAJORVERSION)
740 # define PG_TEXTDOMAIN(domain) (domain "-" PG_MAJORVERSION)
744 /* ----------------------------------------------------------------
745 * Section 8: system-specific hacks
747 * This should be limited to things that absolutely have to be
748 * included in every source file. The port-specific header file
749 * is usually a better place for this sort of thing.
750 * ----------------------------------------------------------------
754 * NOTE: this is also used for opening text files.
755 * WIN32 treats Control-Z as EOF in files opened in text mode.
756 * Therefore, we open files in binary mode on Win32 so we can read
757 * literal control-Z. The other affect is that we see CRLF, but
758 * that is OK because we can already handle those cleanly.
760 #if defined(WIN32) || defined(__CYGWIN__)
761 #define PG_BINARY O_BINARY
762 #define PG_BINARY_A "ab"
763 #define PG_BINARY_R "rb"
764 #define PG_BINARY_W "wb"
767 #define PG_BINARY_A "a"
768 #define PG_BINARY_R "r"
769 #define PG_BINARY_W "w"
772 /* These are for things that are one way on Unix and another on NT */
773 #define NULL_DEV "/dev/null"
776 * Provide prototypes for routines not present in a particular machine's
777 * standard C library.
780 #if !HAVE_DECL_SNPRINTF
782 snprintf(char *str, size_t count, const char *fmt,...)
783 /* This extension allows gcc to check the format string */
784 __attribute__((format(printf, 3, 4)));
787 #if !HAVE_DECL_VSNPRINTF
788 extern int vsnprintf(char *str, size_t count, const char *fmt, va_list args);
791 #if !defined(HAVE_MEMMOVE) && !defined(memmove)
792 #define memmove(d, s, c) bcopy(s, d, c)
796 #define PGDLLIMPORT /* no special DLL markers on most ports */
800 * The following is used as the arg list for signal handlers. Any ports
801 * that take something other than an int argument should override this in
802 * their pg_config_os.h file. Note that variable names are required
803 * because it is used in both the prototypes as well as the definitions.
804 * Note also the long name. We expect that this won't collide with
805 * other names causing compiler warnings.
809 #define SIGNAL_ARGS int postgres_signal_arg
813 * When there is no sigsetjmp, its functionality is provided by plain
814 * setjmp. Incidentally, nothing provides setjmp's functionality in
817 #ifndef HAVE_SIGSETJMP
818 #define sigjmp_buf jmp_buf
819 #define sigsetjmp(x,y) setjmp(x)
820 #define siglongjmp longjmp
823 #if defined(HAVE_FDATASYNC) && !HAVE_DECL_FDATASYNC
824 extern int fdatasync(int fildes);
827 /* If strtoq() exists, rename it to the more standard strtoll() */
828 #if defined(HAVE_LONG_LONG_INT_64) && !defined(HAVE_STRTOLL) && defined(HAVE_STRTOQ)
829 #define strtoll strtoq
830 #define HAVE_STRTOLL 1
833 /* If strtouq() exists, rename it to the more standard strtoull() */
834 #if defined(HAVE_LONG_LONG_INT_64) && !defined(HAVE_STRTOULL) && defined(HAVE_STRTOUQ)
835 #define strtoull strtouq
836 #define HAVE_STRTOULL 1
840 * We assume if we have these two functions, we have their friends too, and
841 * can use the wide-character functions.
843 #if defined(HAVE_WCSTOMBS) && defined(HAVE_TOWLOWER)
844 #define USE_WIDE_UPPER_LOWER
847 /* EXEC_BACKEND defines */
849 #define NON_EXEC_STATIC
851 #define NON_EXEC_STATIC static
854 /* /port compatibility functions */