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