]> granicus.if.org Git - postgresql/blob - src/include/c.h
Update copyright for 2015
[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[1];              /* VARIABLE LENGTH ARRAY */
428 } int2vector;                                   /* VARIABLE LENGTH STRUCT */
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[1];              /* VARIABLE LENGTH ARRAY */
439 } oidvector;                                    /* VARIABLE LENGTH STRUCT */
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
541 #define TYPEALIGN_DOWN(ALIGNVAL,LEN)  \
542         (((uintptr_t) (LEN)) & ~((uintptr_t) ((ALIGNVAL) - 1)))
543
544 #define SHORTALIGN_DOWN(LEN)    TYPEALIGN_DOWN(ALIGNOF_SHORT, (LEN))
545 #define INTALIGN_DOWN(LEN)              TYPEALIGN_DOWN(ALIGNOF_INT, (LEN))
546 #define LONGALIGN_DOWN(LEN)             TYPEALIGN_DOWN(ALIGNOF_LONG, (LEN))
547 #define DOUBLEALIGN_DOWN(LEN)   TYPEALIGN_DOWN(ALIGNOF_DOUBLE, (LEN))
548 #define MAXALIGN_DOWN(LEN)              TYPEALIGN_DOWN(MAXIMUM_ALIGNOF, (LEN))
549
550 /*
551  * The above macros will not work with types wider than uintptr_t, like with
552  * uint64 on 32-bit platforms.  That's not problem for the usual use where a
553  * pointer or a length is aligned, but for the odd case that you need to
554  * align something (potentially) wider, use TYPEALIGN64.
555  */
556 #define TYPEALIGN64(ALIGNVAL,LEN)  \
557         (((uint64) (LEN) + ((ALIGNVAL) - 1)) & ~((uint64) ((ALIGNVAL) - 1)))
558
559 /* we don't currently need wider versions of the other ALIGN macros */
560 #define MAXALIGN64(LEN)                 TYPEALIGN64(MAXIMUM_ALIGNOF, (LEN))
561
562 /* ----------------------------------------------------------------
563  *                              Section 6:      assertions
564  * ----------------------------------------------------------------
565  */
566
567 /*
568  * USE_ASSERT_CHECKING, if defined, turns on all the assertions.
569  * - plai  9/5/90
570  *
571  * It should _NOT_ be defined in releases or in benchmark copies
572  */
573
574 /*
575  * Assert() can be used in both frontend and backend code. In frontend code it
576  * just calls the standard assert, if it's available. If use of assertions is
577  * not configured, it does nothing.
578  */
579 #ifndef USE_ASSERT_CHECKING
580
581 #define Assert(condition)       ((void)true)
582 #define AssertMacro(condition)  ((void)true)
583 #define AssertArg(condition)    ((void)true)
584 #define AssertState(condition)  ((void)true)
585 #define AssertPointerAlignment(ptr, bndr)       ((void)true)
586 #define Trap(condition, errorType)      ((void)true)
587 #define TrapMacro(condition, errorType) (true)
588
589 #elif defined(FRONTEND)
590
591 #include <assert.h>
592 #define Assert(p) assert(p)
593 #define AssertMacro(p)  ((void) assert(p))
594 #define AssertArg(condition) assert(condition)
595 #define AssertState(condition) assert(condition)
596 #define AssertPointerAlignment(ptr, bndr)       ((void)true)
597 #else                                                   /* USE_ASSERT_CHECKING && !FRONTEND */
598
599 /*
600  * Trap
601  *              Generates an exception if the given condition is true.
602  */
603 #define Trap(condition, errorType) \
604         do { \
605                 if (condition) \
606                         ExceptionalCondition(CppAsString(condition), (errorType), \
607                                                                  __FILE__, __LINE__); \
608         } while (0)
609
610 /*
611  *      TrapMacro is the same as Trap but it's intended for use in macros:
612  *
613  *              #define foo(x) (AssertMacro(x != 0), bar(x))
614  *
615  *      Isn't CPP fun?
616  */
617 #define TrapMacro(condition, errorType) \
618         ((bool) (! (condition) || \
619                          (ExceptionalCondition(CppAsString(condition), (errorType), \
620                                                                    __FILE__, __LINE__), 0)))
621
622 #define Assert(condition) \
623                 Trap(!(condition), "FailedAssertion")
624
625 #define AssertMacro(condition) \
626                 ((void) TrapMacro(!(condition), "FailedAssertion"))
627
628 #define AssertArg(condition) \
629                 Trap(!(condition), "BadArgument")
630
631 #define AssertState(condition) \
632                 Trap(!(condition), "BadState")
633
634 /*
635  * Check that `ptr' is `bndr' aligned.
636  */
637 #define AssertPointerAlignment(ptr, bndr) \
638         Trap(TYPEALIGN(bndr, (uintptr_t)(ptr)) != (uintptr_t)(ptr), \
639                  "UnalignedPointer")
640
641 #endif   /* USE_ASSERT_CHECKING && !FRONTEND */
642
643 /*
644  * Macros to support compile-time assertion checks.
645  *
646  * If the "condition" (a compile-time-constant expression) evaluates to false,
647  * throw a compile error using the "errmessage" (a string literal).
648  *
649  * gcc 4.6 and up supports _Static_assert(), but there are bizarre syntactic
650  * placement restrictions.  These macros make it safe to use as a statement
651  * or in an expression, respectively.
652  *
653  * Otherwise we fall back on a kluge that assumes the compiler will complain
654  * about a negative width for a struct bit-field.  This will not include a
655  * helpful error message, but it beats not getting an error at all.
656  */
657 #ifdef HAVE__STATIC_ASSERT
658 #define StaticAssertStmt(condition, errmessage) \
659         do { _Static_assert(condition, errmessage); } while(0)
660 #define StaticAssertExpr(condition, errmessage) \
661         ({ StaticAssertStmt(condition, errmessage); true; })
662 #else                                                   /* !HAVE__STATIC_ASSERT */
663 #define StaticAssertStmt(condition, errmessage) \
664         ((void) sizeof(struct { int static_assert_failure : (condition) ? 1 : -1; }))
665 #define StaticAssertExpr(condition, errmessage) \
666         StaticAssertStmt(condition, errmessage)
667 #endif   /* HAVE__STATIC_ASSERT */
668
669
670 /*
671  * Compile-time checks that a variable (or expression) has the specified type.
672  *
673  * AssertVariableIsOfType() can be used as a statement.
674  * AssertVariableIsOfTypeMacro() is intended for use in macros, eg
675  *              #define foo(x) (AssertVariableIsOfTypeMacro(x, int), bar(x))
676  *
677  * If we don't have __builtin_types_compatible_p, we can still assert that
678  * the types have the same size.  This is far from ideal (especially on 32-bit
679  * platforms) but it provides at least some coverage.
680  */
681 #ifdef HAVE__BUILTIN_TYPES_COMPATIBLE_P
682 #define AssertVariableIsOfType(varname, typename) \
683         StaticAssertStmt(__builtin_types_compatible_p(__typeof__(varname), typename), \
684         CppAsString(varname) " does not have type " CppAsString(typename))
685 #define AssertVariableIsOfTypeMacro(varname, typename) \
686         ((void) StaticAssertExpr(__builtin_types_compatible_p(__typeof__(varname), typename), \
687          CppAsString(varname) " does not have type " CppAsString(typename)))
688 #else                                                   /* !HAVE__BUILTIN_TYPES_COMPATIBLE_P */
689 #define AssertVariableIsOfType(varname, typename) \
690         StaticAssertStmt(sizeof(varname) == sizeof(typename), \
691         CppAsString(varname) " does not have type " CppAsString(typename))
692 #define AssertVariableIsOfTypeMacro(varname, typename) \
693         ((void) StaticAssertExpr(sizeof(varname) == sizeof(typename),           \
694          CppAsString(varname) " does not have type " CppAsString(typename)))
695 #endif   /* HAVE__BUILTIN_TYPES_COMPATIBLE_P */
696
697
698 /* ----------------------------------------------------------------
699  *                              Section 7:      widely useful macros
700  * ----------------------------------------------------------------
701  */
702 /*
703  * Max
704  *              Return the maximum of two numbers.
705  */
706 #define Max(x, y)               ((x) > (y) ? (x) : (y))
707
708 /*
709  * Min
710  *              Return the minimum of two numbers.
711  */
712 #define Min(x, y)               ((x) < (y) ? (x) : (y))
713
714 /*
715  * Abs
716  *              Return the absolute value of the argument.
717  */
718 #define Abs(x)                  ((x) >= 0 ? (x) : -(x))
719
720 /*
721  * StrNCpy
722  *      Like standard library function strncpy(), except that result string
723  *      is guaranteed to be null-terminated --- that is, at most N-1 bytes
724  *      of the source string will be kept.
725  *      Also, the macro returns no result (too hard to do that without
726  *      evaluating the arguments multiple times, which seems worse).
727  *
728  *      BTW: when you need to copy a non-null-terminated string (like a text
729  *      datum) and add a null, do not do it with StrNCpy(..., len+1).  That
730  *      might seem to work, but it fetches one byte more than there is in the
731  *      text object.  One fine day you'll have a SIGSEGV because there isn't
732  *      another byte before the end of memory.  Don't laugh, we've had real
733  *      live bug reports from real live users over exactly this mistake.
734  *      Do it honestly with "memcpy(dst,src,len); dst[len] = '\0';", instead.
735  */
736 #define StrNCpy(dst,src,len) \
737         do \
738         { \
739                 char * _dst = (dst); \
740                 Size _len = (len); \
741 \
742                 if (_len > 0) \
743                 { \
744                         strncpy(_dst, (src), _len); \
745                         _dst[_len-1] = '\0'; \
746                 } \
747         } while (0)
748
749
750 /* Get a bit mask of the bits set in non-long aligned addresses */
751 #define LONG_ALIGN_MASK (sizeof(long) - 1)
752
753 /*
754  * MemSet
755  *      Exactly the same as standard library function memset(), but considerably
756  *      faster for zeroing small word-aligned structures (such as parsetree nodes).
757  *      This has to be a macro because the main point is to avoid function-call
758  *      overhead.   However, we have also found that the loop is faster than
759  *      native libc memset() on some platforms, even those with assembler
760  *      memset() functions.  More research needs to be done, perhaps with
761  *      MEMSET_LOOP_LIMIT tests in configure.
762  */
763 #define MemSet(start, val, len) \
764         do \
765         { \
766                 /* must be void* because we don't know if it is integer aligned yet */ \
767                 void   *_vstart = (void *) (start); \
768                 int             _val = (val); \
769                 Size    _len = (len); \
770 \
771                 if ((((uintptr_t) _vstart) & LONG_ALIGN_MASK) == 0 && \
772                         (_len & LONG_ALIGN_MASK) == 0 && \
773                         _val == 0 && \
774                         _len <= MEMSET_LOOP_LIMIT && \
775                         /* \
776                          *      If MEMSET_LOOP_LIMIT == 0, optimizer should find \
777                          *      the whole "if" false at compile time. \
778                          */ \
779                         MEMSET_LOOP_LIMIT != 0) \
780                 { \
781                         long *_start = (long *) _vstart; \
782                         long *_stop = (long *) ((char *) _start + _len); \
783                         while (_start < _stop) \
784                                 *_start++ = 0; \
785                 } \
786                 else \
787                         memset(_vstart, _val, _len); \
788         } while (0)
789
790 /*
791  * MemSetAligned is the same as MemSet except it omits the test to see if
792  * "start" is word-aligned.  This is okay to use if the caller knows a-priori
793  * that the pointer is suitably aligned (typically, because he just got it
794  * from palloc(), which always delivers a max-aligned pointer).
795  */
796 #define MemSetAligned(start, val, len) \
797         do \
798         { \
799                 long   *_start = (long *) (start); \
800                 int             _val = (val); \
801                 Size    _len = (len); \
802 \
803                 if ((_len & LONG_ALIGN_MASK) == 0 && \
804                         _val == 0 && \
805                         _len <= MEMSET_LOOP_LIMIT && \
806                         MEMSET_LOOP_LIMIT != 0) \
807                 { \
808                         long *_stop = (long *) ((char *) _start + _len); \
809                         while (_start < _stop) \
810                                 *_start++ = 0; \
811                 } \
812                 else \
813                         memset(_start, _val, _len); \
814         } while (0)
815
816
817 /*
818  * MemSetTest/MemSetLoop are a variant version that allow all the tests in
819  * MemSet to be done at compile time in cases where "val" and "len" are
820  * constants *and* we know the "start" pointer must be word-aligned.
821  * If MemSetTest succeeds, then it is okay to use MemSetLoop, otherwise use
822  * MemSetAligned.  Beware of multiple evaluations of the arguments when using
823  * this approach.
824  */
825 #define MemSetTest(val, len) \
826         ( ((len) & LONG_ALIGN_MASK) == 0 && \
827         (len) <= MEMSET_LOOP_LIMIT && \
828         MEMSET_LOOP_LIMIT != 0 && \
829         (val) == 0 )
830
831 #define MemSetLoop(start, val, len) \
832         do \
833         { \
834                 long * _start = (long *) (start); \
835                 long * _stop = (long *) ((char *) _start + (Size) (len)); \
836         \
837                 while (_start < _stop) \
838                         *_start++ = 0; \
839         } while (0)
840
841
842 /*
843  * Mark a point as unreachable in a portable fashion.  This should preferably
844  * be something that the compiler understands, to aid code generation.
845  * In assert-enabled builds, we prefer abort() for debugging reasons.
846  */
847 #if defined(HAVE__BUILTIN_UNREACHABLE) && !defined(USE_ASSERT_CHECKING)
848 #define pg_unreachable() __builtin_unreachable()
849 #elif defined(_MSC_VER) && !defined(USE_ASSERT_CHECKING)
850 #define pg_unreachable() __assume(0)
851 #else
852 #define pg_unreachable() abort()
853 #endif
854
855
856 /*
857  * Function inlining support -- Allow modules to define functions that may be
858  * inlined, if the compiler supports it.
859  *
860  * The function bodies must be defined in the module header prefixed by
861  * STATIC_IF_INLINE, protected by a cpp symbol that the module's .c file must
862  * define.  If the compiler doesn't support inline functions, the function
863  * definitions are pulled in by the .c file as regular (not inline) symbols.
864  *
865  * The header must also declare the functions' prototypes, protected by
866  * !PG_USE_INLINE.
867  */
868
869 /* declarations which are only visible when not inlining and in the .c file */
870 #ifdef PG_USE_INLINE
871 #define STATIC_IF_INLINE static inline
872 #else
873 #define STATIC_IF_INLINE
874 #endif   /* PG_USE_INLINE */
875
876 /* declarations which are marked inline when inlining, extern otherwise */
877 #ifdef PG_USE_INLINE
878 #define STATIC_IF_INLINE_DECLARE static inline
879 #else
880 #define STATIC_IF_INLINE_DECLARE extern
881 #endif   /* PG_USE_INLINE */
882
883
884 /* ----------------------------------------------------------------
885  *                              Section 8:      random stuff
886  * ----------------------------------------------------------------
887  */
888
889 /* msb for char */
890 #define HIGHBIT                                 (0x80)
891 #define IS_HIGHBIT_SET(ch)              ((unsigned char)(ch) & HIGHBIT)
892
893 #define STATUS_OK                               (0)
894 #define STATUS_ERROR                    (-1)
895 #define STATUS_EOF                              (-2)
896 #define STATUS_FOUND                    (1)
897 #define STATUS_WAITING                  (2)
898
899
900 /*
901  * Append PG_USED_FOR_ASSERTS_ONLY to definitions of variables that are only
902  * used in assert-enabled builds, to avoid compiler warnings about unused
903  * variables in assert-disabled builds.
904  */
905 #ifdef USE_ASSERT_CHECKING
906 #define PG_USED_FOR_ASSERTS_ONLY
907 #else
908 #define PG_USED_FOR_ASSERTS_ONLY __attribute__((unused))
909 #endif
910
911
912 /* gettext domain name mangling */
913
914 /*
915  * To better support parallel installations of major PostgeSQL
916  * versions as well as parallel installations of major library soname
917  * versions, we mangle the gettext domain name by appending those
918  * version numbers.  The coding rule ought to be that whereever the
919  * domain name is mentioned as a literal, it must be wrapped into
920  * PG_TEXTDOMAIN().  The macros below do not work on non-literals; but
921  * that is somewhat intentional because it avoids having to worry
922  * about multiple states of premangling and postmangling as the values
923  * are being passed around.
924  *
925  * Make sure this matches the installation rules in nls-global.mk.
926  */
927
928 /* need a second indirection because we want to stringize the macro value, not the name */
929 #define CppAsString2(x) CppAsString(x)
930
931 #ifdef SO_MAJOR_VERSION
932 #define PG_TEXTDOMAIN(domain) (domain CppAsString2(SO_MAJOR_VERSION) "-" PG_MAJORVERSION)
933 #else
934 #define PG_TEXTDOMAIN(domain) (domain "-" PG_MAJORVERSION)
935 #endif
936
937
938 /* ----------------------------------------------------------------
939  *                              Section 9: system-specific hacks
940  *
941  *              This should be limited to things that absolutely have to be
942  *              included in every source file.  The port-specific header file
943  *              is usually a better place for this sort of thing.
944  * ----------------------------------------------------------------
945  */
946
947 /*
948  *      NOTE:  this is also used for opening text files.
949  *      WIN32 treats Control-Z as EOF in files opened in text mode.
950  *      Therefore, we open files in binary mode on Win32 so we can read
951  *      literal control-Z.  The other affect is that we see CRLF, but
952  *      that is OK because we can already handle those cleanly.
953  */
954 #if defined(WIN32) || defined(__CYGWIN__)
955 #define PG_BINARY       O_BINARY
956 #define PG_BINARY_A "ab"
957 #define PG_BINARY_R "rb"
958 #define PG_BINARY_W "wb"
959 #else
960 #define PG_BINARY       0
961 #define PG_BINARY_A "a"
962 #define PG_BINARY_R "r"
963 #define PG_BINARY_W "w"
964 #endif
965
966 /*
967  * Provide prototypes for routines not present in a particular machine's
968  * standard C library.
969  */
970
971 #if !HAVE_DECL_SNPRINTF
972 extern int
973 snprintf(char *str, size_t count, const char *fmt,...)
974 /* This extension allows gcc to check the format string */
975 __attribute__((format(PG_PRINTF_ATTRIBUTE, 3, 4)));
976 #endif
977
978 #if !HAVE_DECL_VSNPRINTF
979 extern int      vsnprintf(char *str, size_t count, const char *fmt, va_list args);
980 #endif
981
982 #if !defined(HAVE_MEMMOVE) && !defined(memmove)
983 #define memmove(d, s, c)                bcopy(s, d, c)
984 #endif
985
986 /* no special DLL markers on most ports */
987 #ifndef PGDLLIMPORT
988 #define PGDLLIMPORT
989 #endif
990 #ifndef PGDLLEXPORT
991 #define PGDLLEXPORT
992 #endif
993
994 /*
995  * The following is used as the arg list for signal handlers.  Any ports
996  * that take something other than an int argument should override this in
997  * their pg_config_os.h file.  Note that variable names are required
998  * because it is used in both the prototypes as well as the definitions.
999  * Note also the long name.  We expect that this won't collide with
1000  * other names causing compiler warnings.
1001  */
1002
1003 #ifndef SIGNAL_ARGS
1004 #define SIGNAL_ARGS  int postgres_signal_arg
1005 #endif
1006
1007 /*
1008  * When there is no sigsetjmp, its functionality is provided by plain
1009  * setjmp. Incidentally, nothing provides setjmp's functionality in
1010  * that case.
1011  */
1012 #ifndef HAVE_SIGSETJMP
1013 #define sigjmp_buf jmp_buf
1014 #define sigsetjmp(x,y) setjmp(x)
1015 #define siglongjmp longjmp
1016 #endif
1017
1018 #if defined(HAVE_FDATASYNC) && !HAVE_DECL_FDATASYNC
1019 extern int      fdatasync(int fildes);
1020 #endif
1021
1022 /* If strtoq() exists, rename it to the more standard strtoll() */
1023 #if defined(HAVE_LONG_LONG_INT_64) && !defined(HAVE_STRTOLL) && defined(HAVE_STRTOQ)
1024 #define strtoll strtoq
1025 #define HAVE_STRTOLL 1
1026 #endif
1027
1028 /* If strtouq() exists, rename it to the more standard strtoull() */
1029 #if defined(HAVE_LONG_LONG_INT_64) && !defined(HAVE_STRTOULL) && defined(HAVE_STRTOUQ)
1030 #define strtoull strtouq
1031 #define HAVE_STRTOULL 1
1032 #endif
1033
1034 /*
1035  * We assume if we have these two functions, we have their friends too, and
1036  * can use the wide-character functions.
1037  */
1038 #if defined(HAVE_WCSTOMBS) && defined(HAVE_TOWLOWER)
1039 #define USE_WIDE_UPPER_LOWER
1040 #endif
1041
1042 /* EXEC_BACKEND defines */
1043 #ifdef EXEC_BACKEND
1044 #define NON_EXEC_STATIC
1045 #else
1046 #define NON_EXEC_STATIC static
1047 #endif
1048
1049 /* /port compatibility functions */
1050 #include "port.h"
1051
1052 #endif   /* C_H */