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