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