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