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