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-2019, 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) compiler characteristics
30 * 2) bool, true, false
31 * 3) standard system types
32 * 4) IsValid macros for system types
33 * 5) offsetof, lengthof, 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,
40 * it's usually wrong to put an "extern" declaration here, unless it's
41 * ifdef'd so that it's seen in only one case or the other.
42 * typedefs and macros are the kind of thing that might go here.
43 *
44 *----------------------------------------------------------------
45 */
46#ifndef C_H
47#define C_H
48
49#include "postgres_ext.h"
50
51/* Must undef pg_config_ext.h symbols before including pg_config.h */
52#undef PG_INT64_TYPE
53
54#include "pg_config.h"
55#include "pg_config_manual.h" /* must be after pg_config.h */
56#include "pg_config_os.h" /* must be before any system header files */
57
58/* System header files that should be available everywhere in Postgres */
59#include <stdio.h>
60#include <stdlib.h>
61#include <string.h>
62#include <stddef.h>
63#include <stdarg.h>
64#ifdef HAVE_STRINGS_H
65#include <strings.h>
66#endif
67#ifdef HAVE_STDINT_H
68#include <stdint.h>
69#endif
70#include <sys/types.h>
71#include <errno.h>
72#if defined(WIN32) || defined(__CYGWIN__)
73#include <fcntl.h> /* ensure O_BINARY is available */
74#endif
75#include <locale.h>
76#ifdef ENABLE_NLS
77#include <libintl.h>
78#endif
79
80
81/* ----------------------------------------------------------------
82 * Section 1: compiler characteristics
83 *
84 * type prefixes (const, signed, volatile, inline) are handled in pg_config.h.
85 * ----------------------------------------------------------------
86 */
87
88/*
89 * Disable "inline" if PG_FORCE_DISABLE_INLINE is defined.
90 * This is used to work around compiler bugs and might also be useful for
91 * investigatory purposes.
92 */
93#ifdef PG_FORCE_DISABLE_INLINE
94#undef inline
95#define inline
96#endif
97
98/*
99 * Attribute macros
100 *
101 * GCC: https://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
102 * GCC: https://gcc.gnu.org/onlinedocs/gcc/Type-Attributes.html
103 * Sunpro: https://docs.oracle.com/cd/E18659_01/html/821-1384/gjzke.html
104 * XLC: http://www-01.ibm.com/support/knowledgecenter/SSGH2K_11.1.0/com.ibm.xlc111.aix.doc/language_ref/function_attributes.html
105 * XLC: http://www-01.ibm.com/support/knowledgecenter/SSGH2K_11.1.0/com.ibm.xlc111.aix.doc/language_ref/type_attrib.html
106 */
107
108/* only GCC supports the unused attribute */
109#ifdef __GNUC__
110#define pg_attribute_unused() __attribute__((unused))
111#else
112#define pg_attribute_unused()
113#endif
114
115/*
116 * Append PG_USED_FOR_ASSERTS_ONLY to definitions of variables that are only
117 * used in assert-enabled builds, to avoid compiler warnings about unused
118 * variables in assert-disabled builds.
119 */
120#ifdef USE_ASSERT_CHECKING
121#define PG_USED_FOR_ASSERTS_ONLY
122#else
123#define PG_USED_FOR_ASSERTS_ONLY pg_attribute_unused()
124#endif
125
126/* GCC and XLC support format attributes */
127#if defined(__GNUC__) || defined(__IBMC__)
128#define pg_attribute_format_arg(a) __attribute__((format_arg(a)))
129#define pg_attribute_printf(f,a) __attribute__((format(PG_PRINTF_ATTRIBUTE, f, a)))
130#else
131#define pg_attribute_format_arg(a)
132#define pg_attribute_printf(f,a)
133#endif
134
135/* GCC, Sunpro and XLC support aligned, packed and noreturn */
136#if defined(__GNUC__) || defined(__SUNPRO_C) || defined(__IBMC__)
137#define pg_attribute_aligned(a) __attribute__((aligned(a)))
138#define pg_attribute_noreturn() __attribute__((noreturn))
139#define pg_attribute_packed() __attribute__((packed))
140#define HAVE_PG_ATTRIBUTE_NORETURN 1
141#else
142/*
143 * NB: aligned and packed are not given default definitions because they
144 * affect code functionality; they *must* be implemented by the compiler
145 * if they are to be used.
146 */
147#define pg_attribute_noreturn()
148#endif
149
150/*
151 * Use "pg_attribute_always_inline" in place of "inline" for functions that
152 * we wish to force inlining of, even when the compiler's heuristics would
153 * choose not to. But, if possible, don't force inlining in unoptimized
154 * debug builds.
155 */
156#if (defined(__GNUC__) && __GNUC__ > 3 && defined(__OPTIMIZE__)) || defined(__SUNPRO_C) || defined(__IBMC__)
157/* GCC > 3, Sunpro and XLC support always_inline via __attribute__ */
158#define pg_attribute_always_inline __attribute__((always_inline)) inline
159#elif defined(_MSC_VER)
160/* MSVC has a special keyword for this */
161#define pg_attribute_always_inline __forceinline
162#else
163/* Otherwise, the best we can do is to say "inline" */
164#define pg_attribute_always_inline inline
165#endif
166
167/*
168 * Forcing a function not to be inlined can be useful if it's the slow path of
169 * a performance-critical function, or should be visible in profiles to allow
170 * for proper cost attribution. Note that unlike the pg_attribute_XXX macros
171 * above, this should be placed before the function's return type and name.
172 */
173/* GCC, Sunpro and XLC support noinline via __attribute__ */
174#if (defined(__GNUC__) && __GNUC__ > 2) || defined(__SUNPRO_C) || defined(__IBMC__)
175#define pg_noinline __attribute__((noinline))
176/* msvc via declspec */
177#elif defined(_MSC_VER)
178#define pg_noinline __declspec(noinline)
179#else
180#define pg_noinline
181#endif
182
183/*
184 * Mark a point as unreachable in a portable fashion. This should preferably
185 * be something that the compiler understands, to aid code generation.
186 * In assert-enabled builds, we prefer abort() for debugging reasons.
187 */
188#if defined(HAVE__BUILTIN_UNREACHABLE) && !defined(USE_ASSERT_CHECKING)
189#define pg_unreachable() __builtin_unreachable()
190#elif defined(_MSC_VER) && !defined(USE_ASSERT_CHECKING)
191#define pg_unreachable() __assume(0)
192#else
193#define pg_unreachable() abort()
194#endif
195
196/*
197 * Hints to the compiler about the likelihood of a branch. Both likely() and
198 * unlikely() return the boolean value of the contained expression.
199 *
200 * These should only be used sparingly, in very hot code paths. It's very easy
201 * to mis-estimate likelihoods.
202 */
203#if __GNUC__ >= 3
204#define likely(x) __builtin_expect((x) != 0, 1)
205#define unlikely(x) __builtin_expect((x) != 0, 0)
206#else
207#define likely(x) ((x) != 0)
208#define unlikely(x) ((x) != 0)
209#endif
210
211/*
212 * CppAsString
213 * Convert the argument to a string, using the C preprocessor.
214 * CppAsString2
215 * Convert the argument to a string, after one round of macro expansion.
216 * CppConcat
217 * Concatenate two arguments together, using the C preprocessor.
218 *
219 * Note: There used to be support here for pre-ANSI C compilers that didn't
220 * support # and ##. Nowadays, these macros are just for clarity and/or
221 * backward compatibility with existing PostgreSQL code.
222 */
223#define CppAsString(identifier) #identifier
224#define CppAsString2(x) CppAsString(x)
225#define CppConcat(x, y) x##y
226
227/*
228 * VA_ARGS_NARGS
229 * Returns the number of macro arguments it is passed.
230 *
231 * An empty argument still counts as an argument, so effectively, this is
232 * "one more than the number of commas in the argument list".
233 *
234 * This works for up to 63 arguments. Internally, VA_ARGS_NARGS_() is passed
235 * 64+N arguments, and the C99 standard only requires macros to allow up to
236 * 127 arguments, so we can't portably go higher. The implementation is
237 * pretty trivial: VA_ARGS_NARGS_() returns its 64th argument, and we set up
238 * the call so that that is the appropriate one of the list of constants.
239 * This idea is due to Laurent Deniau.
240 */
241#define VA_ARGS_NARGS(...) \
242 VA_ARGS_NARGS_(__VA_ARGS__, \
243 63,62,61,60, \
244 59,58,57,56,55,54,53,52,51,50, \
245 49,48,47,46,45,44,43,42,41,40, \
246 39,38,37,36,35,34,33,32,31,30, \
247 29,28,27,26,25,24,23,22,21,20, \
248 19,18,17,16,15,14,13,12,11,10, \
249 9, 8, 7, 6, 5, 4, 3, 2, 1, 0)
250#define VA_ARGS_NARGS_( \
251 _01,_02,_03,_04,_05,_06,_07,_08,_09,_10, \
252 _11,_12,_13,_14,_15,_16,_17,_18,_19,_20, \
253 _21,_22,_23,_24,_25,_26,_27,_28,_29,_30, \
254 _31,_32,_33,_34,_35,_36,_37,_38,_39,_40, \
255 _41,_42,_43,_44,_45,_46,_47,_48,_49,_50, \
256 _51,_52,_53,_54,_55,_56,_57,_58,_59,_60, \
257 _61,_62,_63, N, ...) \
258 (N)
259
260/*
261 * dummyret is used to set return values in macros that use ?: to make
262 * assignments. gcc wants these to be void, other compilers like char
263 */
264#ifdef __GNUC__ /* GNU cc */
265#define dummyret void
266#else
267#define dummyret char
268#endif
269
270/* Which __func__ symbol do we have, if any? */
271#ifdef HAVE_FUNCNAME__FUNC
272#define PG_FUNCNAME_MACRO __func__
273#else
274#ifdef HAVE_FUNCNAME__FUNCTION
275#define PG_FUNCNAME_MACRO __FUNCTION__
276#else
277#define PG_FUNCNAME_MACRO NULL
278#endif
279#endif
280
281
282/* ----------------------------------------------------------------
283 * Section 2: bool, true, false
284 * ----------------------------------------------------------------
285 */
286
287/*
288 * bool
289 * Boolean value, either true or false.
290 *
291 * Use stdbool.h if available and its bool has size 1. That's useful for
292 * better compiler and debugger output and for compatibility with third-party
293 * libraries. But PostgreSQL currently cannot deal with bool of other sizes;
294 * there are static assertions around the code to prevent that.
295 *
296 * For C++ compilers, we assume the compiler has a compatible built-in
297 * definition of bool.
298 */
299
300#ifndef __cplusplus
301
302#if defined(HAVE_STDBOOL_H) && SIZEOF_BOOL == 1
303#include <stdbool.h>
304#define USE_STDBOOL 1
305#else
306
307#ifndef bool
308typedef unsigned char bool;
309#endif
310
311#ifndef true
312#define true ((bool) 1)
313#endif
314
315#ifndef false
316#define false ((bool) 0)
317#endif
318
319#endif
320#endif /* not C++ */
321
322
323/* ----------------------------------------------------------------
324 * Section 3: standard system types
325 * ----------------------------------------------------------------
326 */
327
328/*
329 * Pointer
330 * Variable holding address of any memory resident object.
331 *
332 * XXX Pointer arithmetic is done with this, so it can't be void *
333 * under "true" ANSI compilers.
334 */
335typedef char *Pointer;
336
337/*
338 * intN
339 * Signed integer, EXACTLY N BITS IN SIZE,
340 * used for numerical computations and the
341 * frontend/backend protocol.
342 */
343#ifndef HAVE_INT8
344typedef signed char int8; /* == 8 bits */
345typedef signed short int16; /* == 16 bits */
346typedef signed int int32; /* == 32 bits */
347#endif /* not HAVE_INT8 */
348
349/*
350 * uintN
351 * Unsigned integer, EXACTLY N BITS IN SIZE,
352 * used for numerical computations and the
353 * frontend/backend protocol.
354 */
355#ifndef HAVE_UINT8
356typedef unsigned char uint8; /* == 8 bits */
357typedef unsigned short uint16; /* == 16 bits */
358typedef unsigned int uint32; /* == 32 bits */
359#endif /* not HAVE_UINT8 */
360
361/*
362 * bitsN
363 * Unit of bitwise operation, AT LEAST N BITS IN SIZE.
364 */
365typedef uint8 bits8; /* >= 8 bits */
366typedef uint16 bits16; /* >= 16 bits */
367typedef uint32 bits32; /* >= 32 bits */
368
369/*
370 * 64-bit integers
371 */
372#ifdef HAVE_LONG_INT_64
373/* Plain "long int" fits, use it */
374
375#ifndef HAVE_INT64
376typedef long int int64;
377#endif
378#ifndef HAVE_UINT64
379typedef unsigned long int uint64;
380#endif
381#define INT64CONST(x) (x##L)
382#define UINT64CONST(x) (x##UL)
383#elif defined(HAVE_LONG_LONG_INT_64)
384/* We have working support for "long long int", use that */
385
386#ifndef HAVE_INT64
387typedef long long int int64;
388#endif
389#ifndef HAVE_UINT64
390typedef unsigned long long int uint64;
391#endif
392#define INT64CONST(x) (x##LL)
393#define UINT64CONST(x) (x##ULL)
394#else
395/* neither HAVE_LONG_INT_64 nor HAVE_LONG_LONG_INT_64 */
396#error must have a working 64-bit integer datatype
397#endif
398
399/* snprintf format strings to use for 64-bit integers */
400#define INT64_FORMAT "%" INT64_MODIFIER "d"
401#define UINT64_FORMAT "%" INT64_MODIFIER "u"
402
403/*
404 * 128-bit signed and unsigned integers
405 * There currently is only limited support for such types.
406 * E.g. 128bit literals and snprintf are not supported; but math is.
407 * Also, because we exclude such types when choosing MAXIMUM_ALIGNOF,
408 * it must be possible to coerce the compiler to allocate them on no
409 * more than MAXALIGN boundaries.
410 */
411#if defined(PG_INT128_TYPE)
412#if defined(pg_attribute_aligned) || ALIGNOF_PG_INT128_TYPE <= MAXIMUM_ALIGNOF
413#define HAVE_INT128 1
414
415typedef PG_INT128_TYPE int128
416#if defined(pg_attribute_aligned)
417 pg_attribute_aligned(MAXIMUM_ALIGNOF)
418#endif
419 ;
420
421typedef unsigned PG_INT128_TYPE uint128
422#if defined(pg_attribute_aligned)
423 pg_attribute_aligned(MAXIMUM_ALIGNOF)
424#endif
425 ;
426
427#endif
428#endif
429
430/*
431 * stdint.h limits aren't guaranteed to be present and aren't guaranteed to
432 * have compatible types with our fixed width types. So just define our own.
433 */
434#define PG_INT8_MIN (-0x7F-1)
435#define PG_INT8_MAX (0x7F)
436#define PG_UINT8_MAX (0xFF)
437#define PG_INT16_MIN (-0x7FFF-1)
438#define PG_INT16_MAX (0x7FFF)
439#define PG_UINT16_MAX (0xFFFF)
440#define PG_INT32_MIN (-0x7FFFFFFF-1)
441#define PG_INT32_MAX (0x7FFFFFFF)
442#define PG_UINT32_MAX (0xFFFFFFFFU)
443#define PG_INT64_MIN (-INT64CONST(0x7FFFFFFFFFFFFFFF) - 1)
444#define PG_INT64_MAX INT64CONST(0x7FFFFFFFFFFFFFFF)
445#define PG_UINT64_MAX UINT64CONST(0xFFFFFFFFFFFFFFFF)
446
447/* Max value of size_t might also be missing if we don't have stdint.h */
448#ifndef SIZE_MAX
449#if SIZEOF_SIZE_T == 8
450#define SIZE_MAX PG_UINT64_MAX
451#else
452#define SIZE_MAX PG_UINT32_MAX
453#endif
454#endif
455
456/*
457 * We now always use int64 timestamps, but keep this symbol defined for the
458 * benefit of external code that might test it.
459 */
460#define HAVE_INT64_TIMESTAMP
461
462/*
463 * Size
464 * Size of any memory resident object, as returned by sizeof.
465 */
466typedef size_t Size;
467
468/*
469 * Index
470 * Index into any memory resident array.
471 *
472 * Note:
473 * Indices are non negative.
474 */
475typedef unsigned int Index;
476
477/*
478 * Offset
479 * Offset into any memory resident array.
480 *
481 * Note:
482 * This differs from an Index in that an Index is always
483 * non negative, whereas Offset may be negative.
484 */
485typedef signed int Offset;
486
487/*
488 * Common Postgres datatype names (as used in the catalogs)
489 */
490typedef float float4;
491typedef double float8;
492
493/*
494 * Oid, RegProcedure, TransactionId, SubTransactionId, MultiXactId,
495 * CommandId
496 */
497
498/* typedef Oid is in postgres_ext.h */
499
500/*
501 * regproc is the type name used in the include/catalog headers, but
502 * RegProcedure is the preferred name in C code.
503 */
504typedef Oid regproc;
505typedef regproc RegProcedure;
506
507typedef uint32 TransactionId;
508
509typedef uint32 LocalTransactionId;
510
511typedef uint32 SubTransactionId;
512
513#define InvalidSubTransactionId ((SubTransactionId) 0)
514#define TopSubTransactionId ((SubTransactionId) 1)
515
516/* MultiXactId must be equivalent to TransactionId, to fit in t_xmax */
517typedef TransactionId MultiXactId;
518
519typedef uint32 MultiXactOffset;
520
521typedef uint32 CommandId;
522
523#define FirstCommandId ((CommandId) 0)
524#define InvalidCommandId (~(CommandId)0)
525
526/*
527 * Array indexing support
528 */
529#define MAXDIM 6
530typedef struct
531{
532 int indx[MAXDIM];
533} IntArray;
534
535/* ----------------
536 * Variable-length datatypes all share the 'struct varlena' header.
537 *
538 * NOTE: for TOASTable types, this is an oversimplification, since the value
539 * may be compressed or moved out-of-line. However datatype-specific routines
540 * are mostly content to deal with de-TOASTed values only, and of course
541 * client-side routines should never see a TOASTed value. But even in a
542 * de-TOASTed value, beware of touching vl_len_ directly, as its
543 * representation is no longer convenient. It's recommended that code always
544 * use macros VARDATA_ANY, VARSIZE_ANY, VARSIZE_ANY_EXHDR, VARDATA, VARSIZE,
545 * and SET_VARSIZE instead of relying on direct mentions of the struct fields.
546 * See postgres.h for details of the TOASTed form.
547 * ----------------
548 */
549struct varlena
550{
551 char vl_len_[4]; /* Do not touch this field directly! */
552 char vl_dat[FLEXIBLE_ARRAY_MEMBER]; /* Data content is here */
553};
554
555#define VARHDRSZ ((int32) sizeof(int32))
556
557/*
558 * These widely-used datatypes are just a varlena header and the data bytes.
559 * There is no terminating null or anything like that --- the data length is
560 * always VARSIZE_ANY_EXHDR(ptr).
561 */
562typedef struct varlena bytea;
563typedef struct varlena text;
564typedef struct varlena BpChar; /* blank-padded char, ie SQL char(n) */
565typedef struct varlena VarChar; /* var-length char, ie SQL varchar(n) */
566
567/*
568 * Specialized array types. These are physically laid out just the same
569 * as regular arrays (so that the regular array subscripting code works
570 * with them). They exist as distinct types mostly for historical reasons:
571 * they have nonstandard I/O behavior which we don't want to change for fear
572 * of breaking applications that look at the system catalogs. There is also
573 * an implementation issue for oidvector: it's part of the primary key for
574 * pg_proc, and we can't use the normal btree array support routines for that
575 * without circularity.
576 */
577typedef struct
578{
579 int32 vl_len_; /* these fields must match ArrayType! */
580 int ndim; /* always 1 for int2vector */
581 int32 dataoffset; /* always 0 for int2vector */
582 Oid elemtype;
583 int dim1;
584 int lbound1;
585 int16 values[FLEXIBLE_ARRAY_MEMBER];
586} int2vector;
587
588typedef struct
589{
590 int32 vl_len_; /* these fields must match ArrayType! */
591 int ndim; /* always 1 for oidvector */
592 int32 dataoffset; /* always 0 for oidvector */
593 Oid elemtype;
594 int dim1;
595 int lbound1;
596 Oid values[FLEXIBLE_ARRAY_MEMBER];
597} oidvector;
598
599/*
600 * Representation of a Name: effectively just a C string, but null-padded to
601 * exactly NAMEDATALEN bytes. The use of a struct is historical.
602 */
603typedef struct nameData
604{
605 char data[NAMEDATALEN];
606} NameData;
607typedef NameData *Name;
608
609#define NameStr(name) ((name).data)
610
611
612/* ----------------------------------------------------------------
613 * Section 4: IsValid macros for system types
614 * ----------------------------------------------------------------
615 */
616/*
617 * BoolIsValid
618 * True iff bool is valid.
619 */
620#define BoolIsValid(boolean) ((boolean) == false || (boolean) == true)
621
622/*
623 * PointerIsValid
624 * True iff pointer is valid.
625 */
626#define PointerIsValid(pointer) ((const void*)(pointer) != NULL)
627
628/*
629 * PointerIsAligned
630 * True iff pointer is properly aligned to point to the given type.
631 */
632#define PointerIsAligned(pointer, type) \
633 (((uintptr_t)(pointer) % (sizeof (type))) == 0)
634
635#define OffsetToPointer(base, offset) \
636 ((void *)((char *) base + offset))
637
638#define OidIsValid(objectId) ((bool) ((objectId) != InvalidOid))
639
640#define RegProcedureIsValid(p) OidIsValid(p)
641
642
643/* ----------------------------------------------------------------
644 * Section 5: offsetof, lengthof, alignment
645 * ----------------------------------------------------------------
646 */
647/*
648 * offsetof
649 * Offset of a structure/union field within that structure/union.
650 *
651 * XXX This is supposed to be part of stddef.h, but isn't on
652 * some systems (like SunOS 4).
653 */
654#ifndef offsetof
655#define offsetof(type, field) ((long) &((type *)0)->field)
656#endif /* offsetof */
657
658/*
659 * lengthof
660 * Number of elements in an array.
661 */
662#define lengthof(array) (sizeof (array) / sizeof ((array)[0]))
663
664/* ----------------
665 * Alignment macros: align a length or address appropriately for a given type.
666 * The fooALIGN() macros round up to a multiple of the required alignment,
667 * while the fooALIGN_DOWN() macros round down. The latter are more useful
668 * for problems like "how many X-sized structures will fit in a page?".
669 *
670 * NOTE: TYPEALIGN[_DOWN] will not work if ALIGNVAL is not a power of 2.
671 * That case seems extremely unlikely to be needed in practice, however.
672 *
673 * NOTE: MAXIMUM_ALIGNOF, and hence MAXALIGN(), intentionally exclude any
674 * larger-than-8-byte types the compiler might have.
675 * ----------------
676 */
677
678#define TYPEALIGN(ALIGNVAL,LEN) \
679 (((uintptr_t) (LEN) + ((ALIGNVAL) - 1)) & ~((uintptr_t) ((ALIGNVAL) - 1)))
680
681#define SHORTALIGN(LEN) TYPEALIGN(ALIGNOF_SHORT, (LEN))
682#define INTALIGN(LEN) TYPEALIGN(ALIGNOF_INT, (LEN))
683#define LONGALIGN(LEN) TYPEALIGN(ALIGNOF_LONG, (LEN))
684#define DOUBLEALIGN(LEN) TYPEALIGN(ALIGNOF_DOUBLE, (LEN))
685#define MAXALIGN(LEN) TYPEALIGN(MAXIMUM_ALIGNOF, (LEN))
686/* MAXALIGN covers only built-in types, not buffers */
687#define BUFFERALIGN(LEN) TYPEALIGN(ALIGNOF_BUFFER, (LEN))
688#define CACHELINEALIGN(LEN) TYPEALIGN(PG_CACHE_LINE_SIZE, (LEN))
689
690#define TYPEALIGN_DOWN(ALIGNVAL,LEN) \
691 (((uintptr_t) (LEN)) & ~((uintptr_t) ((ALIGNVAL) - 1)))
692
693#define SHORTALIGN_DOWN(LEN) TYPEALIGN_DOWN(ALIGNOF_SHORT, (LEN))
694#define INTALIGN_DOWN(LEN) TYPEALIGN_DOWN(ALIGNOF_INT, (LEN))
695#define LONGALIGN_DOWN(LEN) TYPEALIGN_DOWN(ALIGNOF_LONG, (LEN))
696#define DOUBLEALIGN_DOWN(LEN) TYPEALIGN_DOWN(ALIGNOF_DOUBLE, (LEN))
697#define MAXALIGN_DOWN(LEN) TYPEALIGN_DOWN(MAXIMUM_ALIGNOF, (LEN))
698#define BUFFERALIGN_DOWN(LEN) TYPEALIGN_DOWN(ALIGNOF_BUFFER, (LEN))
699
700/*
701 * The above macros will not work with types wider than uintptr_t, like with
702 * uint64 on 32-bit platforms. That's not problem for the usual use where a
703 * pointer or a length is aligned, but for the odd case that you need to
704 * align something (potentially) wider, use TYPEALIGN64.
705 */
706#define TYPEALIGN64(ALIGNVAL,LEN) \
707 (((uint64) (LEN) + ((ALIGNVAL) - 1)) & ~((uint64) ((ALIGNVAL) - 1)))
708
709/* we don't currently need wider versions of the other ALIGN macros */
710#define MAXALIGN64(LEN) TYPEALIGN64(MAXIMUM_ALIGNOF, (LEN))
711
712
713/* ----------------------------------------------------------------
714 * Section 6: assertions
715 * ----------------------------------------------------------------
716 */
717
718/*
719 * USE_ASSERT_CHECKING, if defined, turns on all the assertions.
720 * - plai 9/5/90
721 *
722 * It should _NOT_ be defined in releases or in benchmark copies
723 */
724
725/*
726 * Assert() can be used in both frontend and backend code. In frontend code it
727 * just calls the standard assert, if it's available. If use of assertions is
728 * not configured, it does nothing.
729 */
730#ifndef USE_ASSERT_CHECKING
731
732#define Assert(condition) ((void)true)
733#define AssertMacro(condition) ((void)true)
734#define AssertArg(condition) ((void)true)
735#define AssertState(condition) ((void)true)
736#define AssertPointerAlignment(ptr, bndr) ((void)true)
737#define Trap(condition, errorType) ((void)true)
738#define TrapMacro(condition, errorType) (true)
739
740#elif defined(FRONTEND)
741
742#include <assert.h>
743#define Assert(p) assert(p)
744#define AssertMacro(p) ((void) assert(p))
745#define AssertArg(condition) assert(condition)
746#define AssertState(condition) assert(condition)
747#define AssertPointerAlignment(ptr, bndr) ((void)true)
748
749#else /* USE_ASSERT_CHECKING && !FRONTEND */
750
751/*
752 * Trap
753 * Generates an exception if the given condition is true.
754 */
755#define Trap(condition, errorType) \
756 do { \
757 if (condition) \
758 ExceptionalCondition(CppAsString(condition), (errorType), \
759 __FILE__, __LINE__); \
760 } while (0)
761
762/*
763 * TrapMacro is the same as Trap but it's intended for use in macros:
764 *
765 * #define foo(x) (AssertMacro(x != 0), bar(x))
766 *
767 * Isn't CPP fun?
768 */
769#define TrapMacro(condition, errorType) \
770 ((bool) (! (condition) || \
771 (ExceptionalCondition(CppAsString(condition), (errorType), \
772 __FILE__, __LINE__), 0)))
773
774#define Assert(condition) \
775 Trap(!(condition), "FailedAssertion")
776
777#define AssertMacro(condition) \
778 ((void) TrapMacro(!(condition), "FailedAssertion"))
779
780#define AssertArg(condition) \
781 Trap(!(condition), "BadArgument")
782
783#define AssertState(condition) \
784 Trap(!(condition), "BadState")
785
786/*
787 * Check that `ptr' is `bndr' aligned.
788 */
789#define AssertPointerAlignment(ptr, bndr) \
790 Trap(TYPEALIGN(bndr, (uintptr_t)(ptr)) != (uintptr_t)(ptr), \
791 "UnalignedPointer")
792
793#endif /* USE_ASSERT_CHECKING && !FRONTEND */
794
795/*
796 * ExceptionalCondition is compiled into the backend whether or not
797 * USE_ASSERT_CHECKING is defined, so as to support use of extensions
798 * that are built with that #define with a backend that isn't. Hence,
799 * we should declare it as long as !FRONTEND.
800 */
801#ifndef FRONTEND
802extern void ExceptionalCondition(const char *conditionName,
803 const char *errorType,
804 const char *fileName, int lineNumber) pg_attribute_noreturn();
805#endif
806
807/*
808 * Macros to support compile-time assertion checks.
809 *
810 * If the "condition" (a compile-time-constant expression) evaluates to false,
811 * throw a compile error using the "errmessage" (a string literal).
812 *
813 * gcc 4.6 and up supports _Static_assert(), but there are bizarre syntactic
814 * placement restrictions. These macros make it safe to use as a statement
815 * or in an expression, respectively.
816 *
817 * Otherwise we fall back on a kluge that assumes the compiler will complain
818 * about a negative width for a struct bit-field. This will not include a
819 * helpful error message, but it beats not getting an error at all.
820 */
821#ifndef __cplusplus
822#ifdef HAVE__STATIC_ASSERT
823#define StaticAssertStmt(condition, errmessage) \
824 do { _Static_assert(condition, errmessage); } while(0)
825#define StaticAssertExpr(condition, errmessage) \
826 ((void) ({ StaticAssertStmt(condition, errmessage); true; }))
827#else /* !HAVE__STATIC_ASSERT */
828#define StaticAssertStmt(condition, errmessage) \
829 ((void) sizeof(struct { int static_assert_failure : (condition) ? 1 : -1; }))
830#define StaticAssertExpr(condition, errmessage) \
831 StaticAssertStmt(condition, errmessage)
832#endif /* HAVE__STATIC_ASSERT */
833#else /* C++ */
834#if defined(__cpp_static_assert) && __cpp_static_assert >= 200410
835#define StaticAssertStmt(condition, errmessage) \
836 static_assert(condition, errmessage)
837#define StaticAssertExpr(condition, errmessage) \
838 ({ static_assert(condition, errmessage); })
839#else
840#define StaticAssertStmt(condition, errmessage) \
841 do { struct static_assert_struct { int static_assert_failure : (condition) ? 1 : -1; }; } while(0)
842#define StaticAssertExpr(condition, errmessage) \
843 ((void) ({ StaticAssertStmt(condition, errmessage); }))
844#endif
845#endif /* C++ */
846
847
848/*
849 * Compile-time checks that a variable (or expression) has the specified type.
850 *
851 * AssertVariableIsOfType() can be used as a statement.
852 * AssertVariableIsOfTypeMacro() is intended for use in macros, eg
853 * #define foo(x) (AssertVariableIsOfTypeMacro(x, int), bar(x))
854 *
855 * If we don't have __builtin_types_compatible_p, we can still assert that
856 * the types have the same size. This is far from ideal (especially on 32-bit
857 * platforms) but it provides at least some coverage.
858 */
859#ifdef HAVE__BUILTIN_TYPES_COMPATIBLE_P
860#define AssertVariableIsOfType(varname, typename) \
861 StaticAssertStmt(__builtin_types_compatible_p(__typeof__(varname), typename), \
862 CppAsString(varname) " does not have type " CppAsString(typename))
863#define AssertVariableIsOfTypeMacro(varname, typename) \
864 (StaticAssertExpr(__builtin_types_compatible_p(__typeof__(varname), typename), \
865 CppAsString(varname) " does not have type " CppAsString(typename)))
866#else /* !HAVE__BUILTIN_TYPES_COMPATIBLE_P */
867#define AssertVariableIsOfType(varname, typename) \
868 StaticAssertStmt(sizeof(varname) == sizeof(typename), \
869 CppAsString(varname) " does not have type " CppAsString(typename))
870#define AssertVariableIsOfTypeMacro(varname, typename) \
871 (StaticAssertExpr(sizeof(varname) == sizeof(typename), \
872 CppAsString(varname) " does not have type " CppAsString(typename)))
873#endif /* HAVE__BUILTIN_TYPES_COMPATIBLE_P */
874
875
876/* ----------------------------------------------------------------
877 * Section 7: widely useful macros
878 * ----------------------------------------------------------------
879 */
880/*
881 * Max
882 * Return the maximum of two numbers.
883 */
884#define Max(x, y) ((x) > (y) ? (x) : (y))
885
886/*
887 * Min
888 * Return the minimum of two numbers.
889 */
890#define Min(x, y) ((x) < (y) ? (x) : (y))
891
892/*
893 * Abs
894 * Return the absolute value of the argument.
895 */
896#define Abs(x) ((x) >= 0 ? (x) : -(x))
897
898/*
899 * StrNCpy
900 * Like standard library function strncpy(), except that result string
901 * is guaranteed to be null-terminated --- that is, at most N-1 bytes
902 * of the source string will be kept.
903 * Also, the macro returns no result (too hard to do that without
904 * evaluating the arguments multiple times, which seems worse).
905 *
906 * BTW: when you need to copy a non-null-terminated string (like a text
907 * datum) and add a null, do not do it with StrNCpy(..., len+1). That
908 * might seem to work, but it fetches one byte more than there is in the
909 * text object. One fine day you'll have a SIGSEGV because there isn't
910 * another byte before the end of memory. Don't laugh, we've had real
911 * live bug reports from real live users over exactly this mistake.
912 * Do it honestly with "memcpy(dst,src,len); dst[len] = '\0';", instead.
913 */
914#define StrNCpy(dst,src,len) \
915 do \
916 { \
917 char * _dst = (dst); \
918 Size _len = (len); \
919\
920 if (_len > 0) \
921 { \
922 strncpy(_dst, (src), _len); \
923 _dst[_len-1] = '\0'; \
924 } \
925 } while (0)
926
927
928/* Get a bit mask of the bits set in non-long aligned addresses */
929#define LONG_ALIGN_MASK (sizeof(long) - 1)
930
931/*
932 * MemSet
933 * Exactly the same as standard library function memset(), but considerably
934 * faster for zeroing small word-aligned structures (such as parsetree nodes).
935 * This has to be a macro because the main point is to avoid function-call
936 * overhead. However, we have also found that the loop is faster than
937 * native libc memset() on some platforms, even those with assembler
938 * memset() functions. More research needs to be done, perhaps with
939 * MEMSET_LOOP_LIMIT tests in configure.
940 */
941#define MemSet(start, val, len) \
942 do \
943 { \
944 /* must be void* because we don't know if it is integer aligned yet */ \
945 void *_vstart = (void *) (start); \
946 int _val = (val); \
947 Size _len = (len); \
948\
949 if ((((uintptr_t) _vstart) & LONG_ALIGN_MASK) == 0 && \
950 (_len & LONG_ALIGN_MASK) == 0 && \
951 _val == 0 && \
952 _len <= MEMSET_LOOP_LIMIT && \
953 /* \
954 * If MEMSET_LOOP_LIMIT == 0, optimizer should find \
955 * the whole "if" false at compile time. \
956 */ \
957 MEMSET_LOOP_LIMIT != 0) \
958 { \
959 long *_start = (long *) _vstart; \
960 long *_stop = (long *) ((char *) _start + _len); \
961 while (_start < _stop) \
962 *_start++ = 0; \
963 } \
964 else \
965 memset(_vstart, _val, _len); \
966 } while (0)
967
968/*
969 * MemSetAligned is the same as MemSet except it omits the test to see if
970 * "start" is word-aligned. This is okay to use if the caller knows a-priori
971 * that the pointer is suitably aligned (typically, because he just got it
972 * from palloc(), which always delivers a max-aligned pointer).
973 */
974#define MemSetAligned(start, val, len) \
975 do \
976 { \
977 long *_start = (long *) (start); \
978 int _val = (val); \
979 Size _len = (len); \
980\
981 if ((_len & LONG_ALIGN_MASK) == 0 && \
982 _val == 0 && \
983 _len <= MEMSET_LOOP_LIMIT && \
984 MEMSET_LOOP_LIMIT != 0) \
985 { \
986 long *_stop = (long *) ((char *) _start + _len); \
987 while (_start < _stop) \
988 *_start++ = 0; \
989 } \
990 else \
991 memset(_start, _val, _len); \
992 } while (0)
993
994
995/*
996 * MemSetTest/MemSetLoop are a variant version that allow all the tests in
997 * MemSet to be done at compile time in cases where "val" and "len" are
998 * constants *and* we know the "start" pointer must be word-aligned.
999 * If MemSetTest succeeds, then it is okay to use MemSetLoop, otherwise use
1000 * MemSetAligned. Beware of multiple evaluations of the arguments when using
1001 * this approach.
1002 */
1003#define MemSetTest(val, len) \
1004 ( ((len) & LONG_ALIGN_MASK) == 0 && \
1005 (len) <= MEMSET_LOOP_LIMIT && \
1006 MEMSET_LOOP_LIMIT != 0 && \
1007 (val) == 0 )
1008
1009#define MemSetLoop(start, val, len) \
1010 do \
1011 { \
1012 long * _start = (long *) (start); \
1013 long * _stop = (long *) ((char *) _start + (Size) (len)); \
1014 \
1015 while (_start < _stop) \
1016 *_start++ = 0; \
1017 } while (0)
1018
1019
1020/* ----------------------------------------------------------------
1021 * Section 8: random stuff
1022 * ----------------------------------------------------------------
1023 */
1024
1025/*
1026 * Invert the sign of a qsort-style comparison result, ie, exchange negative
1027 * and positive integer values, being careful not to get the wrong answer
1028 * for INT_MIN. The argument should be an integral variable.
1029 */
1030#define INVERT_COMPARE_RESULT(var) \
1031 ((var) = ((var) < 0) ? 1 : -(var))
1032
1033/*
1034 * Use this, not "char buf[BLCKSZ]", to declare a field or local variable
1035 * holding a page buffer, if that page might be accessed as a page and not
1036 * just a string of bytes. Otherwise the variable might be under-aligned,
1037 * causing problems on alignment-picky hardware. (In some places, we use
1038 * this to declare buffers even though we only pass them to read() and
1039 * write(), because copying to/from aligned buffers is usually faster than
1040 * using unaligned buffers.) We include both "double" and "int64" in the
1041 * union to ensure that the compiler knows the value must be MAXALIGN'ed
1042 * (cf. configure's computation of MAXIMUM_ALIGNOF).
1043 */
1044typedef union PGAlignedBlock
1045{
1046 char data[BLCKSZ];
1047 double force_align_d;
1048 int64 force_align_i64;
1049} PGAlignedBlock;
1050
1051/* Same, but for an XLOG_BLCKSZ-sized buffer */
1052typedef union PGAlignedXLogBlock
1053{
1054 char data[XLOG_BLCKSZ];
1055 double force_align_d;
1056 int64 force_align_i64;
1057} PGAlignedXLogBlock;
1058
1059/* msb for char */
1060#define HIGHBIT (0x80)
1061#define IS_HIGHBIT_SET(ch) ((unsigned char)(ch) & HIGHBIT)
1062
1063/*
1064 * Support macros for escaping strings. escape_backslash should be true
1065 * if generating a non-standard-conforming string. Prefixing a string
1066 * with ESCAPE_STRING_SYNTAX guarantees it is non-standard-conforming.
1067 * Beware of multiple evaluation of the "ch" argument!
1068 */
1069#define SQL_STR_DOUBLE(ch, escape_backslash) \
1070 ((ch) == '\'' || ((ch) == '\\' && (escape_backslash)))
1071
1072#define ESCAPE_STRING_SYNTAX 'E'
1073
1074
1075#define STATUS_OK (0)
1076#define STATUS_ERROR (-1)
1077#define STATUS_EOF (-2)
1078#define STATUS_FOUND (1)
1079#define STATUS_WAITING (2)
1080
1081/*
1082 * gettext support
1083 */
1084
1085#ifndef ENABLE_NLS
1086/* stuff we'd otherwise get from <libintl.h> */
1087#define gettext(x) (x)
1088#define dgettext(d,x) (x)
1089#define ngettext(s,p,n) ((n) == 1 ? (s) : (p))
1090#define dngettext(d,s,p,n) ((n) == 1 ? (s) : (p))
1091#endif
1092
1093#define _(x) gettext(x)
1094
1095/*
1096 * Use this to mark string constants as needing translation at some later
1097 * time, rather than immediately. This is useful for cases where you need
1098 * access to the original string and translated string, and for cases where
1099 * immediate translation is not possible, like when initializing global
1100 * variables.
1101 * http://www.gnu.org/software/autoconf/manual/gettext/Special-cases.html
1102 */
1103#define gettext_noop(x) (x)
1104
1105/*
1106 * To better support parallel installations of major PostgreSQL
1107 * versions as well as parallel installations of major library soname
1108 * versions, we mangle the gettext domain name by appending those
1109 * version numbers. The coding rule ought to be that wherever the
1110 * domain name is mentioned as a literal, it must be wrapped into
1111 * PG_TEXTDOMAIN(). The macros below do not work on non-literals; but
1112 * that is somewhat intentional because it avoids having to worry
1113 * about multiple states of premangling and postmangling as the values
1114 * are being passed around.
1115 *
1116 * Make sure this matches the installation rules in nls-global.mk.
1117 */
1118#ifdef SO_MAJOR_VERSION
1119#define PG_TEXTDOMAIN(domain) (domain CppAsString2(SO_MAJOR_VERSION) "-" PG_MAJORVERSION)
1120#else
1121#define PG_TEXTDOMAIN(domain) (domain "-" PG_MAJORVERSION)
1122#endif
1123
1124/*
1125 * Macro that allows to cast constness and volatile away from an expression, but doesn't
1126 * allow changing the underlying type. Enforcement of the latter
1127 * currently only works for gcc like compilers.
1128 *
1129 * Please note IT IS NOT SAFE to cast constness away if the result will ever
1130 * be modified (it would be undefined behaviour). Doing so anyway can cause
1131 * compiler misoptimizations or runtime crashes (modifying readonly memory).
1132 * It is only safe to use when the result will not be modified, but API
1133 * design or language restrictions prevent you from declaring that
1134 * (e.g. because a function returns both const and non-const variables).
1135 *
1136 * Note that this only works in function scope, not for global variables (it'd
1137 * be nice, but not trivial, to improve that).
1138 */
1139#if defined(HAVE__BUILTIN_TYPES_COMPATIBLE_P)
1140#define unconstify(underlying_type, expr) \
1141 (StaticAssertExpr(__builtin_types_compatible_p(__typeof(expr), const underlying_type), \
1142 "wrong cast"), \
1143 (underlying_type) (expr))
1144#define unvolatize(underlying_type, expr) \
1145 (StaticAssertExpr(__builtin_types_compatible_p(__typeof(expr), volatile underlying_type), \
1146 "wrong cast"), \
1147 (underlying_type) (expr))
1148#else
1149#define unconstify(underlying_type, expr) \
1150 ((underlying_type) (expr))
1151#define unvolatize(underlying_type, expr) \
1152 ((underlying_type) (expr))
1153#endif
1154
1155/* ----------------------------------------------------------------
1156 * Section 9: system-specific hacks
1157 *
1158 * This should be limited to things that absolutely have to be
1159 * included in every source file. The port-specific header file
1160 * is usually a better place for this sort of thing.
1161 * ----------------------------------------------------------------
1162 */
1163
1164/*
1165 * NOTE: this is also used for opening text files.
1166 * WIN32 treats Control-Z as EOF in files opened in text mode.
1167 * Therefore, we open files in binary mode on Win32 so we can read
1168 * literal control-Z. The other affect is that we see CRLF, but
1169 * that is OK because we can already handle those cleanly.
1170 */
1171#if defined(WIN32) || defined(__CYGWIN__)
1172#define PG_BINARY O_BINARY
1173#define PG_BINARY_A "ab"
1174#define PG_BINARY_R "rb"
1175#define PG_BINARY_W "wb"
1176#else
1177#define PG_BINARY 0
1178#define PG_BINARY_A "a"
1179#define PG_BINARY_R "r"
1180#define PG_BINARY_W "w"
1181#endif
1182
1183/*
1184 * Provide prototypes for routines not present in a particular machine's
1185 * standard C library.
1186 */
1187
1188#if defined(HAVE_FDATASYNC) && !HAVE_DECL_FDATASYNC
1189extern int fdatasync(int fildes);
1190#endif
1191
1192#ifdef HAVE_LONG_LONG_INT
1193/* Older platforms may provide strto[u]ll functionality under other names */
1194#if !defined(HAVE_STRTOLL) && defined(HAVE___STRTOLL)
1195#define strtoll __strtoll
1196#define HAVE_STRTOLL 1
1197#endif
1198
1199#if !defined(HAVE_STRTOLL) && defined(HAVE_STRTOQ)
1200#define strtoll strtoq
1201#define HAVE_STRTOLL 1
1202#endif
1203
1204#if !defined(HAVE_STRTOULL) && defined(HAVE___STRTOULL)
1205#define strtoull __strtoull
1206#define HAVE_STRTOULL 1
1207#endif
1208
1209#if !defined(HAVE_STRTOULL) && defined(HAVE_STRTOUQ)
1210#define strtoull strtouq
1211#define HAVE_STRTOULL 1
1212#endif
1213
1214#if defined(HAVE_STRTOLL) && !HAVE_DECL_STRTOLL
1215extern long long strtoll(const char *str, char **endptr, int base);
1216#endif
1217
1218#if defined(HAVE_STRTOULL) && !HAVE_DECL_STRTOULL
1219extern unsigned long long strtoull(const char *str, char **endptr, int base);
1220#endif
1221#endif /* HAVE_LONG_LONG_INT */
1222
1223#if !defined(HAVE_MEMMOVE) && !defined(memmove)
1224#define memmove(d, s, c) bcopy(s, d, c)
1225#endif
1226
1227/* no special DLL markers on most ports */
1228#ifndef PGDLLIMPORT
1229#define PGDLLIMPORT
1230#endif
1231#ifndef PGDLLEXPORT
1232#define PGDLLEXPORT
1233#endif
1234
1235/*
1236 * The following is used as the arg list for signal handlers. Any ports
1237 * that take something other than an int argument should override this in
1238 * their pg_config_os.h file. Note that variable names are required
1239 * because it is used in both the prototypes as well as the definitions.
1240 * Note also the long name. We expect that this won't collide with
1241 * other names causing compiler warnings.
1242 */
1243
1244#ifndef SIGNAL_ARGS
1245#define SIGNAL_ARGS int postgres_signal_arg
1246#endif
1247
1248/*
1249 * When there is no sigsetjmp, its functionality is provided by plain
1250 * setjmp. Incidentally, nothing provides setjmp's functionality in
1251 * that case. We now support the case only on Windows.
1252 */
1253#ifdef WIN32
1254#define sigjmp_buf jmp_buf
1255#define sigsetjmp(x,y) setjmp(x)
1256#define siglongjmp longjmp
1257#endif
1258
1259/* EXEC_BACKEND defines */
1260#ifdef EXEC_BACKEND
1261#define NON_EXEC_STATIC
1262#else
1263#define NON_EXEC_STATIC static
1264#endif
1265
1266/* /port compatibility functions */
1267#include "port.h"
1268
1269#endif /* C_H */
1270