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.224 2008/03/17 19:44:41 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)
102 * Use this to mark strings to be translated by gettext, in places where
103 * you don't want an actual function call to occur (eg, constant tables).
105 #define gettext_noop(x) (x)
108 /* ----------------------------------------------------------------
109 * Section 1: hacks to cope with non-ANSI C compilers
111 * type prefixes (const, signed, volatile, inline) are handled in pg_config.h.
112 * ----------------------------------------------------------------
117 * Convert the argument to a string, using the C preprocessor.
119 * Concatenate two arguments together, using the C preprocessor.
121 * Note: the standard Autoconf macro AC_C_STRINGIZE actually only checks
122 * whether #identifier works, but if we have that we likely have ## too.
124 #if defined(HAVE_STRINGIZE)
126 #define CppAsString(identifier) #identifier
127 #define CppConcat(x, y) x##y
128 #else /* !HAVE_STRINGIZE */
130 #define CppAsString(identifier) "identifier"
133 * CppIdentity -- On Reiser based cpp's this is used to concatenate
134 * two tokens. That is
135 * CppIdentity(A)B ==> AB
136 * We renamed it to _private_CppIdentity because it should not
137 * be referenced outside this file. On other cpp's it
140 #define _priv_CppIdentity(x)x
141 #define CppConcat(x, y) _priv_CppIdentity(x)y
142 #endif /* !HAVE_STRINGIZE */
145 * dummyret is used to set return values in macros that use ?: to make
146 * assignments. gcc wants these to be void, other compilers like char
148 #ifdef __GNUC__ /* GNU cc */
149 #define dummyret void
151 #define dummyret char
155 #define __attribute__(_arg_)
158 /* ----------------------------------------------------------------
159 * Section 2: bool, true, false, TRUE, FALSE, NULL
160 * ----------------------------------------------------------------
165 * Boolean value, either true or false.
167 * XXX for C++ compilers, we assume the compiler has a compatible
168 * built-in definition of bool.
178 #define true ((bool) 1)
182 #define false ((bool) 0)
186 typedef bool *BoolPtr;
201 #define NULL ((void *) 0)
205 /* ----------------------------------------------------------------
206 * Section 3: standard system types
207 * ----------------------------------------------------------------
212 * Variable holding address of any memory resident object.
214 * XXX Pointer arithmetic is done with this, so it can't be void *
215 * under "true" ANSI compilers.
217 typedef char *Pointer;
221 * Signed integer, EXACTLY N BITS IN SIZE,
222 * used for numerical computations and the
223 * frontend/backend protocol.
226 typedef signed char int8; /* == 8 bits */
227 typedef signed short int16; /* == 16 bits */
228 typedef signed int int32; /* == 32 bits */
229 #endif /* not HAVE_INT8 */
233 * Unsigned integer, EXACTLY N BITS IN SIZE,
234 * used for numerical computations and the
235 * frontend/backend protocol.
238 typedef unsigned char uint8; /* == 8 bits */
239 typedef unsigned short uint16; /* == 16 bits */
240 typedef unsigned int uint32; /* == 32 bits */
241 #endif /* not HAVE_UINT8 */
245 * Unit of bitwise operation, AT LEAST N BITS IN SIZE.
247 typedef uint8 bits8; /* >= 8 bits */
248 typedef uint16 bits16; /* >= 16 bits */
249 typedef uint32 bits32; /* >= 32 bits */
253 * Floating point number, AT LEAST N BITS IN SIZE,
254 * used for numerical computations.
256 * Since sizeof(floatN) may be > sizeof(char *), always pass
257 * floatN by reference.
259 * XXX: these typedefs are now deprecated in favor of float4 and float8.
260 * They will eventually go away.
262 typedef float float32data;
263 typedef double float64data;
264 typedef float *float32;
265 typedef double *float64;
270 #ifdef HAVE_LONG_INT_64
271 /* Plain "long int" fits, use it */
274 typedef long int int64;
277 typedef unsigned long int uint64;
279 #elif defined(HAVE_LONG_LONG_INT_64)
280 /* We have working support for "long long int", use that */
283 typedef long long int int64;
286 typedef unsigned long long int uint64;
288 #else /* not HAVE_LONG_INT_64 and not
289 * HAVE_LONG_LONG_INT_64 */
291 /* Won't actually work, but fall back to long int so that code compiles */
293 typedef long int int64;
296 typedef unsigned long int uint64;
299 #define INT64_IS_BUSTED
300 #endif /* not HAVE_LONG_INT_64 and not
301 * HAVE_LONG_LONG_INT_64 */
303 /* Decide if we need to decorate 64-bit constants */
304 #ifdef HAVE_LL_CONSTANTS
305 #define INT64CONST(x) ((int64) x##LL)
306 #define UINT64CONST(x) ((uint64) x##ULL)
308 #define INT64CONST(x) ((int64) x)
309 #define UINT64CONST(x) ((uint64) x)
313 /* Select timestamp representation (float8 or int64) */
314 #if defined(USE_INTEGER_DATETIMES) && !defined(INT64_IS_BUSTED)
315 #define HAVE_INT64_TIMESTAMP
318 /* sig_atomic_t is required by ANSI C, but may be missing on old platforms */
319 #ifndef HAVE_SIG_ATOMIC_T
320 typedef int sig_atomic_t;
325 * Size of any memory resident object, as returned by sizeof.
331 * Index into any memory resident array.
334 * Indices are non negative.
336 typedef unsigned int Index;
340 * Offset into any memory resident array.
343 * This differs from an Index in that an Index is always
344 * non negative, whereas Offset may be negative.
346 typedef signed int Offset;
349 * Common Postgres datatype names (as used in the catalogs)
353 typedef float float4;
354 typedef double float8;
357 * Oid, RegProcedure, TransactionId, SubTransactionId, MultiXactId,
361 /* typedef Oid is in postgres_ext.h */
364 * regproc is the type name used in the include/catalog headers, but
365 * RegProcedure is the preferred name in C code.
368 typedef regproc RegProcedure;
370 typedef uint32 TransactionId;
372 typedef uint32 LocalTransactionId;
374 typedef uint32 SubTransactionId;
376 #define InvalidSubTransactionId ((SubTransactionId) 0)
377 #define TopSubTransactionId ((SubTransactionId) 1)
379 /* MultiXactId must be equivalent to TransactionId, to fit in t_xmax */
380 typedef TransactionId MultiXactId;
382 typedef uint32 MultiXactOffset;
384 typedef uint32 CommandId;
386 #define FirstCommandId ((CommandId) 0)
389 * Array indexing support
398 * Variable-length datatypes all share the 'struct varlena' header.
400 * NOTE: for TOASTable types, this is an oversimplification, since the value
401 * may be compressed or moved out-of-line. However datatype-specific routines
402 * are mostly content to deal with de-TOASTed values only, and of course
403 * client-side routines should never see a TOASTed value. But even in a
404 * de-TOASTed value, beware of touching vl_len_ directly, as its representation
405 * is no longer convenient. It's recommended that code always use the VARDATA,
406 * VARSIZE, and SET_VARSIZE macros instead of relying on direct mentions of
407 * the struct fields. See postgres.h for details of the TOASTed form.
412 char vl_len_[4]; /* Do not touch this field directly! */
416 #define VARHDRSZ ((int32) sizeof(int32))
419 * These widely-used datatypes are just a varlena header and the data bytes.
420 * There is no terminating null or anything like that --- the data length is
421 * always VARSIZE(ptr) - VARHDRSZ.
423 typedef struct varlena bytea;
424 typedef struct varlena text;
425 typedef struct varlena BpChar; /* blank-padded char, ie SQL char(n) */
426 typedef struct varlena VarChar; /* var-length char, ie SQL varchar(n) */
429 * Specialized array types. These are physically laid out just the same
430 * as regular arrays (so that the regular array subscripting code works
431 * with them). They exist as distinct types mostly for historical reasons:
432 * they have nonstandard I/O behavior which we don't want to change for fear
433 * of breaking applications that look at the system catalogs. There is also
434 * an implementation issue for oidvector: it's part of the primary key for
435 * pg_proc, and we can't use the normal btree array support routines for that
436 * without circularity.
440 int32 vl_len_; /* these fields must match ArrayType! */
441 int ndim; /* always 1 for int2vector */
442 int32 dataoffset; /* always 0 for int2vector */
446 int2 values[1]; /* VARIABLE LENGTH ARRAY */
447 } int2vector; /* VARIABLE LENGTH STRUCT */
451 int32 vl_len_; /* these fields must match ArrayType! */
452 int ndim; /* always 1 for oidvector */
453 int32 dataoffset; /* always 0 for oidvector */
457 Oid values[1]; /* VARIABLE LENGTH ARRAY */
458 } oidvector; /* VARIABLE LENGTH STRUCT */
461 * We want NameData to have length NAMEDATALEN and int alignment,
462 * because that's how the data type 'name' is defined in pg_type.
463 * Use a union to make sure the compiler agrees. Note that NAMEDATALEN
464 * must be a multiple of sizeof(int), else sizeof(NameData) will probably
465 * not come out equal to NAMEDATALEN.
467 typedef union nameData
469 char data[NAMEDATALEN];
472 typedef NameData *Name;
474 #define NameStr(name) ((name).data)
477 * Support macros for escaping strings. escape_backslash should be TRUE
478 * if generating a non-standard-conforming string. Prefixing a string
479 * with ESCAPE_STRING_SYNTAX guarantees it is non-standard-conforming.
480 * Beware of multiple evaluation of the "ch" argument!
482 #define SQL_STR_DOUBLE(ch, escape_backslash) \
483 ((ch) == '\'' || ((ch) == '\\' && (escape_backslash)))
485 #define ESCAPE_STRING_SYNTAX 'E'
487 /* ----------------------------------------------------------------
488 * Section 4: IsValid macros for system types
489 * ----------------------------------------------------------------
493 * True iff bool is valid.
495 #define BoolIsValid(boolean) ((boolean) == false || (boolean) == true)
499 * True iff pointer is valid.
501 #define PointerIsValid(pointer) ((void*)(pointer) != NULL)
505 * True iff pointer is properly aligned to point to the given type.
507 #define PointerIsAligned(pointer, type) \
508 (((long)(pointer) % (sizeof (type))) == 0)
510 #define OidIsValid(objectId) ((bool) ((objectId) != InvalidOid))
512 #define RegProcedureIsValid(p) OidIsValid(p)
515 /* ----------------------------------------------------------------
516 * Section 5: offsetof, lengthof, endof, alignment
517 * ----------------------------------------------------------------
521 * Offset of a structure/union field within that structure/union.
523 * XXX This is supposed to be part of stddef.h, but isn't on
524 * some systems (like SunOS 4).
527 #define offsetof(type, field) ((long) &((type *)0)->field)
528 #endif /* offsetof */
532 * Number of elements in an array.
534 #define lengthof(array) (sizeof (array) / sizeof ((array)[0]))
538 * Address of the element one past the last in an array.
540 #define endof(array) (&(array)[lengthof(array)])
543 * Alignment macros: align a length or address appropriately for a given type.
544 * The fooALIGN() macros round up to a multiple of the required alignment,
545 * while the fooALIGN_DOWN() macros round down. The latter are more useful
546 * for problems like "how many X-sized structures will fit in a page?".
548 * NOTE: TYPEALIGN[_DOWN] will not work if ALIGNVAL is not a power of 2.
549 * That case seems extremely unlikely to be needed in practice, however.
553 #define TYPEALIGN(ALIGNVAL,LEN) \
554 (((long) (LEN) + ((ALIGNVAL) - 1)) & ~((long) ((ALIGNVAL) - 1)))
556 #define SHORTALIGN(LEN) TYPEALIGN(ALIGNOF_SHORT, (LEN))
557 #define INTALIGN(LEN) TYPEALIGN(ALIGNOF_INT, (LEN))
558 #define LONGALIGN(LEN) TYPEALIGN(ALIGNOF_LONG, (LEN))
559 #define DOUBLEALIGN(LEN) TYPEALIGN(ALIGNOF_DOUBLE, (LEN))
560 #define MAXALIGN(LEN) TYPEALIGN(MAXIMUM_ALIGNOF, (LEN))
561 /* MAXALIGN covers only built-in types, not buffers */
562 #define BUFFERALIGN(LEN) TYPEALIGN(ALIGNOF_BUFFER, (LEN))
564 #define TYPEALIGN_DOWN(ALIGNVAL,LEN) \
565 (((long) (LEN)) & ~((long) ((ALIGNVAL) - 1)))
567 #define SHORTALIGN_DOWN(LEN) TYPEALIGN_DOWN(ALIGNOF_SHORT, (LEN))
568 #define INTALIGN_DOWN(LEN) TYPEALIGN_DOWN(ALIGNOF_INT, (LEN))
569 #define LONGALIGN_DOWN(LEN) TYPEALIGN_DOWN(ALIGNOF_LONG, (LEN))
570 #define DOUBLEALIGN_DOWN(LEN) TYPEALIGN_DOWN(ALIGNOF_DOUBLE, (LEN))
571 #define MAXALIGN_DOWN(LEN) TYPEALIGN_DOWN(MAXIMUM_ALIGNOF, (LEN))
573 /* ----------------------------------------------------------------
574 * Section 6: widely useful macros
575 * ----------------------------------------------------------------
579 * Return the maximum of two numbers.
581 #define Max(x, y) ((x) > (y) ? (x) : (y))
585 * Return the minimum of two numbers.
587 #define Min(x, y) ((x) < (y) ? (x) : (y))
591 * Return the absolute value of the argument.
593 #define Abs(x) ((x) >= 0 ? (x) : -(x))
597 * Like standard library function strncpy(), except that result string
598 * is guaranteed to be null-terminated --- that is, at most N-1 bytes
599 * of the source string will be kept.
600 * Also, the macro returns no result (too hard to do that without
601 * evaluating the arguments multiple times, which seems worse).
603 * BTW: when you need to copy a non-null-terminated string (like a text
604 * datum) and add a null, do not do it with StrNCpy(..., len+1). That
605 * might seem to work, but it fetches one byte more than there is in the
606 * text object. One fine day you'll have a SIGSEGV because there isn't
607 * another byte before the end of memory. Don't laugh, we've had real
608 * live bug reports from real live users over exactly this mistake.
609 * Do it honestly with "memcpy(dst,src,len); dst[len] = '\0';", instead.
611 #define StrNCpy(dst,src,len) \
614 char * _dst = (dst); \
619 strncpy(_dst, (src), _len); \
620 _dst[_len-1] = '\0'; \
625 /* Get a bit mask of the bits set in non-long aligned addresses */
626 #define LONG_ALIGN_MASK (sizeof(long) - 1)
630 * Exactly the same as standard library function memset(), but considerably
631 * faster for zeroing small word-aligned structures (such as parsetree nodes).
632 * This has to be a macro because the main point is to avoid function-call
633 * overhead. However, we have also found that the loop is faster than
634 * native libc memset() on some platforms, even those with assembler
635 * memset() functions. More research needs to be done, perhaps with
636 * MEMSET_LOOP_LIMIT tests in configure.
638 #define MemSet(start, val, len) \
641 /* must be void* because we don't know if it is integer aligned yet */ \
642 void *_vstart = (void *) (start); \
646 if ((((long) _vstart) & LONG_ALIGN_MASK) == 0 && \
647 (_len & LONG_ALIGN_MASK) == 0 && \
649 _len <= MEMSET_LOOP_LIMIT && \
651 * If MEMSET_LOOP_LIMIT == 0, optimizer should find \
652 * the whole "if" false at compile time. \
654 MEMSET_LOOP_LIMIT != 0) \
656 long *_start = (long *) _vstart; \
657 long *_stop = (long *) ((char *) _start + _len); \
658 while (_start < _stop) \
662 memset(_vstart, _val, _len); \
666 * MemSetAligned is the same as MemSet except it omits the test to see if
667 * "start" is word-aligned. This is okay to use if the caller knows a-priori
668 * that the pointer is suitably aligned (typically, because he just got it
669 * from palloc(), which always delivers a max-aligned pointer).
671 #define MemSetAligned(start, val, len) \
674 long *_start = (long *) (start); \
678 if ((_len & LONG_ALIGN_MASK) == 0 && \
680 _len <= MEMSET_LOOP_LIMIT && \
681 MEMSET_LOOP_LIMIT != 0) \
683 long *_stop = (long *) ((char *) _start + _len); \
684 while (_start < _stop) \
688 memset(_start, _val, _len); \
693 * MemSetTest/MemSetLoop are a variant version that allow all the tests in
694 * MemSet to be done at compile time in cases where "val" and "len" are
695 * constants *and* we know the "start" pointer must be word-aligned.
696 * If MemSetTest succeeds, then it is okay to use MemSetLoop, otherwise use
697 * MemSetAligned. Beware of multiple evaluations of the arguments when using
700 #define MemSetTest(val, len) \
701 ( ((len) & LONG_ALIGN_MASK) == 0 && \
702 (len) <= MEMSET_LOOP_LIMIT && \
703 MEMSET_LOOP_LIMIT != 0 && \
706 #define MemSetLoop(start, val, len) \
709 long * _start = (long *) (start); \
710 long * _stop = (long *) ((char *) _start + (Size) (len)); \
712 while (_start < _stop) \
717 /* ----------------------------------------------------------------
718 * Section 7: random stuff
719 * ----------------------------------------------------------------
723 #define HIGHBIT (0x80)
724 #define IS_HIGHBIT_SET(ch) ((unsigned char)(ch) & HIGHBIT)
726 #define STATUS_OK (0)
727 #define STATUS_ERROR (-1)
728 #define STATUS_EOF (-2)
729 #define STATUS_FOUND (1)
730 #define STATUS_WAITING (2)
733 /* ----------------------------------------------------------------
734 * Section 8: system-specific hacks
736 * This should be limited to things that absolutely have to be
737 * included in every source file. The port-specific header file
738 * is usually a better place for this sort of thing.
739 * ----------------------------------------------------------------
743 * NOTE: this is also used for opening text files.
744 * WIN32 treats Control-Z as EOF in files opened in text mode.
745 * Therefore, we open files in binary mode on Win32 so we can read
746 * literal control-Z. The other affect is that we see CRLF, but
747 * that is OK because we can already handle those cleanly.
749 #if defined(WIN32) || defined(__CYGWIN__)
750 #define PG_BINARY O_BINARY
751 #define PG_BINARY_A "ab"
752 #define PG_BINARY_R "rb"
753 #define PG_BINARY_W "wb"
756 #define PG_BINARY_A "a"
757 #define PG_BINARY_R "r"
758 #define PG_BINARY_W "w"
761 #if defined(sun) && defined(__sparc__) && !defined(__SVR4)
765 /* These are for things that are one way on Unix and another on NT */
766 #define NULL_DEV "/dev/null"
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(printf, 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)
789 #define PGDLLIMPORT /* no special DLL markers on most ports */
793 * The following is used as the arg list for signal handlers. Any ports
794 * that take something other than an int argument should override this in
795 * their pg_config_os.h file. Note that variable names are required
796 * because it is used in both the prototypes as well as the definitions.
797 * Note also the long name. We expect that this won't collide with
798 * other names causing compiler warnings.
802 #define SIGNAL_ARGS int postgres_signal_arg
806 * When there is no sigsetjmp, its functionality is provided by plain
807 * setjmp. Incidentally, nothing provides setjmp's functionality in
810 #ifndef HAVE_SIGSETJMP
811 #define sigjmp_buf jmp_buf
812 #define sigsetjmp(x,y) setjmp(x)
813 #define siglongjmp longjmp
816 #if defined(HAVE_FDATASYNC) && !HAVE_DECL_FDATASYNC
817 extern int fdatasync(int fildes);
820 /* If strtoq() exists, rename it to the more standard strtoll() */
821 #if defined(HAVE_LONG_LONG_INT_64) && !defined(HAVE_STRTOLL) && defined(HAVE_STRTOQ)
822 #define strtoll strtoq
823 #define HAVE_STRTOLL 1
826 /* If strtouq() exists, rename it to the more standard strtoull() */
827 #if defined(HAVE_LONG_LONG_INT_64) && !defined(HAVE_STRTOULL) && defined(HAVE_STRTOUQ)
828 #define strtoull strtouq
829 #define HAVE_STRTOULL 1
832 /* EXEC_BACKEND defines */
834 #define NON_EXEC_STATIC
836 #define NON_EXEC_STATIC static
839 /* /port compatibility functions */