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