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