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-2006, PostgreSQL Global Development Group
13 * Portions Copyright (c) 1994, Regents of the University of California
15 * $PostgreSQL: pgsql/src/include/c.h,v 1.208 2006/07/29 17:35:07 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 down */
56 #include "pg_config_os.h" /* must be before any system header files */
58 #include "postgres_ext.h"
61 #if defined(_MSC_VER) || defined(__BORLANDC__)
62 #define WIN32_ONLY_COMPILER
63 #define errcode __vc_errcode
64 #if defined(__BORLANDC__) || (_MSC_VER > 1400)
78 #include <sys/types.h>
81 #if defined(WIN32) || defined(__CYGWIN__)
82 #include <fcntl.h> /* ensure O_BINARY is available */
84 #ifdef HAVE_SUPPORTDEFS_H
85 #include <SupportDefs.h>
88 #if defined(WIN32) || defined(__CYGWIN__)
89 /* We have to redefine some system functions after they are included above. */
90 #include "pg_config_os.h"
93 /* Must be before gettext() games below */
96 #define _(x) gettext((x))
101 #define gettext(x) (x)
105 * Use this to mark strings to be translated by gettext, in places where
106 * you don't want an actual function call to occur (eg, constant tables).
108 #define gettext_noop(x) (x)
111 /* ----------------------------------------------------------------
112 * Section 1: hacks to cope with non-ANSI C compilers
114 * type prefixes (const, signed, volatile, inline) are handled in pg_config.h.
115 * ----------------------------------------------------------------
120 * Convert the argument to a string, using the C preprocessor.
122 * Concatenate two arguments together, using the C preprocessor.
124 * Note: the standard Autoconf macro AC_C_STRINGIZE actually only checks
125 * whether #identifier works, but if we have that we likely have ## too.
127 #if defined(HAVE_STRINGIZE)
129 #define CppAsString(identifier) #identifier
130 #define CppConcat(x, y) x##y
131 #else /* !HAVE_STRINGIZE */
133 #define CppAsString(identifier) "identifier"
136 * CppIdentity -- On Reiser based cpp's this is used to concatenate
137 * two tokens. That is
138 * CppIdentity(A)B ==> AB
139 * We renamed it to _private_CppIdentity because it should not
140 * be referenced outside this file. On other cpp's it
143 #define _priv_CppIdentity(x)x
144 #define CppConcat(x, y) _priv_CppIdentity(x)y
145 #endif /* !HAVE_STRINGIZE */
148 * dummyret is used to set return values in macros that use ?: to make
149 * assignments. gcc wants these to be void, other compilers like char
151 #ifdef __GNUC__ /* GNU cc */
152 #define dummyret void
154 #define dummyret char
158 #define __attribute__(_arg_)
161 /* ----------------------------------------------------------------
162 * Section 2: bool, true, false, TRUE, FALSE, NULL
163 * ----------------------------------------------------------------
168 * Boolean value, either true or false.
170 * XXX for C++ compilers, we assume the compiler has a compatible
171 * built-in definition of bool.
181 #define true ((bool) 1)
185 #define false ((bool) 0)
189 typedef bool *BoolPtr;
204 #define NULL ((void *) 0)
208 /* ----------------------------------------------------------------
209 * Section 3: standard system types
210 * ----------------------------------------------------------------
215 * Variable holding address of any memory resident object.
217 * XXX Pointer arithmetic is done with this, so it can't be void *
218 * under "true" ANSI compilers.
220 typedef char *Pointer;
224 * Signed integer, EXACTLY N BITS IN SIZE,
225 * used for numerical computations and the
226 * frontend/backend protocol.
229 typedef signed char int8; /* == 8 bits */
230 typedef signed short int16; /* == 16 bits */
231 typedef signed int int32; /* == 32 bits */
232 #endif /* not HAVE_INT8 */
236 * Unsigned integer, EXACTLY N BITS IN SIZE,
237 * used for numerical computations and the
238 * frontend/backend protocol.
241 typedef unsigned char uint8; /* == 8 bits */
242 typedef unsigned short uint16; /* == 16 bits */
243 typedef unsigned int uint32; /* == 32 bits */
244 #endif /* not HAVE_UINT8 */
248 * Unit of bitwise operation, AT LEAST N BITS IN SIZE.
250 typedef uint8 bits8; /* >= 8 bits */
251 typedef uint16 bits16; /* >= 16 bits */
252 typedef uint32 bits32; /* >= 32 bits */
256 * Floating point number, AT LEAST N BITS IN SIZE,
257 * used for numerical computations.
259 * Since sizeof(floatN) may be > sizeof(char *), always pass
260 * floatN by reference.
262 * XXX: these typedefs are now deprecated in favor of float4 and float8.
263 * They will eventually go away.
265 typedef float float32data;
266 typedef double float64data;
267 typedef float *float32;
268 typedef double *float64;
273 #ifdef HAVE_LONG_INT_64
274 /* Plain "long int" fits, use it */
277 typedef long int int64;
280 typedef unsigned long int uint64;
282 #elif defined(HAVE_LONG_LONG_INT_64)
283 /* We have working support for "long long int", use that */
286 typedef long long int int64;
289 typedef unsigned long long int uint64;
291 #else /* not HAVE_LONG_INT_64 and not
292 * HAVE_LONG_LONG_INT_64 */
294 /* Won't actually work, but fall back to long int so that code compiles */
296 typedef long int int64;
299 typedef unsigned long int uint64;
302 #define INT64_IS_BUSTED
303 #endif /* not HAVE_LONG_INT_64 and not
304 * HAVE_LONG_LONG_INT_64 */
306 /* Decide if we need to decorate 64-bit constants */
307 #ifdef HAVE_LL_CONSTANTS
308 #define INT64CONST(x) ((int64) x##LL)
309 #define UINT64CONST(x) ((uint64) x##ULL)
311 #define INT64CONST(x) ((int64) x)
312 #define UINT64CONST(x) ((uint64) x)
316 /* Select timestamp representation (float8 or int64) */
317 #if defined(USE_INTEGER_DATETIMES) && !defined(INT64_IS_BUSTED)
318 #define HAVE_INT64_TIMESTAMP
321 /* sig_atomic_t is required by ANSI C, but may be missing on old platforms */
322 #ifndef HAVE_SIG_ATOMIC_T
323 typedef int sig_atomic_t;
328 * Size of any memory resident object, as returned by sizeof.
334 * Index into any memory resident array.
337 * Indices are non negative.
339 typedef unsigned int Index;
343 * Offset into any memory resident array.
346 * This differs from an Index in that an Index is always
347 * non negative, whereas Offset may be negative.
349 typedef signed int Offset;
352 * Common Postgres datatype names (as used in the catalogs)
356 typedef float float4;
357 typedef double float8;
360 * Oid, RegProcedure, TransactionId, SubTransactionId, MultiXactId,
364 /* typedef Oid is in postgres_ext.h */
367 * regproc is the type name used in the include/catalog headers, but
368 * RegProcedure is the preferred name in C code.
371 typedef regproc RegProcedure;
373 typedef uint32 TransactionId;
375 typedef uint32 SubTransactionId;
377 #define InvalidSubTransactionId ((SubTransactionId) 0)
378 #define TopSubTransactionId ((SubTransactionId) 1)
380 /* MultiXactId must be equivalent to TransactionId, to fit in t_xmax */
381 typedef TransactionId MultiXactId;
383 typedef uint32 MultiXactOffset;
385 typedef uint32 CommandId;
387 #define FirstCommandId ((CommandId) 0)
390 * Array indexing support
399 * Variable-length datatypes all share the 'struct varlena' header.
401 * NOTE: for TOASTable types, this is an oversimplification, since the value
402 * may be compressed or moved out-of-line. However datatype-specific routines
403 * are mostly content to deal with de-TOASTed values only, and of course
404 * client-side routines should never see a TOASTed value. See postgres.h for
405 * details of the TOASTed form.
414 #define VARHDRSZ ((int32) sizeof(int32))
417 * These widely-used datatypes are just a varlena header and the data bytes.
418 * There is no terminating null or anything like that --- the data length is
419 * always VARSIZE(ptr) - VARHDRSZ.
421 typedef struct varlena bytea;
422 typedef struct varlena text;
423 typedef struct varlena BpChar; /* blank-padded char, ie SQL char(n) */
424 typedef struct varlena VarChar; /* var-length char, ie SQL varchar(n) */
427 * Specialized array types. These are physically laid out just the same
428 * as regular arrays (so that the regular array subscripting code works
429 * with them). They exist as distinct types mostly for historical reasons:
430 * they have nonstandard I/O behavior which we don't want to change for fear
431 * of breaking applications that look at the system catalogs. There is also
432 * an implementation issue for oidvector: it's part of the primary key for
433 * pg_proc, and we can't use the normal btree array support routines for that
434 * without circularity.
438 int32 size; /* these fields must match ArrayType! */
439 int ndim; /* always 1 for int2vector */
440 int32 dataoffset; /* always 0 for int2vector */
444 int2 values[1]; /* VARIABLE LENGTH ARRAY */
445 } int2vector; /* VARIABLE LENGTH STRUCT */
449 int32 size; /* these fields must match ArrayType! */
450 int ndim; /* always 1 for oidvector */
451 int32 dataoffset; /* always 0 for oidvector */
455 Oid values[1]; /* VARIABLE LENGTH ARRAY */
456 } oidvector; /* VARIABLE LENGTH STRUCT */
459 * We want NameData to have length NAMEDATALEN and int alignment,
460 * because that's how the data type 'name' is defined in pg_type.
461 * Use a union to make sure the compiler agrees. Note that NAMEDATALEN
462 * must be a multiple of sizeof(int), else sizeof(NameData) will probably
463 * not come out equal to NAMEDATALEN.
465 typedef union nameData
467 char data[NAMEDATALEN];
470 typedef NameData *Name;
472 #define NameStr(name) ((name).data)
475 * Support macros for escaping strings. escape_backslash should be TRUE
476 * if generating a non-standard-conforming string. Prefixing a string
477 * with ESCAPE_STRING_SYNTAX guarantees it is non-standard-conforming.
478 * Beware of multiple evaluation of the "ch" argument!
480 #define SQL_STR_DOUBLE(ch, escape_backslash) \
481 ((ch) == '\'' || ((ch) == '\\' && (escape_backslash)))
483 #define ESCAPE_STRING_SYNTAX 'E'
485 /* ----------------------------------------------------------------
486 * Section 4: IsValid macros for system types
487 * ----------------------------------------------------------------
491 * True iff bool is valid.
493 #define BoolIsValid(boolean) ((boolean) == false || (boolean) == true)
497 * True iff pointer is valid.
499 #define PointerIsValid(pointer) ((void*)(pointer) != NULL)
503 * True iff pointer is properly aligned to point to the given type.
505 #define PointerIsAligned(pointer, type) \
506 (((long)(pointer) % (sizeof (type))) == 0)
508 #define OidIsValid(objectId) ((bool) ((objectId) != InvalidOid))
510 #define RegProcedureIsValid(p) OidIsValid(p)
513 /* ----------------------------------------------------------------
514 * Section 5: offsetof, lengthof, endof, alignment
515 * ----------------------------------------------------------------
519 * Offset of a structure/union field within that structure/union.
521 * XXX This is supposed to be part of stddef.h, but isn't on
522 * some systems (like SunOS 4).
525 #define offsetof(type, field) ((long) &((type *)0)->field)
526 #endif /* offsetof */
530 * Number of elements in an array.
532 #define lengthof(array) (sizeof (array) / sizeof ((array)[0]))
536 * Address of the element one past the last in an array.
538 #define endof(array) (&(array)[lengthof(array)])
541 * Alignment macros: align a length or address appropriately for a given type.
543 * There used to be some incredibly crufty platform-dependent hackery here,
544 * but now we rely on the configure script to get the info for us. Much nicer.
546 * NOTE: TYPEALIGN will not work if ALIGNVAL is not a power of 2.
547 * That case seems extremely unlikely to occur in practice, however.
551 #define TYPEALIGN(ALIGNVAL,LEN) \
552 (((long) (LEN) + ((ALIGNVAL) - 1)) & ~((long) ((ALIGNVAL) - 1)))
554 #define SHORTALIGN(LEN) TYPEALIGN(ALIGNOF_SHORT, (LEN))
555 #define INTALIGN(LEN) TYPEALIGN(ALIGNOF_INT, (LEN))
556 #define LONGALIGN(LEN) TYPEALIGN(ALIGNOF_LONG, (LEN))
557 #define DOUBLEALIGN(LEN) TYPEALIGN(ALIGNOF_DOUBLE, (LEN))
558 #define MAXALIGN(LEN) TYPEALIGN(MAXIMUM_ALIGNOF, (LEN))
559 /* MAXALIGN covers only built-in types, not buffers */
560 #define BUFFERALIGN(LEN) TYPEALIGN(ALIGNOF_BUFFER, (LEN))
563 /* ----------------------------------------------------------------
564 * Section 6: widely useful macros
565 * ----------------------------------------------------------------
569 * Return the maximum of two numbers.
571 #define Max(x, y) ((x) > (y) ? (x) : (y))
575 * Return the minimum of two numbers.
577 #define Min(x, y) ((x) < (y) ? (x) : (y))
581 * Return the absolute value of the argument.
583 #define Abs(x) ((x) >= 0 ? (x) : -(x))
587 * Like standard library function strncpy(), except that result string
588 * is guaranteed to be null-terminated --- that is, at most N-1 bytes
589 * of the source string will be kept.
590 * Also, the macro returns no result (too hard to do that without
591 * evaluating the arguments multiple times, which seems worse).
593 * BTW: when you need to copy a non-null-terminated string (like a text
594 * datum) and add a null, do not do it with StrNCpy(..., len+1). That
595 * might seem to work, but it fetches one byte more than there is in the
596 * text object. One fine day you'll have a SIGSEGV because there isn't
597 * another byte before the end of memory. Don't laugh, we've had real
598 * live bug reports from real live users over exactly this mistake.
599 * Do it honestly with "memcpy(dst,src,len); dst[len] = '\0';", instead.
601 #define StrNCpy(dst,src,len) \
604 char * _dst = (dst); \
609 strncpy(_dst, (src), _len); \
610 _dst[_len-1] = '\0'; \
615 /* Get a bit mask of the bits set in non-long aligned addresses */
616 #define LONG_ALIGN_MASK (sizeof(long) - 1)
620 * Exactly the same as standard library function memset(), but considerably
621 * faster for zeroing small word-aligned structures (such as parsetree nodes).
622 * This has to be a macro because the main point is to avoid function-call
623 * overhead. However, we have also found that the loop is faster than
624 * native libc memset() on some platforms, even those with assembler
625 * memset() functions. More research needs to be done, perhaps with
626 * MEMSET_LOOP_LIMIT tests in configure.
628 #define MemSet(start, val, len) \
631 /* must be void* because we don't know if it is integer aligned yet */ \
632 void *_vstart = (void *) (start); \
636 if ((((long) _vstart) & LONG_ALIGN_MASK) == 0 && \
637 (_len & LONG_ALIGN_MASK) == 0 && \
639 _len <= MEMSET_LOOP_LIMIT && \
641 * If MEMSET_LOOP_LIMIT == 0, optimizer should find \
642 * the whole "if" false at compile time. \
644 MEMSET_LOOP_LIMIT != 0) \
646 long *_start = (long *) _vstart; \
647 long *_stop = (long *) ((char *) _start + _len); \
648 while (_start < _stop) \
652 memset(_vstart, _val, _len); \
656 * MemSetAligned is the same as MemSet except it omits the test to see if
657 * "start" is word-aligned. This is okay to use if the caller knows a-priori
658 * that the pointer is suitably aligned (typically, because he just got it
659 * from palloc(), which always delivers a max-aligned pointer).
661 #define MemSetAligned(start, val, len) \
664 long *_start = (long *) (start); \
668 if ((_len & LONG_ALIGN_MASK) == 0 && \
670 _len <= MEMSET_LOOP_LIMIT && \
671 MEMSET_LOOP_LIMIT != 0) \
673 long *_stop = (long *) ((char *) _start + _len); \
674 while (_start < _stop) \
678 memset(_start, _val, _len); \
683 * MemSetTest/MemSetLoop are a variant version that allow all the tests in
684 * MemSet to be done at compile time in cases where "val" and "len" are
685 * constants *and* we know the "start" pointer must be word-aligned.
686 * If MemSetTest succeeds, then it is okay to use MemSetLoop, otherwise use
687 * MemSetAligned. Beware of multiple evaluations of the arguments when using
690 #define MemSetTest(val, len) \
691 ( ((len) & LONG_ALIGN_MASK) == 0 && \
692 (len) <= MEMSET_LOOP_LIMIT && \
693 MEMSET_LOOP_LIMIT != 0 && \
696 #define MemSetLoop(start, val, len) \
699 long * _start = (long *) (start); \
700 long * _stop = (long *) ((char *) _start + (Size) (len)); \
702 while (_start < _stop) \
707 /* ----------------------------------------------------------------
708 * Section 7: random stuff
709 * ----------------------------------------------------------------
713 #define HIGHBIT (0x80)
714 #define IS_HIGHBIT_SET(ch) ((unsigned char)(ch) & HIGHBIT)
716 #define STATUS_OK (0)
717 #define STATUS_ERROR (-1)
718 #define STATUS_EOF (-2)
719 #define STATUS_FOUND (1)
720 #define STATUS_WAITING (2)
723 /* ----------------------------------------------------------------
724 * Section 8: system-specific hacks
726 * This should be limited to things that absolutely have to be
727 * included in every source file. The port-specific header file
728 * is usually a better place for this sort of thing.
729 * ----------------------------------------------------------------
733 * NOTE: this is also used for opening text files.
734 * WIN32 treats Control-Z as EOF in files opened in text mode.
735 * Therefore, we open files in binary mode on Win32 so we can read
736 * literal control-Z. The other affect is that we see CRLF, but
737 * that is OK because we can already handle those cleanly.
739 #if defined(WIN32) || defined(__CYGWIN__)
740 #define PG_BINARY O_BINARY
741 #define PG_BINARY_R "rb"
742 #define PG_BINARY_W "wb"
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 */