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-2007, PostgreSQL Global Development Group
13 * Portions Copyright (c) 1994, Regents of the University of California
15 * $PostgreSQL: pgsql/src/include/c.h,v 1.217 2007/01/25 03:30:43 momjian 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"
63 #define errcode __msvc_errcode
76 #include <sys/types.h>
79 #if defined(WIN32) || defined(__CYGWIN__)
80 #include <fcntl.h> /* ensure O_BINARY is available */
82 #ifdef HAVE_SUPPORTDEFS_H
83 #include <SupportDefs.h>
86 #if defined(WIN32) || defined(__CYGWIN__)
87 /* We have to redefine some system functions after they are included above. */
88 #include "pg_config_os.h"
91 /* Must be before gettext() games below */
94 #define _(x) gettext((x))
99 #define gettext(x) (x)
103 * Use this to mark strings to be translated by gettext, in places where
104 * you don't want an actual function call to occur (eg, constant tables).
106 #define gettext_noop(x) (x)
109 /* ----------------------------------------------------------------
110 * Section 1: hacks to cope with non-ANSI C compilers
112 * type prefixes (const, signed, volatile, inline) are handled in pg_config.h.
113 * ----------------------------------------------------------------
118 * Convert the argument to a string, using the C preprocessor.
120 * Concatenate two arguments together, using the C preprocessor.
122 * Note: the standard Autoconf macro AC_C_STRINGIZE actually only checks
123 * whether #identifier works, but if we have that we likely have ## too.
125 #if defined(HAVE_STRINGIZE)
127 #define CppAsString(identifier) #identifier
128 #define CppConcat(x, y) x##y
129 #else /* !HAVE_STRINGIZE */
131 #define CppAsString(identifier) "identifier"
134 * CppIdentity -- On Reiser based cpp's this is used to concatenate
135 * two tokens. That is
136 * CppIdentity(A)B ==> AB
137 * We renamed it to _private_CppIdentity because it should not
138 * be referenced outside this file. On other cpp's it
141 #define _priv_CppIdentity(x)x
142 #define CppConcat(x, y) _priv_CppIdentity(x)y
143 #endif /* !HAVE_STRINGIZE */
146 * dummyret is used to set return values in macros that use ?: to make
147 * assignments. gcc wants these to be void, other compilers like char
149 #ifdef __GNUC__ /* GNU cc */
150 #define dummyret void
152 #define dummyret char
156 #define __attribute__(_arg_)
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 */
254 * Floating point number, AT LEAST N BITS IN SIZE,
255 * used for numerical computations.
257 * Since sizeof(floatN) may be > sizeof(char *), always pass
258 * floatN by reference.
260 * XXX: these typedefs are now deprecated in favor of float4 and float8.
261 * They will eventually go away.
263 typedef float float32data;
264 typedef double float64data;
265 typedef float *float32;
266 typedef double *float64;
271 #ifdef HAVE_LONG_INT_64
272 /* Plain "long int" fits, use it */
275 typedef long int int64;
278 typedef unsigned long int uint64;
280 #elif defined(HAVE_LONG_LONG_INT_64)
281 /* We have working support for "long long int", use that */
284 typedef long long int int64;
287 typedef unsigned long long int uint64;
289 #else /* not HAVE_LONG_INT_64 and not
290 * HAVE_LONG_LONG_INT_64 */
292 /* Won't actually work, but fall back to long int so that code compiles */
294 typedef long int int64;
297 typedef unsigned long int uint64;
300 #define INT64_IS_BUSTED
301 #endif /* not HAVE_LONG_INT_64 and not
302 * HAVE_LONG_LONG_INT_64 */
304 /* Decide if we need to decorate 64-bit constants */
305 #ifdef HAVE_LL_CONSTANTS
306 #define INT64CONST(x) ((int64) x##LL)
307 #define UINT64CONST(x) ((uint64) x##ULL)
309 #define INT64CONST(x) ((int64) x)
310 #define UINT64CONST(x) ((uint64) x)
314 /* Select timestamp representation (float8 or int64) */
315 #if defined(USE_INTEGER_DATETIMES) && !defined(INT64_IS_BUSTED)
316 #define HAVE_INT64_TIMESTAMP
319 /* sig_atomic_t is required by ANSI C, but may be missing on old platforms */
320 #ifndef HAVE_SIG_ATOMIC_T
321 typedef int sig_atomic_t;
326 * Size of any memory resident object, as returned by sizeof.
332 * Index into any memory resident array.
335 * Indices are non negative.
337 typedef unsigned int Index;
341 * Offset into any memory resident array.
344 * This differs from an Index in that an Index is always
345 * non negative, whereas Offset may be negative.
347 typedef signed int Offset;
350 * Common Postgres datatype names (as used in the catalogs)
354 typedef float float4;
355 typedef double float8;
358 * Oid, RegProcedure, TransactionId, SubTransactionId, MultiXactId,
362 /* typedef Oid is in postgres_ext.h */
365 * regproc is the type name used in the include/catalog headers, but
366 * RegProcedure is the preferred name in C code.
369 typedef regproc RegProcedure;
371 typedef uint32 TransactionId;
373 typedef uint32 SubTransactionId;
375 #define InvalidSubTransactionId ((SubTransactionId) 0)
376 #define TopSubTransactionId ((SubTransactionId) 1)
378 /* MultiXactId must be equivalent to TransactionId, to fit in t_xmax */
379 typedef TransactionId MultiXactId;
381 typedef uint32 MultiXactOffset;
383 typedef uint32 CommandId;
385 #define FirstCommandId ((CommandId) 0)
388 * Array indexing support
397 * Variable-length datatypes all share the 'struct varlena' header.
399 * NOTE: for TOASTable types, this is an oversimplification, since the value
400 * may be compressed or moved out-of-line. However datatype-specific routines
401 * are mostly content to deal with de-TOASTed values only, and of course
402 * client-side routines should never see a TOASTed value. See postgres.h for
403 * details of the TOASTed form.
412 #define VARHDRSZ ((int32) sizeof(int32))
415 * These widely-used datatypes are just a varlena header and the data bytes.
416 * There is no terminating null or anything like that --- the data length is
417 * always VARSIZE(ptr) - VARHDRSZ.
419 typedef struct varlena bytea;
420 typedef struct varlena text;
421 typedef struct varlena BpChar; /* blank-padded char, ie SQL char(n) */
422 typedef struct varlena VarChar; /* var-length char, ie SQL varchar(n) */
425 * Specialized array types. These are physically laid out just the same
426 * as regular arrays (so that the regular array subscripting code works
427 * with them). They exist as distinct types mostly for historical reasons:
428 * they have nonstandard I/O behavior which we don't want to change for fear
429 * of breaking applications that look at the system catalogs. There is also
430 * an implementation issue for oidvector: it's part of the primary key for
431 * pg_proc, and we can't use the normal btree array support routines for that
432 * without circularity.
436 int32 size; /* these fields must match ArrayType! */
437 int ndim; /* always 1 for int2vector */
438 int32 dataoffset; /* always 0 for int2vector */
442 int2 values[1]; /* VARIABLE LENGTH ARRAY */
443 } int2vector; /* VARIABLE LENGTH STRUCT */
447 int32 size; /* these fields must match ArrayType! */
448 int ndim; /* always 1 for oidvector */
449 int32 dataoffset; /* always 0 for oidvector */
453 Oid values[1]; /* VARIABLE LENGTH ARRAY */
454 } oidvector; /* VARIABLE LENGTH STRUCT */
457 * We want NameData to have length NAMEDATALEN and int alignment,
458 * because that's how the data type 'name' is defined in pg_type.
459 * Use a union to make sure the compiler agrees. Note that NAMEDATALEN
460 * must be a multiple of sizeof(int), else sizeof(NameData) will probably
461 * not come out equal to NAMEDATALEN.
463 typedef union nameData
465 char data[NAMEDATALEN];
468 typedef NameData *Name;
470 #define NameStr(name) ((name).data)
473 * Support macros for escaping strings. escape_backslash should be TRUE
474 * if generating a non-standard-conforming string. Prefixing a string
475 * with ESCAPE_STRING_SYNTAX guarantees it is non-standard-conforming.
476 * Beware of multiple evaluation of the "ch" argument!
478 #define SQL_STR_DOUBLE(ch, escape_backslash) \
479 ((ch) == '\'' || ((ch) == '\\' && (escape_backslash)))
481 #define ESCAPE_STRING_SYNTAX 'E'
483 /* ----------------------------------------------------------------
484 * Section 4: IsValid macros for system types
485 * ----------------------------------------------------------------
489 * True iff bool is valid.
491 #define BoolIsValid(boolean) ((boolean) == false || (boolean) == true)
495 * True iff pointer is valid.
497 #define PointerIsValid(pointer) ((void*)(pointer) != NULL)
501 * True iff pointer is properly aligned to point to the given type.
503 #define PointerIsAligned(pointer, type) \
504 (((long)(pointer) % (sizeof (type))) == 0)
506 #define OidIsValid(objectId) ((bool) ((objectId) != InvalidOid))
508 #define RegProcedureIsValid(p) OidIsValid(p)
511 /* ----------------------------------------------------------------
512 * Section 5: offsetof, lengthof, endof, alignment
513 * ----------------------------------------------------------------
517 * Offset of a structure/union field within that structure/union.
519 * XXX This is supposed to be part of stddef.h, but isn't on
520 * some systems (like SunOS 4).
523 #define offsetof(type, field) ((long) &((type *)0)->field)
524 #endif /* offsetof */
528 * Number of elements in an array.
530 #define lengthof(array) (sizeof (array) / sizeof ((array)[0]))
534 * Address of the element one past the last in an array.
536 #define endof(array) (&(array)[lengthof(array)])
539 * Alignment macros: align a length or address appropriately for a given type.
541 * There used to be some incredibly crufty platform-dependent hackery here,
542 * but now we rely on the configure script to get the info for us. Much nicer.
544 * NOTE: TYPEALIGN will not work if ALIGNVAL is not a power of 2.
545 * That case seems extremely unlikely to occur in practice, however.
549 #define TYPEALIGN(ALIGNVAL,LEN) \
550 (((long) (LEN) + ((ALIGNVAL) - 1)) & ~((long) ((ALIGNVAL) - 1)))
552 #define SHORTALIGN(LEN) TYPEALIGN(ALIGNOF_SHORT, (LEN))
553 #define INTALIGN(LEN) TYPEALIGN(ALIGNOF_INT, (LEN))
554 #define LONGALIGN(LEN) TYPEALIGN(ALIGNOF_LONG, (LEN))
555 #define DOUBLEALIGN(LEN) TYPEALIGN(ALIGNOF_DOUBLE, (LEN))
556 #define MAXALIGN(LEN) TYPEALIGN(MAXIMUM_ALIGNOF, (LEN))
557 /* MAXALIGN covers only built-in types, not buffers */
558 #define BUFFERALIGN(LEN) TYPEALIGN(ALIGNOF_BUFFER, (LEN))
561 /* ----------------------------------------------------------------
562 * Section 6: widely useful macros
563 * ----------------------------------------------------------------
567 * Return the maximum of two numbers.
569 #define Max(x, y) ((x) > (y) ? (x) : (y))
573 * Return the minimum of two numbers.
575 #define Min(x, y) ((x) < (y) ? (x) : (y))
579 * Return the absolute value of the argument.
581 #define Abs(x) ((x) >= 0 ? (x) : -(x))
585 * Like standard library function strncpy(), except that result string
586 * is guaranteed to be null-terminated --- that is, at most N-1 bytes
587 * of the source string will be kept.
588 * Also, the macro returns no result (too hard to do that without
589 * evaluating the arguments multiple times, which seems worse).
591 * BTW: when you need to copy a non-null-terminated string (like a text
592 * datum) and add a null, do not do it with StrNCpy(..., len+1). That
593 * might seem to work, but it fetches one byte more than there is in the
594 * text object. One fine day you'll have a SIGSEGV because there isn't
595 * another byte before the end of memory. Don't laugh, we've had real
596 * live bug reports from real live users over exactly this mistake.
597 * Do it honestly with "memcpy(dst,src,len); dst[len] = '\0';", instead.
599 #define StrNCpy(dst,src,len) \
602 char * _dst = (dst); \
607 strncpy(_dst, (src), _len); \
608 _dst[_len-1] = '\0'; \
613 /* Get a bit mask of the bits set in non-long aligned addresses */
614 #define LONG_ALIGN_MASK (sizeof(long) - 1)
618 * Exactly the same as standard library function memset(), but considerably
619 * faster for zeroing small word-aligned structures (such as parsetree nodes).
620 * This has to be a macro because the main point is to avoid function-call
621 * overhead. However, we have also found that the loop is faster than
622 * native libc memset() on some platforms, even those with assembler
623 * memset() functions. More research needs to be done, perhaps with
624 * MEMSET_LOOP_LIMIT tests in configure.
626 #define MemSet(start, val, len) \
629 /* must be void* because we don't know if it is integer aligned yet */ \
630 void *_vstart = (void *) (start); \
634 if ((((long) _vstart) & LONG_ALIGN_MASK) == 0 && \
635 (_len & LONG_ALIGN_MASK) == 0 && \
637 _len <= MEMSET_LOOP_LIMIT && \
639 * If MEMSET_LOOP_LIMIT == 0, optimizer should find \
640 * the whole "if" false at compile time. \
642 MEMSET_LOOP_LIMIT != 0) \
644 long *_start = (long *) _vstart; \
645 long *_stop = (long *) ((char *) _start + _len); \
646 while (_start < _stop) \
650 memset(_vstart, _val, _len); \
654 * MemSetAligned is the same as MemSet except it omits the test to see if
655 * "start" is word-aligned. This is okay to use if the caller knows a-priori
656 * that the pointer is suitably aligned (typically, because he just got it
657 * from palloc(), which always delivers a max-aligned pointer).
659 #define MemSetAligned(start, val, len) \
662 long *_start = (long *) (start); \
666 if ((_len & LONG_ALIGN_MASK) == 0 && \
668 _len <= MEMSET_LOOP_LIMIT && \
669 MEMSET_LOOP_LIMIT != 0) \
671 long *_stop = (long *) ((char *) _start + _len); \
672 while (_start < _stop) \
676 memset(_start, _val, _len); \
681 * MemSetTest/MemSetLoop are a variant version that allow all the tests in
682 * MemSet to be done at compile time in cases where "val" and "len" are
683 * constants *and* we know the "start" pointer must be word-aligned.
684 * If MemSetTest succeeds, then it is okay to use MemSetLoop, otherwise use
685 * MemSetAligned. Beware of multiple evaluations of the arguments when using
688 #define MemSetTest(val, len) \
689 ( ((len) & LONG_ALIGN_MASK) == 0 && \
690 (len) <= MEMSET_LOOP_LIMIT && \
691 MEMSET_LOOP_LIMIT != 0 && \
694 #define MemSetLoop(start, val, len) \
697 long * _start = (long *) (start); \
698 long * _stop = (long *) ((char *) _start + (Size) (len)); \
700 while (_start < _stop) \
705 /* ----------------------------------------------------------------
706 * Section 7: random stuff
707 * ----------------------------------------------------------------
711 #define HIGHBIT (0x80)
712 #define IS_HIGHBIT_SET(ch) ((unsigned char)(ch) & HIGHBIT)
714 #define STATUS_OK (0)
715 #define STATUS_ERROR (-1)
716 #define STATUS_EOF (-2)
717 #define STATUS_FOUND (1)
718 #define STATUS_WAITING (2)
721 /* ----------------------------------------------------------------
722 * Section 8: system-specific hacks
724 * This should be limited to things that absolutely have to be
725 * included in every source file. The port-specific header file
726 * is usually a better place for this sort of thing.
727 * ----------------------------------------------------------------
731 * NOTE: this is also used for opening text files.
732 * WIN32 treats Control-Z as EOF in files opened in text mode.
733 * Therefore, we open files in binary mode on Win32 so we can read
734 * literal control-Z. The other affect is that we see CRLF, but
735 * that is OK because we can already handle those cleanly.
737 #if defined(WIN32) || defined(__CYGWIN__)
738 #define PG_BINARY O_BINARY
739 #define PG_BINARY_A "ab"
740 #define PG_BINARY_R "rb"
741 #define PG_BINARY_W "wb"
744 #define PG_BINARY_A "a"
745 #define PG_BINARY_R "r"
746 #define PG_BINARY_W "w"
749 #if defined(sun) && defined(__sparc__) && !defined(__SVR4)
753 /* These are for things that are one way on Unix and another on NT */
754 #define NULL_DEV "/dev/null"
757 * Provide prototypes for routines not present in a particular machine's
758 * standard C library.
761 #if !HAVE_DECL_SNPRINTF
763 snprintf(char *str, size_t count, const char *fmt,...)
764 /* This extension allows gcc to check the format string */
765 __attribute__((format(printf, 3, 4)));
768 #if !HAVE_DECL_VSNPRINTF
769 extern int vsnprintf(char *str, size_t count, const char *fmt, va_list args);
772 #if !defined(HAVE_MEMMOVE) && !defined(memmove)
773 #define memmove(d, s, c) bcopy(s, d, c)
777 #define DLLIMPORT /* no special DLL markers on most ports */
781 * The following is used as the arg list for signal handlers. Any ports
782 * that take something other than an int argument should override this in
783 * their pg_config_os.h file. Note that variable names are required
784 * because it is used in both the prototypes as well as the definitions.
785 * Note also the long name. We expect that this won't collide with
786 * other names causing compiler warnings.
790 #define SIGNAL_ARGS int postgres_signal_arg
794 * When there is no sigsetjmp, its functionality is provided by plain
795 * setjmp. Incidentally, nothing provides setjmp's functionality in
798 #ifndef HAVE_SIGSETJMP
799 #define sigjmp_buf jmp_buf
800 #define sigsetjmp(x,y) setjmp(x)
801 #define siglongjmp longjmp
804 #if defined(HAVE_FDATASYNC) && !HAVE_DECL_FDATASYNC
805 extern int fdatasync(int fildes);
808 /* If strtoq() exists, rename it to the more standard strtoll() */
809 #if defined(HAVE_LONG_LONG_INT_64) && !defined(HAVE_STRTOLL) && defined(HAVE_STRTOQ)
810 #define strtoll strtoq
811 #define HAVE_STRTOLL 1
814 /* If strtouq() exists, rename it to the more standard strtoull() */
815 #if defined(HAVE_LONG_LONG_INT_64) && !defined(HAVE_STRTOULL) && defined(HAVE_STRTOUQ)
816 #define strtoull strtouq
817 #define HAVE_STRTOULL 1
820 /* EXEC_BACKEND defines */
822 #define NON_EXEC_STATIC
824 #define NON_EXEC_STATIC static
827 /* /port compatibility functions */