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