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