]> granicus.if.org Git - postgresql/blob - src/include/c.h
Rely on inline functions even if that causes warnings in older compilers.
[postgresql] / src / include / c.h
1 /*-------------------------------------------------------------------------
2  *
3  * c.h
4  *        Fundamental C definitions.  This is included by every .c file in
5  *        PostgreSQL (via either postgres.h or postgres_fe.h, as appropriate).
6  *
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...
10  *
11  *
12  * Portions Copyright (c) 1996-2015, PostgreSQL Global Development Group
13  * Portions Copyright (c) 1994, Regents of the University of California
14  *
15  * src/include/c.h
16  *
17  *-------------------------------------------------------------------------
18  */
19 /*
20  *----------------------------------------------------------------
21  *       TABLE OF CONTENTS
22  *
23  *              When adding stuff to this file, please try to put stuff
24  *              into the relevant section, or add new sections as appropriate.
25  *
26  *        section       description
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)              assertions
35  *              7)              widely useful macros
36  *              8)              random stuff
37  *              9)              system-specific hacks
38  *
39  * NOTE: since this file is included by both frontend and backend modules, it's
40  * almost certainly wrong to put an "extern" declaration here.  typedefs and
41  * macros are the kind of thing that might go here.
42  *
43  *----------------------------------------------------------------
44  */
45 #ifndef C_H
46 #define C_H
47
48 #include "postgres_ext.h"
49
50 /* Must undef pg_config_ext.h symbols before including pg_config.h */
51 #undef PG_INT64_TYPE
52
53 #include "pg_config.h"
54 #include "pg_config_manual.h"   /* must be after pg_config.h */
55
56 /*
57  * Force disable inlining if PG_FORCE_DISABLE_INLINE is defined. This is used
58  * to work around compiler bugs and might also be useful for investigatory
59  * purposes.
60  *
61  * This is done early (in slightly the wrong section) for two reasons: a) we
62  * don't want to include headers with different settings of this b)
63  * functionality later in this file might want to rely on inline functions.
64  */
65 #ifdef PG_FORCE_DISABLE_INLINE
66 #undef inline
67 #define inline
68 #endif
69
70 /*
71  * We always rely on the WIN32 macro being set by our build system,
72  * but _WIN32 is the compiler pre-defined macro. So make sure we define
73  * WIN32 whenever _WIN32 is set, to facilitate standalone building.
74  */
75 #if defined(_WIN32) && !defined(WIN32)
76 #define WIN32
77 #endif
78
79 #if !defined(WIN32) && !defined(__CYGWIN__)             /* win32 includes further down */
80 #include "pg_config_os.h"               /* must be before any system header files */
81 #endif
82
83 #if _MSC_VER >= 1400 || defined(HAVE_CRTDEFS_H)
84 #define errcode __msvc_errcode
85 #include <crtdefs.h>
86 #undef errcode
87 #endif
88
89 /*
90  * We have to include stdlib.h here because it defines many of these macros
91  * on some platforms, and we only want our definitions used if stdlib.h doesn't
92  * have its own.  The same goes for stddef and stdarg if present.
93  */
94
95 #include <stdio.h>
96 #include <stdlib.h>
97 #include <string.h>
98 #include <stddef.h>
99 #include <stdarg.h>
100 #ifdef HAVE_STRINGS_H
101 #include <strings.h>
102 #endif
103 #ifdef HAVE_STDINT_H
104 #include <stdint.h>
105 #endif
106 #include <sys/types.h>
107
108 #include <errno.h>
109 #if defined(WIN32) || defined(__CYGWIN__)
110 #include <fcntl.h>                              /* ensure O_BINARY is available */
111 #endif
112
113 #if defined(WIN32) || defined(__CYGWIN__)
114 /* We have to redefine some system functions after they are included above. */
115 #include "pg_config_os.h"
116 #endif
117
118 /* Must be before gettext() games below */
119 #include <locale.h>
120
121 #define _(x) gettext(x)
122
123 #ifdef ENABLE_NLS
124 #include <libintl.h>
125 #else
126 #define gettext(x) (x)
127 #define dgettext(d,x) (x)
128 #define ngettext(s,p,n) ((n) == 1 ? (s) : (p))
129 #define dngettext(d,s,p,n) ((n) == 1 ? (s) : (p))
130 #endif
131
132 /*
133  *      Use this to mark string constants as needing translation at some later
134  *      time, rather than immediately.  This is useful for cases where you need
135  *      access to the original string and translated string, and for cases where
136  *      immediate translation is not possible, like when initializing global
137  *      variables.
138  *              http://www.gnu.org/software/autoconf/manual/gettext/Special-cases.html
139  */
140 #define gettext_noop(x) (x)
141
142
143 /* ----------------------------------------------------------------
144  *                              Section 1: hacks to cope with non-ANSI C compilers
145  *
146  * type prefixes (const, signed, volatile, inline) are handled in pg_config.h.
147  * ----------------------------------------------------------------
148  */
149
150 /*
151  * CppAsString
152  *              Convert the argument to a string, using the C preprocessor.
153  * CppConcat
154  *              Concatenate two arguments together, using the C preprocessor.
155  *
156  * Note: There used to be support here for pre-ANSI C compilers that didn't
157  * support # and ##.  Nowadays, these macros are just for clarity and/or
158  * backward compatibility with existing PostgreSQL code.
159  */
160 #define CppAsString(identifier) #identifier
161 #define CppConcat(x, y)                 x##y
162
163 /*
164  * dummyret is used to set return values in macros that use ?: to make
165  * assignments.  gcc wants these to be void, other compilers like char
166  */
167 #ifdef __GNUC__                                 /* GNU cc */
168 #define dummyret        void
169 #else
170 #define dummyret        char
171 #endif
172
173 /* ----------------------------------------------------------------
174  *                              Section 2:      bool, true, false, TRUE, FALSE, NULL
175  * ----------------------------------------------------------------
176  */
177
178 /*
179  * bool
180  *              Boolean value, either true or false.
181  *
182  * XXX for C++ compilers, we assume the compiler has a compatible
183  * built-in definition of bool.
184  */
185
186 #ifndef __cplusplus
187
188 #ifndef bool
189 typedef char bool;
190 #endif
191
192 #ifndef true
193 #define true    ((bool) 1)
194 #endif
195
196 #ifndef false
197 #define false   ((bool) 0)
198 #endif
199 #endif   /* not C++ */
200
201 typedef bool *BoolPtr;
202
203 #ifndef TRUE
204 #define TRUE    1
205 #endif
206
207 #ifndef FALSE
208 #define FALSE   0
209 #endif
210
211 /*
212  * NULL
213  *              Null pointer.
214  */
215 #ifndef NULL
216 #define NULL    ((void *) 0)
217 #endif
218
219
220 /* ----------------------------------------------------------------
221  *                              Section 3:      standard system types
222  * ----------------------------------------------------------------
223  */
224
225 /*
226  * Pointer
227  *              Variable holding address of any memory resident object.
228  *
229  *              XXX Pointer arithmetic is done with this, so it can't be void *
230  *              under "true" ANSI compilers.
231  */
232 typedef char *Pointer;
233
234 /*
235  * intN
236  *              Signed integer, EXACTLY N BITS IN SIZE,
237  *              used for numerical computations and the
238  *              frontend/backend protocol.
239  */
240 #ifndef HAVE_INT8
241 typedef signed char int8;               /* == 8 bits */
242 typedef signed short int16;             /* == 16 bits */
243 typedef signed int int32;               /* == 32 bits */
244 #endif   /* not HAVE_INT8 */
245
246 /*
247  * uintN
248  *              Unsigned integer, EXACTLY N BITS IN SIZE,
249  *              used for numerical computations and the
250  *              frontend/backend protocol.
251  */
252 #ifndef HAVE_UINT8
253 typedef unsigned char uint8;    /* == 8 bits */
254 typedef unsigned short uint16;  /* == 16 bits */
255 typedef unsigned int uint32;    /* == 32 bits */
256 #endif   /* not HAVE_UINT8 */
257
258 /*
259  * bitsN
260  *              Unit of bitwise operation, AT LEAST N BITS IN SIZE.
261  */
262 typedef uint8 bits8;                    /* >= 8 bits */
263 typedef uint16 bits16;                  /* >= 16 bits */
264 typedef uint32 bits32;                  /* >= 32 bits */
265
266 /*
267  * 64-bit integers
268  */
269 #ifdef HAVE_LONG_INT_64
270 /* Plain "long int" fits, use it */
271
272 #ifndef HAVE_INT64
273 typedef long int int64;
274 #endif
275 #ifndef HAVE_UINT64
276 typedef unsigned long int uint64;
277 #endif
278 #elif defined(HAVE_LONG_LONG_INT_64)
279 /* We have working support for "long long int", use that */
280
281 #ifndef HAVE_INT64
282 typedef long long int int64;
283 #endif
284 #ifndef HAVE_UINT64
285 typedef unsigned long long int uint64;
286 #endif
287 #else
288 /* neither HAVE_LONG_INT_64 nor HAVE_LONG_LONG_INT_64 */
289 #error must have a working 64-bit integer datatype
290 #endif
291
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)
296 #else
297 #define INT64CONST(x)  ((int64) x)
298 #define UINT64CONST(x) ((uint64) x)
299 #endif
300
301 /* snprintf format strings to use for 64-bit integers */
302 #define INT64_FORMAT "%" INT64_MODIFIER "d"
303 #define UINT64_FORMAT "%" INT64_MODIFIER "u"
304
305 /*
306  * 128-bit signed and unsigned integers
307  *              There currently is only a limited support for the type. E.g. 128bit
308  *              literals and snprintf are not supported; but math is.
309  */
310 #if defined(PG_INT128_TYPE)
311 #define HAVE_INT128
312 typedef PG_INT128_TYPE int128;
313 typedef unsigned PG_INT128_TYPE uint128;
314 #endif
315
316 /*
317  * stdint.h limits aren't guaranteed to be present and aren't guaranteed to
318  * have compatible types with our fixed width types. So just define our own.
319  */
320 #define PG_INT8_MIN             (-0x7F-1)
321 #define PG_INT8_MAX             (0x7F)
322 #define PG_UINT8_MAX    (0xFF)
323 #define PG_INT16_MIN    (-0x7FFF-1)
324 #define PG_INT16_MAX    (0x7FFF)
325 #define PG_UINT16_MAX   (0xFFFF)
326 #define PG_INT32_MIN    (-0x7FFFFFFF-1)
327 #define PG_INT32_MAX    (0x7FFFFFFF)
328 #define PG_UINT32_MAX   (0xFFFFFFFF)
329 #define PG_INT64_MIN    (-INT64CONST(0x7FFFFFFFFFFFFFFF) - 1)
330 #define PG_INT64_MAX    INT64CONST(0x7FFFFFFFFFFFFFFF)
331 #define PG_UINT64_MAX   UINT64CONST(0xFFFFFFFFFFFFFFFF)
332
333 /* Select timestamp representation (float8 or int64) */
334 #ifdef USE_INTEGER_DATETIMES
335 #define HAVE_INT64_TIMESTAMP
336 #endif
337
338 /* sig_atomic_t is required by ANSI C, but may be missing on old platforms */
339 #ifndef HAVE_SIG_ATOMIC_T
340 typedef int sig_atomic_t;
341 #endif
342
343 /*
344  * Size
345  *              Size of any memory resident object, as returned by sizeof.
346  */
347 typedef size_t Size;
348
349 /*
350  * Index
351  *              Index into any memory resident array.
352  *
353  * Note:
354  *              Indices are non negative.
355  */
356 typedef unsigned int Index;
357
358 /*
359  * Offset
360  *              Offset into any memory resident array.
361  *
362  * Note:
363  *              This differs from an Index in that an Index is always
364  *              non negative, whereas Offset may be negative.
365  */
366 typedef signed int Offset;
367
368 /*
369  * Common Postgres datatype names (as used in the catalogs)
370  */
371 typedef float float4;
372 typedef double float8;
373
374 /*
375  * Oid, RegProcedure, TransactionId, SubTransactionId, MultiXactId,
376  * CommandId
377  */
378
379 /* typedef Oid is in postgres_ext.h */
380
381 /*
382  * regproc is the type name used in the include/catalog headers, but
383  * RegProcedure is the preferred name in C code.
384  */
385 typedef Oid regproc;
386 typedef regproc RegProcedure;
387
388 typedef uint32 TransactionId;
389
390 typedef uint32 LocalTransactionId;
391
392 typedef uint32 SubTransactionId;
393
394 #define InvalidSubTransactionId         ((SubTransactionId) 0)
395 #define TopSubTransactionId                     ((SubTransactionId) 1)
396
397 /* MultiXactId must be equivalent to TransactionId, to fit in t_xmax */
398 typedef TransactionId MultiXactId;
399
400 typedef uint32 MultiXactOffset;
401
402 typedef uint32 CommandId;
403
404 #define FirstCommandId  ((CommandId) 0)
405 #define InvalidCommandId        (~(CommandId)0)
406
407 /*
408  * Array indexing support
409  */
410 #define MAXDIM 6
411 typedef struct
412 {
413         int                     indx[MAXDIM];
414 } IntArray;
415
416 /* ----------------
417  *              Variable-length datatypes all share the 'struct varlena' header.
418  *
419  * NOTE: for TOASTable types, this is an oversimplification, since the value
420  * may be compressed or moved out-of-line.  However datatype-specific routines
421  * are mostly content to deal with de-TOASTed values only, and of course
422  * client-side routines should never see a TOASTed value.  But even in a
423  * de-TOASTed value, beware of touching vl_len_ directly, as its representation
424  * is no longer convenient.  It's recommended that code always use the VARDATA,
425  * VARSIZE, and SET_VARSIZE macros instead of relying on direct mentions of
426  * the struct fields.  See postgres.h for details of the TOASTed form.
427  * ----------------
428  */
429 struct varlena
430 {
431         char            vl_len_[4];             /* Do not touch this field directly! */
432         char            vl_dat[FLEXIBLE_ARRAY_MEMBER];  /* Data content is here */
433 };
434
435 #define VARHDRSZ                ((int32) sizeof(int32))
436
437 /*
438  * These widely-used datatypes are just a varlena header and the data bytes.
439  * There is no terminating null or anything like that --- the data length is
440  * always VARSIZE(ptr) - VARHDRSZ.
441  */
442 typedef struct varlena bytea;
443 typedef struct varlena text;
444 typedef struct varlena BpChar;  /* blank-padded char, ie SQL char(n) */
445 typedef struct varlena VarChar; /* var-length char, ie SQL varchar(n) */
446
447 /*
448  * Specialized array types.  These are physically laid out just the same
449  * as regular arrays (so that the regular array subscripting code works
450  * with them).  They exist as distinct types mostly for historical reasons:
451  * they have nonstandard I/O behavior which we don't want to change for fear
452  * of breaking applications that look at the system catalogs.  There is also
453  * an implementation issue for oidvector: it's part of the primary key for
454  * pg_proc, and we can't use the normal btree array support routines for that
455  * without circularity.
456  */
457 typedef struct
458 {
459         int32           vl_len_;                /* these fields must match ArrayType! */
460         int                     ndim;                   /* always 1 for int2vector */
461         int32           dataoffset;             /* always 0 for int2vector */
462         Oid                     elemtype;
463         int                     dim1;
464         int                     lbound1;
465         int16           values[FLEXIBLE_ARRAY_MEMBER];
466 } int2vector;
467
468 typedef struct
469 {
470         int32           vl_len_;                /* these fields must match ArrayType! */
471         int                     ndim;                   /* always 1 for oidvector */
472         int32           dataoffset;             /* always 0 for oidvector */
473         Oid                     elemtype;
474         int                     dim1;
475         int                     lbound1;
476         Oid                     values[FLEXIBLE_ARRAY_MEMBER];
477 } oidvector;
478
479 /*
480  * Representation of a Name: effectively just a C string, but null-padded to
481  * exactly NAMEDATALEN bytes.  The use of a struct is historical.
482  */
483 typedef struct nameData
484 {
485         char            data[NAMEDATALEN];
486 } NameData;
487 typedef NameData *Name;
488
489 #define NameStr(name)   ((name).data)
490
491 /*
492  * Support macros for escaping strings.  escape_backslash should be TRUE
493  * if generating a non-standard-conforming string.  Prefixing a string
494  * with ESCAPE_STRING_SYNTAX guarantees it is non-standard-conforming.
495  * Beware of multiple evaluation of the "ch" argument!
496  */
497 #define SQL_STR_DOUBLE(ch, escape_backslash)    \
498         ((ch) == '\'' || ((ch) == '\\' && (escape_backslash)))
499
500 #define ESCAPE_STRING_SYNTAX    'E'
501
502 /* ----------------------------------------------------------------
503  *                              Section 4:      IsValid macros for system types
504  * ----------------------------------------------------------------
505  */
506 /*
507  * BoolIsValid
508  *              True iff bool is valid.
509  */
510 #define BoolIsValid(boolean)    ((boolean) == false || (boolean) == true)
511
512 /*
513  * PointerIsValid
514  *              True iff pointer is valid.
515  */
516 #define PointerIsValid(pointer) ((const void*)(pointer) != NULL)
517
518 /*
519  * PointerIsAligned
520  *              True iff pointer is properly aligned to point to the given type.
521  */
522 #define PointerIsAligned(pointer, type) \
523                 (((uintptr_t)(pointer) % (sizeof (type))) == 0)
524
525 #define OidIsValid(objectId)  ((bool) ((objectId) != InvalidOid))
526
527 #define RegProcedureIsValid(p)  OidIsValid(p)
528
529
530 /* ----------------------------------------------------------------
531  *                              Section 5:      offsetof, lengthof, endof, alignment
532  * ----------------------------------------------------------------
533  */
534 /*
535  * offsetof
536  *              Offset of a structure/union field within that structure/union.
537  *
538  *              XXX This is supposed to be part of stddef.h, but isn't on
539  *              some systems (like SunOS 4).
540  */
541 #ifndef offsetof
542 #define offsetof(type, field)   ((long) &((type *)0)->field)
543 #endif   /* offsetof */
544
545 /*
546  * lengthof
547  *              Number of elements in an array.
548  */
549 #define lengthof(array) (sizeof (array) / sizeof ((array)[0]))
550
551 /*
552  * endof
553  *              Address of the element one past the last in an array.
554  */
555 #define endof(array)    (&(array)[lengthof(array)])
556
557 /* ----------------
558  * Alignment macros: align a length or address appropriately for a given type.
559  * The fooALIGN() macros round up to a multiple of the required alignment,
560  * while the fooALIGN_DOWN() macros round down.  The latter are more useful
561  * for problems like "how many X-sized structures will fit in a page?".
562  *
563  * NOTE: TYPEALIGN[_DOWN] will not work if ALIGNVAL is not a power of 2.
564  * That case seems extremely unlikely to be needed in practice, however.
565  * ----------------
566  */
567
568 #define TYPEALIGN(ALIGNVAL,LEN)  \
569         (((uintptr_t) (LEN) + ((ALIGNVAL) - 1)) & ~((uintptr_t) ((ALIGNVAL) - 1)))
570
571 #define SHORTALIGN(LEN)                 TYPEALIGN(ALIGNOF_SHORT, (LEN))
572 #define INTALIGN(LEN)                   TYPEALIGN(ALIGNOF_INT, (LEN))
573 #define LONGALIGN(LEN)                  TYPEALIGN(ALIGNOF_LONG, (LEN))
574 #define DOUBLEALIGN(LEN)                TYPEALIGN(ALIGNOF_DOUBLE, (LEN))
575 #define MAXALIGN(LEN)                   TYPEALIGN(MAXIMUM_ALIGNOF, (LEN))
576 /* MAXALIGN covers only built-in types, not buffers */
577 #define BUFFERALIGN(LEN)                TYPEALIGN(ALIGNOF_BUFFER, (LEN))
578 #define CACHELINEALIGN(LEN)             TYPEALIGN(PG_CACHE_LINE_SIZE, (LEN))
579
580 #define TYPEALIGN_DOWN(ALIGNVAL,LEN)  \
581         (((uintptr_t) (LEN)) & ~((uintptr_t) ((ALIGNVAL) - 1)))
582
583 #define SHORTALIGN_DOWN(LEN)    TYPEALIGN_DOWN(ALIGNOF_SHORT, (LEN))
584 #define INTALIGN_DOWN(LEN)              TYPEALIGN_DOWN(ALIGNOF_INT, (LEN))
585 #define LONGALIGN_DOWN(LEN)             TYPEALIGN_DOWN(ALIGNOF_LONG, (LEN))
586 #define DOUBLEALIGN_DOWN(LEN)   TYPEALIGN_DOWN(ALIGNOF_DOUBLE, (LEN))
587 #define MAXALIGN_DOWN(LEN)              TYPEALIGN_DOWN(MAXIMUM_ALIGNOF, (LEN))
588
589 /*
590  * The above macros will not work with types wider than uintptr_t, like with
591  * uint64 on 32-bit platforms.  That's not problem for the usual use where a
592  * pointer or a length is aligned, but for the odd case that you need to
593  * align something (potentially) wider, use TYPEALIGN64.
594  */
595 #define TYPEALIGN64(ALIGNVAL,LEN)  \
596         (((uint64) (LEN) + ((ALIGNVAL) - 1)) & ~((uint64) ((ALIGNVAL) - 1)))
597
598 /* we don't currently need wider versions of the other ALIGN macros */
599 #define MAXALIGN64(LEN)                 TYPEALIGN64(MAXIMUM_ALIGNOF, (LEN))
600
601 /* ----------------
602  * Attribute macros
603  *
604  * GCC: https://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
605  * GCC: https://gcc.gnu.org/onlinedocs/gcc/Type-Attributes.html
606  * Sunpro: https://docs.oracle.com/cd/E18659_01/html/821-1384/gjzke.html
607  * XLC: http://www-01.ibm.com/support/knowledgecenter/SSGH2K_11.1.0/com.ibm.xlc111.aix.doc/language_ref/function_attributes.html
608  * XLC: http://www-01.ibm.com/support/knowledgecenter/SSGH2K_11.1.0/com.ibm.xlc111.aix.doc/language_ref/type_attrib.html
609  * ----------------
610  */
611
612 /* only GCC supports the unused attribute */
613 #ifdef __GNUC__
614 #define pg_attribute_unused() __attribute__((unused))
615 #else
616 #define pg_attribute_unused()
617 #endif
618
619 /* GCC and XLC support format attributes */
620 #if defined(__GNUC__) || defined(__IBMC__)
621 #define pg_attribute_format_arg(a) __attribute__((format_arg(a)))
622 #define pg_attribute_printf(f,a) __attribute__((format(PG_PRINTF_ATTRIBUTE, f, a)))
623 #else
624 #define pg_attribute_format_arg(a)
625 #define pg_attribute_printf(f,a)
626 #endif
627
628 /* GCC, Sunpro and XLC support aligned, packed and noreturn */
629 #if defined(__GNUC__) || defined(__SUNPRO_C) || defined(__IBMC__)
630 #define pg_attribute_aligned(a) __attribute__((aligned(a)))
631 #define pg_attribute_noreturn() __attribute__((noreturn))
632 #define pg_attribute_packed() __attribute__((packed))
633 #define HAVE_PG_ATTRIBUTE_NORETURN 1
634 #else
635 /*
636  * NB: aligned and packed are not given default definitions because they
637  * affect code functionality; they *must* be implemented by the compiler
638  * if they are to be used.
639  */
640 #define pg_attribute_noreturn()
641 #endif
642
643 /* ----------------------------------------------------------------
644  *                              Section 6:      assertions
645  * ----------------------------------------------------------------
646  */
647
648 /*
649  * USE_ASSERT_CHECKING, if defined, turns on all the assertions.
650  * - plai  9/5/90
651  *
652  * It should _NOT_ be defined in releases or in benchmark copies
653  */
654
655 /*
656  * Assert() can be used in both frontend and backend code. In frontend code it
657  * just calls the standard assert, if it's available. If use of assertions is
658  * not configured, it does nothing.
659  */
660 #ifndef USE_ASSERT_CHECKING
661
662 #define Assert(condition)       ((void)true)
663 #define AssertMacro(condition)  ((void)true)
664 #define AssertArg(condition)    ((void)true)
665 #define AssertState(condition)  ((void)true)
666 #define AssertPointerAlignment(ptr, bndr)       ((void)true)
667 #define Trap(condition, errorType)      ((void)true)
668 #define TrapMacro(condition, errorType) (true)
669
670 #elif defined(FRONTEND)
671
672 #include <assert.h>
673 #define Assert(p) assert(p)
674 #define AssertMacro(p)  ((void) assert(p))
675 #define AssertArg(condition) assert(condition)
676 #define AssertState(condition) assert(condition)
677 #define AssertPointerAlignment(ptr, bndr)       ((void)true)
678 #else                                                   /* USE_ASSERT_CHECKING && !FRONTEND */
679
680 /*
681  * Trap
682  *              Generates an exception if the given condition is true.
683  */
684 #define Trap(condition, errorType) \
685         do { \
686                 if (condition) \
687                         ExceptionalCondition(CppAsString(condition), (errorType), \
688                                                                  __FILE__, __LINE__); \
689         } while (0)
690
691 /*
692  *      TrapMacro is the same as Trap but it's intended for use in macros:
693  *
694  *              #define foo(x) (AssertMacro(x != 0), bar(x))
695  *
696  *      Isn't CPP fun?
697  */
698 #define TrapMacro(condition, errorType) \
699         ((bool) (! (condition) || \
700                          (ExceptionalCondition(CppAsString(condition), (errorType), \
701                                                                    __FILE__, __LINE__), 0)))
702
703 #define Assert(condition) \
704                 Trap(!(condition), "FailedAssertion")
705
706 #define AssertMacro(condition) \
707                 ((void) TrapMacro(!(condition), "FailedAssertion"))
708
709 #define AssertArg(condition) \
710                 Trap(!(condition), "BadArgument")
711
712 #define AssertState(condition) \
713                 Trap(!(condition), "BadState")
714
715 /*
716  * Check that `ptr' is `bndr' aligned.
717  */
718 #define AssertPointerAlignment(ptr, bndr) \
719         Trap(TYPEALIGN(bndr, (uintptr_t)(ptr)) != (uintptr_t)(ptr), \
720                  "UnalignedPointer")
721
722 #endif   /* USE_ASSERT_CHECKING && !FRONTEND */
723
724 /*
725  * Macros to support compile-time assertion checks.
726  *
727  * If the "condition" (a compile-time-constant expression) evaluates to false,
728  * throw a compile error using the "errmessage" (a string literal).
729  *
730  * gcc 4.6 and up supports _Static_assert(), but there are bizarre syntactic
731  * placement restrictions.  These macros make it safe to use as a statement
732  * or in an expression, respectively.
733  *
734  * Otherwise we fall back on a kluge that assumes the compiler will complain
735  * about a negative width for a struct bit-field.  This will not include a
736  * helpful error message, but it beats not getting an error at all.
737  */
738 #ifdef HAVE__STATIC_ASSERT
739 #define StaticAssertStmt(condition, errmessage) \
740         do { _Static_assert(condition, errmessage); } while(0)
741 #define StaticAssertExpr(condition, errmessage) \
742         ({ StaticAssertStmt(condition, errmessage); true; })
743 #else                                                   /* !HAVE__STATIC_ASSERT */
744 #define StaticAssertStmt(condition, errmessage) \
745         ((void) sizeof(struct { int static_assert_failure : (condition) ? 1 : -1; }))
746 #define StaticAssertExpr(condition, errmessage) \
747         StaticAssertStmt(condition, errmessage)
748 #endif   /* HAVE__STATIC_ASSERT */
749
750
751 /*
752  * Compile-time checks that a variable (or expression) has the specified type.
753  *
754  * AssertVariableIsOfType() can be used as a statement.
755  * AssertVariableIsOfTypeMacro() is intended for use in macros, eg
756  *              #define foo(x) (AssertVariableIsOfTypeMacro(x, int), bar(x))
757  *
758  * If we don't have __builtin_types_compatible_p, we can still assert that
759  * the types have the same size.  This is far from ideal (especially on 32-bit
760  * platforms) but it provides at least some coverage.
761  */
762 #ifdef HAVE__BUILTIN_TYPES_COMPATIBLE_P
763 #define AssertVariableIsOfType(varname, typename) \
764         StaticAssertStmt(__builtin_types_compatible_p(__typeof__(varname), typename), \
765         CppAsString(varname) " does not have type " CppAsString(typename))
766 #define AssertVariableIsOfTypeMacro(varname, typename) \
767         ((void) StaticAssertExpr(__builtin_types_compatible_p(__typeof__(varname), typename), \
768          CppAsString(varname) " does not have type " CppAsString(typename)))
769 #else                                                   /* !HAVE__BUILTIN_TYPES_COMPATIBLE_P */
770 #define AssertVariableIsOfType(varname, typename) \
771         StaticAssertStmt(sizeof(varname) == sizeof(typename), \
772         CppAsString(varname) " does not have type " CppAsString(typename))
773 #define AssertVariableIsOfTypeMacro(varname, typename) \
774         ((void) StaticAssertExpr(sizeof(varname) == sizeof(typename),           \
775          CppAsString(varname) " does not have type " CppAsString(typename)))
776 #endif   /* HAVE__BUILTIN_TYPES_COMPATIBLE_P */
777
778
779 /* ----------------------------------------------------------------
780  *                              Section 7:      widely useful macros
781  * ----------------------------------------------------------------
782  */
783 /*
784  * Max
785  *              Return the maximum of two numbers.
786  */
787 #define Max(x, y)               ((x) > (y) ? (x) : (y))
788
789 /*
790  * Min
791  *              Return the minimum of two numbers.
792  */
793 #define Min(x, y)               ((x) < (y) ? (x) : (y))
794
795 /*
796  * Abs
797  *              Return the absolute value of the argument.
798  */
799 #define Abs(x)                  ((x) >= 0 ? (x) : -(x))
800
801 /*
802  * StrNCpy
803  *      Like standard library function strncpy(), except that result string
804  *      is guaranteed to be null-terminated --- that is, at most N-1 bytes
805  *      of the source string will be kept.
806  *      Also, the macro returns no result (too hard to do that without
807  *      evaluating the arguments multiple times, which seems worse).
808  *
809  *      BTW: when you need to copy a non-null-terminated string (like a text
810  *      datum) and add a null, do not do it with StrNCpy(..., len+1).  That
811  *      might seem to work, but it fetches one byte more than there is in the
812  *      text object.  One fine day you'll have a SIGSEGV because there isn't
813  *      another byte before the end of memory.  Don't laugh, we've had real
814  *      live bug reports from real live users over exactly this mistake.
815  *      Do it honestly with "memcpy(dst,src,len); dst[len] = '\0';", instead.
816  */
817 #define StrNCpy(dst,src,len) \
818         do \
819         { \
820                 char * _dst = (dst); \
821                 Size _len = (len); \
822 \
823                 if (_len > 0) \
824                 { \
825                         strncpy(_dst, (src), _len); \
826                         _dst[_len-1] = '\0'; \
827                 } \
828         } while (0)
829
830
831 /* Get a bit mask of the bits set in non-long aligned addresses */
832 #define LONG_ALIGN_MASK (sizeof(long) - 1)
833
834 /*
835  * MemSet
836  *      Exactly the same as standard library function memset(), but considerably
837  *      faster for zeroing small word-aligned structures (such as parsetree nodes).
838  *      This has to be a macro because the main point is to avoid function-call
839  *      overhead.   However, we have also found that the loop is faster than
840  *      native libc memset() on some platforms, even those with assembler
841  *      memset() functions.  More research needs to be done, perhaps with
842  *      MEMSET_LOOP_LIMIT tests in configure.
843  */
844 #define MemSet(start, val, len) \
845         do \
846         { \
847                 /* must be void* because we don't know if it is integer aligned yet */ \
848                 void   *_vstart = (void *) (start); \
849                 int             _val = (val); \
850                 Size    _len = (len); \
851 \
852                 if ((((uintptr_t) _vstart) & LONG_ALIGN_MASK) == 0 && \
853                         (_len & LONG_ALIGN_MASK) == 0 && \
854                         _val == 0 && \
855                         _len <= MEMSET_LOOP_LIMIT && \
856                         /* \
857                          *      If MEMSET_LOOP_LIMIT == 0, optimizer should find \
858                          *      the whole "if" false at compile time. \
859                          */ \
860                         MEMSET_LOOP_LIMIT != 0) \
861                 { \
862                         long *_start = (long *) _vstart; \
863                         long *_stop = (long *) ((char *) _start + _len); \
864                         while (_start < _stop) \
865                                 *_start++ = 0; \
866                 } \
867                 else \
868                         memset(_vstart, _val, _len); \
869         } while (0)
870
871 /*
872  * MemSetAligned is the same as MemSet except it omits the test to see if
873  * "start" is word-aligned.  This is okay to use if the caller knows a-priori
874  * that the pointer is suitably aligned (typically, because he just got it
875  * from palloc(), which always delivers a max-aligned pointer).
876  */
877 #define MemSetAligned(start, val, len) \
878         do \
879         { \
880                 long   *_start = (long *) (start); \
881                 int             _val = (val); \
882                 Size    _len = (len); \
883 \
884                 if ((_len & LONG_ALIGN_MASK) == 0 && \
885                         _val == 0 && \
886                         _len <= MEMSET_LOOP_LIMIT && \
887                         MEMSET_LOOP_LIMIT != 0) \
888                 { \
889                         long *_stop = (long *) ((char *) _start + _len); \
890                         while (_start < _stop) \
891                                 *_start++ = 0; \
892                 } \
893                 else \
894                         memset(_start, _val, _len); \
895         } while (0)
896
897
898 /*
899  * MemSetTest/MemSetLoop are a variant version that allow all the tests in
900  * MemSet to be done at compile time in cases where "val" and "len" are
901  * constants *and* we know the "start" pointer must be word-aligned.
902  * If MemSetTest succeeds, then it is okay to use MemSetLoop, otherwise use
903  * MemSetAligned.  Beware of multiple evaluations of the arguments when using
904  * this approach.
905  */
906 #define MemSetTest(val, len) \
907         ( ((len) & LONG_ALIGN_MASK) == 0 && \
908         (len) <= MEMSET_LOOP_LIMIT && \
909         MEMSET_LOOP_LIMIT != 0 && \
910         (val) == 0 )
911
912 #define MemSetLoop(start, val, len) \
913         do \
914         { \
915                 long * _start = (long *) (start); \
916                 long * _stop = (long *) ((char *) _start + (Size) (len)); \
917         \
918                 while (_start < _stop) \
919                         *_start++ = 0; \
920         } while (0)
921
922
923 /*
924  * Mark a point as unreachable in a portable fashion.  This should preferably
925  * be something that the compiler understands, to aid code generation.
926  * In assert-enabled builds, we prefer abort() for debugging reasons.
927  */
928 #if defined(HAVE__BUILTIN_UNREACHABLE) && !defined(USE_ASSERT_CHECKING)
929 #define pg_unreachable() __builtin_unreachable()
930 #elif defined(_MSC_VER) && !defined(USE_ASSERT_CHECKING)
931 #define pg_unreachable() __assume(0)
932 #else
933 #define pg_unreachable() abort()
934 #endif
935
936
937 /* ----------------------------------------------------------------
938  *                              Section 8:      random stuff
939  * ----------------------------------------------------------------
940  */
941
942 /* msb for char */
943 #define HIGHBIT                                 (0x80)
944 #define IS_HIGHBIT_SET(ch)              ((unsigned char)(ch) & HIGHBIT)
945
946 #define STATUS_OK                               (0)
947 #define STATUS_ERROR                    (-1)
948 #define STATUS_EOF                              (-2)
949 #define STATUS_FOUND                    (1)
950 #define STATUS_WAITING                  (2)
951
952
953 /*
954  * Append PG_USED_FOR_ASSERTS_ONLY to definitions of variables that are only
955  * used in assert-enabled builds, to avoid compiler warnings about unused
956  * variables in assert-disabled builds.
957  */
958 #ifdef USE_ASSERT_CHECKING
959 #define PG_USED_FOR_ASSERTS_ONLY
960 #else
961 #define PG_USED_FOR_ASSERTS_ONLY pg_attribute_unused()
962 #endif
963
964
965 /* gettext domain name mangling */
966
967 /*
968  * To better support parallel installations of major PostgeSQL
969  * versions as well as parallel installations of major library soname
970  * versions, we mangle the gettext domain name by appending those
971  * version numbers.  The coding rule ought to be that wherever the
972  * domain name is mentioned as a literal, it must be wrapped into
973  * PG_TEXTDOMAIN().  The macros below do not work on non-literals; but
974  * that is somewhat intentional because it avoids having to worry
975  * about multiple states of premangling and postmangling as the values
976  * are being passed around.
977  *
978  * Make sure this matches the installation rules in nls-global.mk.
979  */
980
981 /* need a second indirection because we want to stringize the macro value, not the name */
982 #define CppAsString2(x) CppAsString(x)
983
984 #ifdef SO_MAJOR_VERSION
985 #define PG_TEXTDOMAIN(domain) (domain CppAsString2(SO_MAJOR_VERSION) "-" PG_MAJORVERSION)
986 #else
987 #define PG_TEXTDOMAIN(domain) (domain "-" PG_MAJORVERSION)
988 #endif
989
990
991 /* ----------------------------------------------------------------
992  *                              Section 9: system-specific hacks
993  *
994  *              This should be limited to things that absolutely have to be
995  *              included in every source file.  The port-specific header file
996  *              is usually a better place for this sort of thing.
997  * ----------------------------------------------------------------
998  */
999
1000 /*
1001  *      NOTE:  this is also used for opening text files.
1002  *      WIN32 treats Control-Z as EOF in files opened in text mode.
1003  *      Therefore, we open files in binary mode on Win32 so we can read
1004  *      literal control-Z.  The other affect is that we see CRLF, but
1005  *      that is OK because we can already handle those cleanly.
1006  */
1007 #if defined(WIN32) || defined(__CYGWIN__)
1008 #define PG_BINARY       O_BINARY
1009 #define PG_BINARY_A "ab"
1010 #define PG_BINARY_R "rb"
1011 #define PG_BINARY_W "wb"
1012 #else
1013 #define PG_BINARY       0
1014 #define PG_BINARY_A "a"
1015 #define PG_BINARY_R "r"
1016 #define PG_BINARY_W "w"
1017 #endif
1018
1019 /*
1020  * Provide prototypes for routines not present in a particular machine's
1021  * standard C library.
1022  */
1023
1024 #if !HAVE_DECL_SNPRINTF
1025 extern int      snprintf(char *str, size_t count, const char *fmt,...) pg_attribute_printf(3, 4);
1026 #endif
1027
1028 #if !HAVE_DECL_VSNPRINTF
1029 extern int      vsnprintf(char *str, size_t count, const char *fmt, va_list args);
1030 #endif
1031
1032 #if !defined(HAVE_MEMMOVE) && !defined(memmove)
1033 #define memmove(d, s, c)                bcopy(s, d, c)
1034 #endif
1035
1036 /* no special DLL markers on most ports */
1037 #ifndef PGDLLIMPORT
1038 #define PGDLLIMPORT
1039 #endif
1040 #ifndef PGDLLEXPORT
1041 #define PGDLLEXPORT
1042 #endif
1043
1044 /*
1045  * The following is used as the arg list for signal handlers.  Any ports
1046  * that take something other than an int argument should override this in
1047  * their pg_config_os.h file.  Note that variable names are required
1048  * because it is used in both the prototypes as well as the definitions.
1049  * Note also the long name.  We expect that this won't collide with
1050  * other names causing compiler warnings.
1051  */
1052
1053 #ifndef SIGNAL_ARGS
1054 #define SIGNAL_ARGS  int postgres_signal_arg
1055 #endif
1056
1057 /*
1058  * When there is no sigsetjmp, its functionality is provided by plain
1059  * setjmp. Incidentally, nothing provides setjmp's functionality in
1060  * that case.
1061  */
1062 #ifndef HAVE_SIGSETJMP
1063 #define sigjmp_buf jmp_buf
1064 #define sigsetjmp(x,y) setjmp(x)
1065 #define siglongjmp longjmp
1066 #endif
1067
1068 #if defined(HAVE_FDATASYNC) && !HAVE_DECL_FDATASYNC
1069 extern int      fdatasync(int fildes);
1070 #endif
1071
1072 /* If strtoq() exists, rename it to the more standard strtoll() */
1073 #if defined(HAVE_LONG_LONG_INT_64) && !defined(HAVE_STRTOLL) && defined(HAVE_STRTOQ)
1074 #define strtoll strtoq
1075 #define HAVE_STRTOLL 1
1076 #endif
1077
1078 /* If strtouq() exists, rename it to the more standard strtoull() */
1079 #if defined(HAVE_LONG_LONG_INT_64) && !defined(HAVE_STRTOULL) && defined(HAVE_STRTOUQ)
1080 #define strtoull strtouq
1081 #define HAVE_STRTOULL 1
1082 #endif
1083
1084 /*
1085  * We assume if we have these two functions, we have their friends too, and
1086  * can use the wide-character functions.
1087  */
1088 #if defined(HAVE_WCSTOMBS) && defined(HAVE_TOWLOWER)
1089 #define USE_WIDE_UPPER_LOWER
1090 #endif
1091
1092 /* EXEC_BACKEND defines */
1093 #ifdef EXEC_BACKEND
1094 #define NON_EXEC_STATIC
1095 #else
1096 #define NON_EXEC_STATIC static
1097 #endif
1098
1099 /* /port compatibility functions */
1100 #include "port.h"
1101
1102 #endif   /* C_H */