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