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