PostgreSQL Source Code git master
Loading...
Searching...
No Matches
c.h
Go to the documentation of this file.
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-2026, 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/* IWYU pragma: always_keep */
20/*
21 *----------------------------------------------------------------
22 * TABLE OF CONTENTS
23 *
24 * When adding stuff to this file, please try to put stuff
25 * into the relevant section, or add new sections as appropriate.
26 *
27 * section description
28 * ------- ------------------------------------------------
29 * 0) pg_config.h and standard system headers
30 * 1) compiler characteristics
31 * 2) bool, true, false
32 * 3) standard system types
33 * 4) IsValid macros for system types
34 * 5) lengthof, alignment
35 * 6) assertions
36 * 7) widely useful macros
37 * 8) random stuff
38 * 9) system-specific hacks
39 *
40 * NOTE: since this file is included by both frontend and backend modules,
41 * it's usually wrong to put an "extern" declaration here, unless it's
42 * ifdef'd so that it's seen in only one case or the other.
43 * typedefs and macros are the kind of thing that might go here.
44 *
45 *----------------------------------------------------------------
46 */
47#ifndef C_H
48#define C_H
49
50/* IWYU pragma: begin_exports */
51
52/*
53 * These headers must be included before any system headers, because on some
54 * platforms they affect the behavior of the system headers (for example, by
55 * defining _FILE_OFFSET_BITS).
56 */
57#include "pg_config.h"
58#include "pg_config_manual.h" /* must be after pg_config.h */
59#include "pg_config_os.h" /* config from include/port/PORTNAME.h */
60
61/* System header files that should be available everywhere in Postgres */
62#include <assert.h>
63#include <inttypes.h>
64#include <stdalign.h>
65#include <stdio.h>
66#include <stdlib.h>
67#include <string.h>
68#include <stddef.h>
69#include <stdarg.h>
70#ifdef HAVE_STRINGS_H
71#include <strings.h>
72#endif
73#include <stdint.h>
74#include <sys/types.h>
75#include <errno.h>
76#if defined(WIN32) || defined(__CYGWIN__)
77#include <fcntl.h> /* ensure O_BINARY is available */
78#endif
79#include <locale.h>
80#ifdef HAVE_XLOCALE_H
81#include <xlocale.h>
82#endif
83#ifdef ENABLE_NLS
84#include <libintl.h>
85#endif
86
87#ifdef __cplusplus
88extern "C++"
89{
90/* This header is used in the definition of various C++ things below. */
91#include <type_traits>
92}
93#endif
94
95 /* Pull in fundamental symbols that we also expose to applications */
96#include "postgres_ext.h"
97
98/* Define before including zlib.h to add const decorations to zlib API. */
99#ifdef HAVE_LIBZ
100#define ZLIB_CONST
101#endif
102
103
104/* ----------------------------------------------------------------
105 * Section 1: compiler characteristics
106 * ----------------------------------------------------------------
107 */
108
109/*
110 * Not all compilers follow gcc's names of macros for particular target
111 * architectures. Let's standardize on gcc's names (with trailing __),
112 * and cause those to become defined here if they are not already.
113 *
114 * Note: while this list is alphabetical, it's necessary to check _M_ARM64
115 * before _M_AMD64, because Microsoft's ARM64EC environment defines both.
116 */
117#if defined(__arm__) || defined(__arm)
118#ifndef __arm__
119#define __arm__ 1
120#endif
121#elif defined(__aarch64__) || defined(_M_ARM64)
122#ifndef __aarch64__
123#define __aarch64__ 1
124#endif
125#elif defined(__loongarch64__) || defined(__loongarch64)
126#ifndef __loongarch64__
127#define __loongarch64__ 1
128#endif
129#elif defined(__mips__)
130/* no work */
131#elif defined(__mips64__)
132/* no work */
133#elif defined(__powerpc__) || defined(__ppc__)
134#ifndef __powerpc__
135#define __powerpc__ 1
136#endif
137#elif defined(__powerpc64__) || defined(__ppc64__)
138#ifndef __powerpc64__
139#define __powerpc64__ 1
140#endif
141#elif defined(__riscv)
142/* RISC-V doesn't follow the common naming pattern, so force it */
143#if SIZEOF_VOID_P == 8
144#define __riscv64__ 1
145#else
146#define __riscv__ 1
147#endif
148#elif defined(__s390__)
149/* no work */
150#elif defined(__s390x__)
151/* no work */
152#elif defined(__sparc__) || defined(__sparc)
153#ifndef __sparc__
154#define __sparc__ 1
155#endif
156#elif defined(__i386__) || defined (__i386) || defined(_M_IX86)
157#ifndef __i386__
158#define __i386__ 1
159#endif
160#elif defined(__x86_64__) || defined(__x86_64) || defined (__amd64) || defined(_M_AMD64)
161#ifndef __x86_64__
162#define __x86_64__ 1
163#endif
164#else
165#error "cannot identify target architecture"
166#endif
167
168/*
169 * Disable "inline" if PG_FORCE_DISABLE_INLINE is defined.
170 * This is used to work around compiler bugs and might also be useful for
171 * investigatory purposes.
172 */
173#ifdef PG_FORCE_DISABLE_INLINE
174#undef inline
175#define inline
176#endif
177
178/*
179 * Attribute macros
180 *
181 * C23: https://en.cppreference.com/w/c/language/attributes.html
182 * C++: https://en.cppreference.com/w/cpp/language/attributes.html
183 * GCC: https://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
184 * GCC: https://gcc.gnu.org/onlinedocs/gcc/Type-Attributes.html
185 * Clang: https://clang.llvm.org/docs/AttributeReference.html
186 */
187
188/*
189 * For compilers which don't support __has_attribute, we just define
190 * __has_attribute(x) to 0 so that we can define macros for various
191 * __attribute__s more easily below.
192 *
193 * Note that __has_attribute only tells about GCC-style attributes, not C23 or
194 * C++ attributes.
195 */
196#ifndef __has_attribute
197#define __has_attribute(attribute) 0
198#endif
199
200/*
201 * pg_attribute_unused() suppresses compiler warnings on unused entities.
202 */
203#if (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 202311L) || (defined(__cplusplus) && __cplusplus >= 201703L)
204#define pg_attribute_unused() [[maybe_unused]]
205#elif defined(__GNUC__)
206#define pg_attribute_unused() __attribute__((unused))
207#else
208#define pg_attribute_unused()
209#endif
210
211/*
212 * pg_fallthrough indicates that the fall through from the previous case is
213 * intentional.
214 */
215#if (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 202311L) || (defined(__cplusplus) && __cplusplus >= 201703L)
216#define pg_fallthrough [[fallthrough]]
217#elif __has_attribute(fallthrough)
218#define pg_fallthrough __attribute__((fallthrough))
219#else
220#define pg_fallthrough
221#endif
222
223/*
224 * pg_nodiscard means the compiler should warn if the result of a function
225 * call is ignored.
226 */
227#if (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 202311L) || (defined(__cplusplus) && __cplusplus >= 201703L)
228#define pg_nodiscard [[nodiscard]]
229#elif defined(__GNUC__)
230#define pg_nodiscard __attribute__((warn_unused_result))
231#else
232#define pg_nodiscard
233#endif
234
235/*
236 * pg_noreturn corresponds to the C11 noreturn/_Noreturn function specifier.
237 * We can't use the standard name "noreturn" because some third-party code
238 * uses __attribute__((noreturn)) in headers, which would get confused if
239 * "noreturn" is defined to "_Noreturn", as is done by <stdnoreturn.h>.
240 *
241 * C23 attributes must be placed at the start of a declaration or statement.
242 * C11 function specifiers go before the function name in a declaration, but
243 * it is common style (and required for C23 compatibility) to put them before
244 * the return type.
245 */
246#if (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 202311L) || defined(__cplusplus)
247#define pg_noreturn [[noreturn]]
248#else
249#define pg_noreturn _Noreturn
250#endif
251
252/*
253 * This macro will disable address safety instrumentation for a function
254 * when running with "-fsanitize=address". Think twice before using this!
255 */
256#if defined(__clang__) || __GNUC__ >= 8
257#define pg_attribute_no_sanitize_address() __attribute__((no_sanitize("address")))
258#elif __has_attribute(no_sanitize_address)
259/* This would work for clang, but it's deprecated. */
260#define pg_attribute_no_sanitize_address() __attribute__((no_sanitize_address))
261#else
262#define pg_attribute_no_sanitize_address()
263#endif
264
265/*
266 * Place this macro before functions that should be allowed to make misaligned
267 * accesses. Think twice before using it on non-x86-specific code!
268 * Testing can be done with "-fsanitize=alignment -fsanitize-trap=alignment"
269 * on clang, or "-fsanitize=alignment -fno-sanitize-recover=alignment" on gcc.
270 */
271#if __clang_major__ >= 7 || __GNUC__ >= 8
272#define pg_attribute_no_sanitize_alignment() __attribute__((no_sanitize("alignment")))
273#else
274#define pg_attribute_no_sanitize_alignment()
275#endif
276
277/*
278 * pg_attribute_nonnull means the compiler should warn if the function is
279 * called with the listed arguments set to NULL. If no arguments are
280 * listed, the compiler should warn if any pointer arguments are set to NULL.
281 */
282#if __has_attribute (nonnull)
283#define pg_attribute_nonnull(...) __attribute__((nonnull(__VA_ARGS__)))
284#else
285#define pg_attribute_nonnull(...)
286#endif
287
288/*
289 * pg_attribute_target allows specifying different target options that the
290 * function should be compiled with (e.g., for using special CPU instructions).
291 * Note that there still needs to be a configure-time check to verify that a
292 * specific target is understood by the compiler.
293 */
294#if __has_attribute (target)
295#define pg_attribute_target(...) __attribute__((target(__VA_ARGS__)))
296#else
297#define pg_attribute_target(...)
298#endif
299
300/*
301 * Append PG_USED_FOR_ASSERTS_ONLY to definitions of variables that are only
302 * used in assert-enabled builds, to avoid compiler warnings about unused
303 * variables in assert-disabled builds.
304 */
305#ifdef USE_ASSERT_CHECKING
306#define PG_USED_FOR_ASSERTS_ONLY
307#else
308#define PG_USED_FOR_ASSERTS_ONLY pg_attribute_unused()
309#endif
310
311/*
312 * Our C and C++ compilers may have different ideas about which printf
313 * archetype best represents what src/port/snprintf.c can do.
314 */
315#ifndef __cplusplus
316#define PG_PRINTF_ATTRIBUTE PG_C_PRINTF_ATTRIBUTE
317#else
318#define PG_PRINTF_ATTRIBUTE PG_CXX_PRINTF_ATTRIBUTE
319#endif
320
321/* GCC supports format attributes */
322#if defined(__GNUC__)
323#define pg_attribute_format_arg(a) __attribute__((format_arg(a)))
324#define pg_attribute_printf(f,a) __attribute__((format(PG_PRINTF_ATTRIBUTE, f, a)))
325#else
326#define pg_attribute_format_arg(a)
327#define pg_attribute_printf(f,a)
328#endif
329
330/* GCC supports aligned and packed */
331#if defined(__GNUC__)
332#define pg_attribute_aligned(a) __attribute__((aligned(a)))
333#define pg_attribute_packed() __attribute__((packed))
334#elif defined(_MSC_VER)
335/*
336 * MSVC supports aligned.
337 *
338 * Packing is also possible but only by wrapping the entire struct definition
339 * which doesn't fit into our current macro declarations.
340 */
341#define pg_attribute_aligned(a) __declspec(align(a))
342#else
343/*
344 * NB: aligned and packed are not given default definitions because they
345 * affect code functionality; they *must* be implemented by the compiler
346 * if they are to be used.
347 */
348#endif
349
350/*
351 * Use "pg_attribute_always_inline" in place of "inline" for functions that
352 * we wish to force inlining of, even when the compiler's heuristics would
353 * choose not to. But, if possible, don't force inlining in unoptimized
354 * debug builds.
355 */
356#if defined(__GNUC__) && defined(__OPTIMIZE__)
357/* GCC supports always_inline via __attribute__ */
358#define pg_attribute_always_inline __attribute__((always_inline)) inline
359#elif defined(_MSC_VER)
360/* MSVC has a special keyword for this */
361#define pg_attribute_always_inline __forceinline
362#else
363/* Otherwise, the best we can do is to say "inline" */
364#define pg_attribute_always_inline inline
365#endif
366
367/*
368 * Forcing a function not to be inlined can be useful if it's the slow path of
369 * a performance-critical function, or should be visible in profiles to allow
370 * for proper cost attribution. Note that unlike the pg_attribute_XXX macros
371 * above, this should be placed before the function's return type and name.
372 */
373/* GCC supports noinline via __attribute__ */
374#if defined(__GNUC__)
375#define pg_noinline __attribute__((noinline))
376/* msvc via declspec */
377#elif defined(_MSC_VER)
378#define pg_noinline __declspec(noinline)
379#else
380#define pg_noinline
381#endif
382
383/*
384 * For now, just define pg_attribute_cold and pg_attribute_hot to be empty
385 * macros on minGW 8.1. There appears to be a compiler bug that results in
386 * compilation failure. At this time, we still have at least one buildfarm
387 * animal running that compiler, so this should make that green again. It's
388 * likely this compiler is not popular enough to warrant keeping this code
389 * around forever, so let's just remove it once the last buildfarm animal
390 * upgrades.
391 */
392#if defined(__MINGW64__) && __GNUC__ == 8 && __GNUC_MINOR__ == 1
393
394#define pg_attribute_cold
395#define pg_attribute_hot
396
397#else
398/*
399 * Marking certain functions as "hot" or "cold" can be useful to assist the
400 * compiler in arranging the assembly code in a more efficient way.
401 */
402#if __has_attribute (cold)
403#define pg_attribute_cold __attribute__((cold))
404#else
405#define pg_attribute_cold
406#endif
407
408#if __has_attribute (hot)
409#define pg_attribute_hot __attribute__((hot))
410#else
411#define pg_attribute_hot
412#endif
413
414#endif /* defined(__MINGW64__) && __GNUC__ == 8 &&
415 * __GNUC_MINOR__ == 1 */
416/*
417 * Mark a point as unreachable in a portable fashion. This should preferably
418 * be something that the compiler understands, to aid code generation.
419 * In assert-enabled builds, we prefer abort() for debugging reasons.
420 */
421#if defined(HAVE__BUILTIN_UNREACHABLE) && !defined(USE_ASSERT_CHECKING)
422#define pg_unreachable() __builtin_unreachable()
423#elif defined(_MSC_VER) && !defined(USE_ASSERT_CHECKING)
424#define pg_unreachable() __assume(0)
425#else
426#define pg_unreachable() abort()
427#endif
428
429/*
430 * Define a compiler-independent macro for determining if an expression is a
431 * compile-time integer const. We don't define this macro to return 0 when
432 * unsupported due to the risk of users of the macro misbehaving if we return
433 * 0 when the expression *is* an integer constant. Callers may check if this
434 * macro is defined by checking if HAVE_PG_INTEGER_CONSTANT_P is defined.
435 */
436#if defined(HAVE__BUILTIN_CONSTANT_P)
437
438/* When __builtin_constant_p() is available, use it. */
439#define pg_integer_constant_p(x) __builtin_constant_p(x)
440#define HAVE_PG_INTEGER_CONSTANT_P
441#elif defined(_MSC_VER) && defined(__STDC_VERSION__)
442
443/*
444 * With MSVC we can use a trick with _Generic to make this work. This has
445 * been borrowed from:
446 * https://stackoverflow.com/questions/49480442/detecting-integer-constant-expressions-in-macros
447 * and only works with integer constants. Compilation will fail if given a
448 * constant or variable of any type other than an integer.
449 */
450#define pg_integer_constant_p(x) \
451 _Generic((1 ? ((void *) ((x) * (uintptr_t) 0)) : &(int) {1}), int *: 1, void *: 0)
452#define HAVE_PG_INTEGER_CONSTANT_P
453#endif
454
455/*
456 * pg_assume(expr) states that we assume `expr` to evaluate to true. In assert
457 * enabled builds pg_assume() is turned into an assertion, in optimized builds
458 * we try to clue the compiler into the fact that `expr` is true.
459 *
460 * This is useful for two purposes:
461 *
462 * 1) Avoid compiler warnings by telling the compiler about assumptions the
463 * code makes. This is particularly useful when building with optimizations
464 * and w/o assertions.
465 *
466 * 2) Help the compiler to generate more efficient code
467 *
468 * It is unspecified whether `expr` is evaluated, therefore it better be
469 * side-effect free.
470 */
471#if defined(USE_ASSERT_CHECKING)
472#define pg_assume(expr) Assert(expr)
473#elif defined(HAVE__BUILTIN_UNREACHABLE)
474#define pg_assume(expr) \
475 do { \
476 if (!(expr)) \
477 __builtin_unreachable(); \
478 } while (0)
479#elif defined(_MSC_VER)
480#define pg_assume(expr) __assume(expr)
481#else
482#define pg_assume(expr) ((void) 0)
483#endif
484
485/*
486 * Hints to the compiler about the likelihood of a branch. Both likely() and
487 * unlikely() return the boolean value of the contained expression.
488 *
489 * These should only be used sparingly, in very hot code paths. It's very easy
490 * to mis-estimate likelihoods.
491 */
492#ifdef __GNUC__
493#define likely(x) __builtin_expect((x) != 0, 1)
494#define unlikely(x) __builtin_expect((x) != 0, 0)
495#else
496#define likely(x) ((x) != 0)
497#define unlikely(x) ((x) != 0)
498#endif
499
500/*
501 * When we call clang to generate bitcode, we might be using configure results
502 * from a different compiler, which might not be fully compatible with the
503 * clang we are using. The fully correct solution would be to run a separate
504 * set of configure tests for that clang-for-bitcode, but that could be very
505 * difficult to implement, and in practice clang supports most things other
506 * compilers support. So this section just contains some hardcoded ugliness
507 * to override some configure results where it is necessary.
508 */
509#if defined(__clang__)
510#if __clang_major__ < 19
511#undef HAVE_TYPEOF_UNQUAL
512#else
513#undef typeof_unqual
514#define typeof_unqual __typeof_unqual__
515#endif
516#endif /* __clang__ */
517
518/*
519 * Provide typeof in C++ for C++ compilers that don't support typeof natively.
520 * It might be spelled __typeof__ instead of typeof, in which case
521 * pg_cxx_typeof provides that mapping. If neither is supported, we can use
522 * decltype, but to make it equivalent to C's typeof, we need to remove
523 * references from the result [1]. Also ensure HAVE_TYPEOF is set so that
524 * typeof-dependent code is always enabled in C++ mode.
525 *
526 * [1]: https://www.open-std.org/jtc1/sc22/wg14/www/docs/n2927.htm#existing-decltype
527 */
528#if defined(__cplusplus)
529#undef typeof
530#ifdef pg_cxx_typeof
531#define typeof(x) pg_cxx_typeof(x)
532#elif !defined(HAVE_CXX_TYPEOF)
533#define typeof(x) std::remove_reference<decltype(x)>::type
534#endif
535#ifndef HAVE_TYPEOF
536#define HAVE_TYPEOF 1
537#endif
538/*
539 * and analogously for typeof_unqual
540 */
541#undef typeof_unqual
542#ifdef pg_cxx_typeof_unqual
543#define typeof_unqual(x) pg_cxx_typeof_unqual(x)
544#elif !defined(HAVE_CXX_TYPEOF_UNQUAL)
545#define typeof_unqual(x) std::remove_cv<std::remove_reference<decltype(x)>::type>::type
546#endif
547#ifndef HAVE_TYPEOF_UNQUAL
548#define HAVE_TYPEOF_UNQUAL 1
549#endif
550#endif /* __cplusplus */
551
552/*
553 * CppAsString
554 * Convert the argument to a string, using the C preprocessor.
555 * CppAsString2
556 * Convert the argument to a string, after one round of macro expansion.
557 * CppConcat
558 * Concatenate two arguments together, using the C preprocessor.
559 *
560 * Note: There used to be support here for pre-ANSI C compilers that didn't
561 * support # and ##. Nowadays, these macros are just for clarity and/or
562 * backward compatibility with existing PostgreSQL code.
563 */
564#define CppAsString(identifier) #identifier
565#define CppAsString2(x) CppAsString(x)
566#define CppConcat(x, y) x##y
567
568/*
569 * VA_ARGS_NARGS
570 * Returns the number of macro arguments it is passed.
571 *
572 * An empty argument still counts as an argument, so effectively, this is
573 * "one more than the number of commas in the argument list".
574 *
575 * This works for up to 63 arguments. Internally, VA_ARGS_NARGS_() is passed
576 * 64+N arguments, and the C99 standard only requires macros to allow up to
577 * 127 arguments, so we can't portably go higher. The implementation is
578 * pretty trivial: VA_ARGS_NARGS_() returns its 64th argument, and we set up
579 * the call so that that is the appropriate one of the list of constants.
580 * This idea is due to Laurent Deniau.
581 */
582#define VA_ARGS_NARGS(...) \
583 VA_ARGS_NARGS_(__VA_ARGS__, \
584 63,62,61,60, \
585 59,58,57,56,55,54,53,52,51,50, \
586 49,48,47,46,45,44,43,42,41,40, \
587 39,38,37,36,35,34,33,32,31,30, \
588 29,28,27,26,25,24,23,22,21,20, \
589 19,18,17,16,15,14,13,12,11,10, \
590 9, 8, 7, 6, 5, 4, 3, 2, 1, 0)
591
592#define VA_ARGS_NARGS_( \
593 _01,_02,_03,_04,_05,_06,_07,_08,_09,_10, \
594 _11,_12,_13,_14,_15,_16,_17,_18,_19,_20, \
595 _21,_22,_23,_24,_25,_26,_27,_28,_29,_30, \
596 _31,_32,_33,_34,_35,_36,_37,_38,_39,_40, \
597 _41,_42,_43,_44,_45,_46,_47,_48,_49,_50, \
598 _51,_52,_53,_54,_55,_56,_57,_58,_59,_60, \
599 _61,_62,_63, N, ...) \
600 (N)
601
602/*
603 * Generic function pointer. This can be used in the rare cases where it's
604 * necessary to cast a function pointer to a seemingly incompatible function
605 * pointer type while avoiding gcc's -Wcast-function-type warnings.
606 */
607typedef void (*pg_funcptr_t) (void);
608
609/*
610 * We require C99, hence the compiler should understand flexible array
611 * members. However, for documentation purposes we still consider it to be
612 * project style to write "field[FLEXIBLE_ARRAY_MEMBER]" not just "field[]".
613 * When computing the size of such an object, use "offsetof(struct s, f)"
614 * for portability. Don't use "offsetof(struct s, f[0])", as this doesn't
615 * work with MSVC and with C++ compilers.
616 */
617#define FLEXIBLE_ARRAY_MEMBER /* empty */
618
619/*
620 * Does the compiler support #pragma GCC system_header? We optionally use it
621 * to avoid warnings that we can't fix (e.g. in the perl headers).
622 * See https://gcc.gnu.org/onlinedocs/cpp/System-Headers.html
623 *
624 * Headers for which we do not want to show compiler warnings can,
625 * conditionally, use #pragma GCC system_header to avoid warnings. Obviously
626 * this should only be used for external headers over which we do not have
627 * control.
628 *
629 * Support for the pragma is tested here, instead of during configure, as gcc
630 * also warns about the pragma being used in a .c file. It's surprisingly hard
631 * to get autoconf to use .h as the file-ending. Looks like gcc has
632 * implemented the pragma since the 2000, so this test should suffice.
633 *
634 *
635 * Alternatively, we could add the include paths for problematic headers with
636 * -isystem, but that is a larger hammer and is harder to search for.
637 *
638 * A more granular alternative would be to use #pragma GCC diagnostic
639 * push/ignored/pop, but gcc warns about unknown warnings being ignored, so
640 * every to-be-ignored-temporarily compiler warning would require its own
641 * pg_config.h symbol and #ifdef.
642 */
643#ifdef __GNUC__
644#define HAVE_PRAGMA_GCC_SYSTEM_HEADER 1
645#endif
646
647
648/* ----------------------------------------------------------------
649 * Section 2: bool, true, false
650 * ----------------------------------------------------------------
651 */
652
653/*
654 * bool
655 * Boolean value, either true or false.
656 *
657 * PostgreSQL currently cannot deal with bool of size other than 1; there are
658 * static assertions around the code to prevent that.
659 */
660
661#include <stdbool.h>
662
663
664/* ----------------------------------------------------------------
665 * Section 3: standard system types
666 * ----------------------------------------------------------------
667 */
668
669/*
670 * Pointer
671 * Variable holding address of any memory resident object.
672 * (obsolescent; use void * or char *)
673 */
674typedef void *Pointer;
675
676/* Historical names for types in <stdint.h>. */
677typedef int8_t int8;
685
686/*
687 * 64-bit integers
688 */
689#define INT64CONST(x) INT64_C(x)
690#define UINT64CONST(x) UINT64_C(x)
691
692/* snprintf format strings to use for 64-bit integers */
693#define INT64_FORMAT "%" PRId64
694#define UINT64_FORMAT "%" PRIu64
695#define OID8_FORMAT "%" PRIu64
696
697/*
698 * 128-bit signed and unsigned integers
699 * There currently is only limited support for such types.
700 * E.g. 128bit literals and snprintf are not supported; but math is.
701 * Also, because we exclude such types when choosing MAXIMUM_ALIGNOF,
702 * it must be possible to coerce the compiler to allocate them on no
703 * more than MAXALIGN boundaries.
704 */
705#if defined(PG_INT128_TYPE)
706#if defined(pg_attribute_aligned) || ALIGNOF_PG_INT128_TYPE <= MAXIMUM_ALIGNOF
707#define HAVE_INT128 1
708
710#if defined(pg_attribute_aligned)
712#endif
713 ;
714
715typedef unsigned PG_INT128_TYPE uint128
716#if defined(pg_attribute_aligned)
718#endif
719 ;
720
721#endif
722#endif
723
724/* Historical names for limits in <stdint.h>. */
725#define PG_INT8_MIN INT8_MIN
726#define PG_INT8_MAX INT8_MAX
727#define PG_UINT8_MAX UINT8_MAX
728#define PG_INT16_MIN INT16_MIN
729#define PG_INT16_MAX INT16_MAX
730#define PG_UINT16_MAX UINT16_MAX
731#define PG_INT32_MIN INT32_MIN
732#define PG_INT32_MAX INT32_MAX
733#define PG_UINT32_MAX UINT32_MAX
734#define PG_INT64_MIN INT64_MIN
735#define PG_INT64_MAX INT64_MAX
736#define PG_UINT64_MAX UINT64_MAX
737
738/*
739 * We now always use int64 timestamps, but keep this symbol defined for the
740 * benefit of external code that might test it.
741 */
742#define HAVE_INT64_TIMESTAMP
743
744/*
745 * Size
746 * Size of any memory resident object, as returned by sizeof.
747 */
748typedef size_t Size;
749
750/*
751 * Index
752 * Index into any memory resident array.
753 *
754 * Note:
755 * Indices are non negative.
756 */
757typedef unsigned int Index;
758
759/*
760 * Offset
761 * Offset into any memory resident array.
762 *
763 * Note:
764 * This differs from an Index in that an Index is always
765 * non negative, whereas Offset may be negative.
766 */
767typedef signed int Offset;
768
769/*
770 * Common Postgres datatype names (as used in the catalogs)
771 */
772typedef float float4;
773typedef double float8;
774
775/*
776 * float8, int8, and related datatypes are now always pass-by-value.
777 * We keep this symbol to avoid breaking extension code that may use it.
778 */
779#define FLOAT8PASSBYVAL true
780
781/*
782 * Oid, Oid8, RegProcedure, TransactionId, SubTransactionId, MultiXactId,
783 * CommandId
784 */
785
786/* typedef Oid is in postgres_ext.h */
787
788/*
789 * regproc is the type name used in the include/catalog headers, but
790 * RegProcedure is the preferred name in C code.
791 */
792typedef Oid regproc;
794
796
798
800
801#define InvalidSubTransactionId ((SubTransactionId) 0)
802#define TopSubTransactionId ((SubTransactionId) 1)
803
804/* MultiXactId must be equivalent to TransactionId, to fit in t_xmax */
806
808
810
811#define FirstCommandId ((CommandId) 0)
812#define InvalidCommandId (~(CommandId)0)
813
814/* 8-byte Object ID */
815typedef uint64 Oid8;
816
817#define InvalidOid8 ((Oid8) 0)
818#define OID8_MAX UINT64_MAX
819
820/* ----------------
821 * Variable-length datatypes all share the 'varlena' header.
822 *
823 * NOTE: for TOASTable types, this is an oversimplification, since the value
824 * may be compressed or moved out-of-line. However datatype-specific routines
825 * are mostly content to deal with de-TOASTed values only, and of course
826 * client-side routines should never see a TOASTed value. But even in a
827 * de-TOASTed value, beware of touching vl_len_ directly, as its
828 * representation is no longer convenient. It's recommended that code always
829 * use macros VARDATA_ANY, VARSIZE_ANY, VARSIZE_ANY_EXHDR, VARDATA, VARSIZE,
830 * and SET_VARSIZE instead of relying on direct mentions of the struct fields.
831 * See varatt.h for details of the TOASTed form.
832 * ----------------
833 */
834typedef struct varlena
835{
836 char vl_len_[4]; /* Do not touch this field directly! */
837 char vl_dat[FLEXIBLE_ARRAY_MEMBER]; /* Data content is here */
839
840#define VARHDRSZ ((int32) sizeof(int32))
841
842/*
843 * These widely-used datatypes are just a varlena header and the data bytes.
844 * There is no terminating null or anything like that --- the data length is
845 * always VARSIZE_ANY_EXHDR(ptr).
846 */
848typedef varlena text;
849typedef varlena BpChar; /* blank-padded char, ie SQL char(n) */
850typedef varlena VarChar; /* var-length char, ie SQL varchar(n) */
851
852/*
853 * Specialized array types. These are physically laid out just the same
854 * as regular arrays (so that the regular array subscripting code works
855 * with them). They exist as distinct types mostly for historical reasons:
856 * they have nonstandard I/O behavior which we don't want to change for fear
857 * of breaking applications that look at the system catalogs. There is also
858 * an implementation issue for oidvector: it's part of the primary key for
859 * pg_proc, and we can't use the normal btree array support routines for that
860 * without circularity.
861 */
862typedef struct
863{
864 int32 vl_len_; /* these fields must match ArrayType! */
865 int ndim; /* always 1 for int2vector */
866 int32 dataoffset; /* always 0 for int2vector */
868 int dim1;
871} int2vector;
872
873typedef struct
874{
875 int32 vl_len_; /* these fields must match ArrayType! */
876 int ndim; /* always 1 for oidvector */
877 int32 dataoffset; /* always 0 for oidvector */
879 int dim1;
882} oidvector;
883
884/*
885 * Representation of a Name: effectively just a C string, but null-padded to
886 * exactly NAMEDATALEN bytes. The use of a struct is historical.
887 */
888typedef struct nameData
889{
892typedef NameData *Name;
893
894#define NameStr(name) ((name).data)
895
896
897/* ----------------------------------------------------------------
898 * Section 4: IsValid macros for system types
899 * ----------------------------------------------------------------
900 */
901/*
902 * BoolIsValid
903 * True iff bool is valid.
904 */
905#define BoolIsValid(boolean) ((boolean) == false || (boolean) == true)
906
907/*
908 * PointerIsAligned
909 * True iff pointer is properly aligned to point to the given type.
910 */
911#define PointerIsAligned(pointer, type) \
912 (((uintptr_t)(pointer) % (sizeof (type))) == 0)
913
914#define OffsetToPointer(base, offset) \
915 ((void *)((char *) base + offset))
916
917#define OidIsValid(objectId) ((bool) ((objectId) != InvalidOid))
918
919#define Oid8IsValid(objectId) ((bool) ((objectId) != InvalidOid8))
920
921#define RegProcedureIsValid(p) OidIsValid(p)
922
923
924/* ----------------------------------------------------------------
925 * Section 5: lengthof, alignment
926 * ----------------------------------------------------------------
927 */
928/*
929 * lengthof
930 * Number of elements in an array.
931 */
932#define lengthof(array) (sizeof (array) / sizeof ((array)[0]))
933
934/* ----------------
935 * Alignment macros: align a length or address appropriately for a given type.
936 * The fooALIGN() macros round up to a multiple of the required alignment,
937 * while the fooALIGN_DOWN() macros round down. The latter are more useful
938 * for problems like "how many X-sized structures will fit in a page?".
939 *
940 * NOTE: TYPEALIGN[_DOWN] will not work if ALIGNVAL is not a power of 2.
941 * That case seems extremely unlikely to be needed in practice, however.
942 *
943 * NOTE: MAXIMUM_ALIGNOF, and hence MAXALIGN(), intentionally exclude any
944 * larger-than-8-byte types the compiler might have.
945 * ----------------
946 */
947
948#define TYPEALIGN(ALIGNVAL,LEN) \
949 (((uintptr_t) (LEN) + ((ALIGNVAL) - 1)) & ~((uintptr_t) ((ALIGNVAL) - 1)))
950
951#define SHORTALIGN(LEN) TYPEALIGN(ALIGNOF_SHORT, (LEN))
952#define INTALIGN(LEN) TYPEALIGN(ALIGNOF_INT, (LEN))
953#define INT64ALIGN(LEN) TYPEALIGN(ALIGNOF_INT64_T, (LEN))
954#define DOUBLEALIGN(LEN) TYPEALIGN(ALIGNOF_DOUBLE, (LEN))
955#define MAXALIGN(LEN) TYPEALIGN(MAXIMUM_ALIGNOF, (LEN))
956/* MAXALIGN covers only built-in types, not buffers */
957#define BUFFERALIGN(LEN) TYPEALIGN(ALIGNOF_BUFFER, (LEN))
958#define CACHELINEALIGN(LEN) TYPEALIGN(PG_CACHE_LINE_SIZE, (LEN))
959
960#define TYPEALIGN_DOWN(ALIGNVAL,LEN) \
961 (((uintptr_t) (LEN)) & ~((uintptr_t) ((ALIGNVAL) - 1)))
962
963#define SHORTALIGN_DOWN(LEN) TYPEALIGN_DOWN(ALIGNOF_SHORT, (LEN))
964#define INTALIGN_DOWN(LEN) TYPEALIGN_DOWN(ALIGNOF_INT, (LEN))
965#define INT64ALIGN_DOWN(LEN) TYPEALIGN_DOWN(ALIGNOF_INT64_T, (LEN))
966#define DOUBLEALIGN_DOWN(LEN) TYPEALIGN_DOWN(ALIGNOF_DOUBLE, (LEN))
967#define MAXALIGN_DOWN(LEN) TYPEALIGN_DOWN(MAXIMUM_ALIGNOF, (LEN))
968#define BUFFERALIGN_DOWN(LEN) TYPEALIGN_DOWN(ALIGNOF_BUFFER, (LEN))
969
970/*
971 * The above macros will not work with types wider than uintptr_t, like with
972 * uint64 on 32-bit platforms. That's not problem for the usual use where a
973 * pointer or a length is aligned, but for the odd case that you need to
974 * align something (potentially) wider, use TYPEALIGN64.
975 */
976#define TYPEALIGN64(ALIGNVAL,LEN) \
977 (((uint64) (LEN) + ((ALIGNVAL) - 1)) & ~((uint64) ((ALIGNVAL) - 1)))
978
979/* we don't currently need wider versions of the other ALIGN macros */
980#define MAXALIGN64(LEN) TYPEALIGN64(MAXIMUM_ALIGNOF, (LEN))
981
982
983/* ----------------------------------------------------------------
984 * Section 6: assertions
985 * ----------------------------------------------------------------
986 */
987
988/*
989 * USE_ASSERT_CHECKING, if defined, turns on all the assertions.
990 * - plai 9/5/90
991 *
992 * It should _NOT_ be defined in releases or in benchmark copies
993 */
994
995/*
996 * Assert() can be used in both frontend and backend code. In frontend code it
997 * just calls the standard assert, if it's available. If use of assertions is
998 * not configured, it does nothing.
999 */
1000#ifndef USE_ASSERT_CHECKING
1001
1002#define Assert(condition) ((void)true)
1003#define AssertMacro(condition) ((void)true)
1004
1005#elif defined(FRONTEND)
1006
1007#define Assert(p) assert(p)
1008#define AssertMacro(p) ((void) assert(p))
1009
1010#else /* USE_ASSERT_CHECKING && !FRONTEND */
1011
1012/*
1013 * Assert
1014 * Generates a fatal exception if the given condition is false.
1015 */
1016#define Assert(condition) \
1017 do { \
1018 if (!(condition)) \
1019 ExceptionalCondition(#condition, __FILE__, __LINE__); \
1020 } while (0)
1021
1022/*
1023 * AssertMacro is the same as Assert but it's suitable for use in
1024 * expression-like macros, for example:
1025 *
1026 * #define foo(x) (AssertMacro(x != 0), bar(x))
1027 */
1028#define AssertMacro(condition) \
1029 ((void) ((condition) || \
1030 (ExceptionalCondition(#condition, __FILE__, __LINE__), 0)))
1031
1032#endif /* USE_ASSERT_CHECKING && !FRONTEND */
1033
1034/*
1035 * Check that `ptr' is `bndr' aligned.
1036 */
1037#define AssertPointerAlignment(ptr, bndr) \
1038 Assert(TYPEALIGN(bndr, (uintptr_t)(ptr)) == (uintptr_t)(ptr))
1039
1040/*
1041 * ExceptionalCondition is compiled into the backend whether or not
1042 * USE_ASSERT_CHECKING is defined, so as to support use of extensions
1043 * that are built with that #define with a backend that isn't. Hence,
1044 * we should declare it as long as !FRONTEND.
1045 */
1046#ifndef FRONTEND
1047pg_noreturn extern void ExceptionalCondition(const char *conditionName,
1048 const char *fileName, int lineNumber);
1049#endif
1050
1051/*
1052 * Macros to support compile-time assertion checks.
1053 *
1054 * If the "condition" (a compile-time-constant expression) evaluates to false,
1055 * throw a compile error using the "errmessage" (a string literal).
1056 */
1057
1058/*
1059 * We require C11 and C++11, so static_assert() is expected to be there.
1060 * StaticAssertDecl() was previously used for portability, but it's now just a
1061 * plain wrapper and doesn't need to be used in new code. static_assert() is
1062 * a "declaration", and so it must be placed where for example a variable
1063 * declaration would be valid. As long as we compile with
1064 * -Wno-declaration-after-statement, that also means it cannot be placed after
1065 * statements in a function.
1066 */
1067#define StaticAssertDecl(condition, errmessage) \
1068 static_assert(condition, errmessage)
1069
1070/*
1071 * StaticAssertStmt() was previously used to make static assertions work as a
1072 * statement, but its use is now deprecated.
1073 */
1074#define StaticAssertStmt(condition, errmessage) \
1075 do { static_assert(condition, errmessage); } while(0)
1076
1077/*
1078 * StaticAssertExpr() is for use in an expression.
1079 *
1080 * See <https://www.open-std.org/jtc1/sc22/wg14/www/docs/n3715.pdf> for some
1081 * rationale for the precise behavior of this implementation. See
1082 * <https://stackoverflow.com/questions/31311748> about the C++
1083 * implementation.
1084 *
1085 * For compilers that don't support this, we fall back on a kluge that assumes
1086 * the compiler will complain about a negative width for a struct bit-field.
1087 * This will not include a helpful error message, but it beats not getting an
1088 * error at all.
1089 */
1090#ifndef __cplusplus
1091#if !defined(_MSC_VER) || _MSC_VER >= 1933
1092#define StaticAssertExpr(condition, errmessage) \
1093 ((void) sizeof(struct {static_assert(condition, errmessage); char a;}))
1094#else /* _MSC_VER < 1933 */
1095/*
1096 * This compiler is buggy and fails to compile the previous variant; use a
1097 * fallback implementation.
1098 */
1099#define StaticAssertExpr(condition, errmessage) \
1100 ((void) sizeof(struct { int static_assert_failure : (condition) ? 1 : -1; }))
1101#endif /* _MSC_VER < 1933 */
1102#else /* __cplusplus */
1103#define StaticAssertExpr(condition, errmessage) \
1104 ([]{static_assert(condition, errmessage);})
1105#endif
1106
1107
1108/*
1109 * Compile-time checks that a variable (or expression) has the specified type.
1110 *
1111 * StaticAssertVariableIsOfType() can be used as a declaration.
1112 * StaticAssertVariableIsOfTypeMacro() is intended for use in macros, eg
1113 * #define foo(x) (StaticAssertVariableIsOfTypeMacro(x, int), bar(x))
1114 *
1115 * If we don't have __builtin_types_compatible_p, we can still assert that
1116 * the types have the same size. This is far from ideal (especially on 32-bit
1117 * platforms) but it provides at least some coverage.
1118 */
1119#ifdef HAVE__BUILTIN_TYPES_COMPATIBLE_P
1120#define StaticAssertVariableIsOfType(varname, typename) \
1121 StaticAssertDecl(__builtin_types_compatible_p(typeof(varname), typename), \
1122 CppAsString(varname) " does not have type " CppAsString(typename))
1123#define StaticAssertVariableIsOfTypeMacro(varname, typename) \
1124 (StaticAssertExpr(__builtin_types_compatible_p(typeof(varname), typename), \
1125 CppAsString(varname) " does not have type " CppAsString(typename)))
1126#else /* !HAVE__BUILTIN_TYPES_COMPATIBLE_P */
1127#define StaticAssertVariableIsOfType(varname, typename) \
1128 StaticAssertDecl(sizeof(varname) == sizeof(typename), \
1129 CppAsString(varname) " does not have type " CppAsString(typename))
1130#define StaticAssertVariableIsOfTypeMacro(varname, typename) \
1131 (StaticAssertExpr(sizeof(varname) == sizeof(typename), \
1132 CppAsString(varname) " does not have type " CppAsString(typename)))
1133#endif /* HAVE__BUILTIN_TYPES_COMPATIBLE_P */
1134
1135
1136/* ----------------------------------------------------------------
1137 * Section 7: widely useful macros
1138 * ----------------------------------------------------------------
1139 */
1140/*
1141 * Max
1142 * Return the maximum of two numbers.
1143 */
1144#define Max(x, y) ((x) > (y) ? (x) : (y))
1145
1146/*
1147 * Min
1148 * Return the minimum of two numbers.
1149 */
1150#define Min(x, y) ((x) < (y) ? (x) : (y))
1151
1152
1153/* Get a bit mask of the bits set in non-size_t aligned addresses */
1154#define SIZE_T_ALIGN_MASK (sizeof(size_t) - 1)
1155
1156/*
1157 * MemSet
1158 * Exactly the same as standard library function memset(), but considerably
1159 * faster for zeroing small size_t-aligned structures (such as parsetree
1160 * nodes). This has to be a macro because the main point is to avoid
1161 * function-call overhead. However, we have also found that the loop is
1162 * faster than native libc memset() on some platforms, even those with
1163 * assembler memset() functions. More research needs to be done, perhaps
1164 * with MEMSET_LOOP_LIMIT tests in configure.
1165 */
1166#define MemSet(start, val, len) \
1167 do \
1168 { \
1169 /* must be void* because we don't know if it is size_t aligned yet */ \
1170 void *_vstart = (void *) (start); \
1171 int _val = (val); \
1172 Size _len = (len); \
1173\
1174 if ((((uintptr_t) _vstart) & SIZE_T_ALIGN_MASK) == 0 && \
1175 (_len & SIZE_T_ALIGN_MASK) == 0 && \
1176 _val == 0 && \
1177 _len <= MEMSET_LOOP_LIMIT && \
1178 /* \
1179 * If MEMSET_LOOP_LIMIT == 0, optimizer should find \
1180 * the whole "if" false at compile time. \
1181 */ \
1182 MEMSET_LOOP_LIMIT != 0) \
1183 { \
1184 size_t *_start = (size_t *) _vstart; \
1185 size_t *_stop = (size_t *) ((char *) _start + _len); \
1186 while (_start < _stop) \
1187 *_start++ = 0; \
1188 } \
1189 else \
1190 memset(_vstart, _val, _len); \
1191 } while (0)
1192
1193/*
1194 * MemSetAligned is the same as MemSet except it omits the test to see if
1195 * "start" is size_t-aligned. This is okay to use if the caller knows
1196 * a-priori that the pointer is suitably aligned (typically, because he just
1197 * got it from palloc(), which always delivers a max-aligned pointer).
1198 */
1199#define MemSetAligned(start, val, len) \
1200 do \
1201 { \
1202 size_t *_start = (size_t *) (start); \
1203 int _val = (val); \
1204 Size _len = (len); \
1205\
1206 if ((_len & SIZE_T_ALIGN_MASK) == 0 && \
1207 _val == 0 && \
1208 _len <= MEMSET_LOOP_LIMIT && \
1209 MEMSET_LOOP_LIMIT != 0) \
1210 { \
1211 size_t *_stop = (size_t *) ((char *) _start + _len); \
1212 while (_start < _stop) \
1213 *_start++ = 0; \
1214 } \
1215 else \
1216 memset(_start, _val, _len); \
1217 } while (0)
1218
1219
1220/*
1221 * Macros for range-checking float values before converting to integer.
1222 * We must be careful here that the boundary values are expressed exactly
1223 * in the float domain. PG_INTnn_MIN is an exact power of 2, so it will
1224 * be represented exactly; but PG_INTnn_MAX isn't, and might get rounded
1225 * off, so avoid using that.
1226 * The input must be rounded to an integer beforehand, typically with rint(),
1227 * else we might draw the wrong conclusion about close-to-the-limit values.
1228 * These macros will do the right thing for Inf, but not necessarily for NaN,
1229 * so check isnan(num) first if that's a possibility.
1231#define FLOAT4_FITS_IN_INT16(num) \
1232 ((num) >= (float4) PG_INT16_MIN && (num) < -((float4) PG_INT16_MIN))
1233#define FLOAT4_FITS_IN_INT32(num) \
1234 ((num) >= (float4) PG_INT32_MIN && (num) < -((float4) PG_INT32_MIN))
1235#define FLOAT4_FITS_IN_INT64(num) \
1236 ((num) >= (float4) PG_INT64_MIN && (num) < -((float4) PG_INT64_MIN))
1237#define FLOAT8_FITS_IN_INT16(num) \
1238 ((num) >= (float8) PG_INT16_MIN && (num) < -((float8) PG_INT16_MIN))
1239#define FLOAT8_FITS_IN_INT32(num) \
1240 ((num) >= (float8) PG_INT32_MIN && (num) < -((float8) PG_INT32_MIN))
1241#define FLOAT8_FITS_IN_INT64(num) \
1242 ((num) >= (float8) PG_INT64_MIN && (num) < -((float8) PG_INT64_MIN))
1243
1244
1245/* ----------------------------------------------------------------
1246 * Section 8: random stuff
1247 * ----------------------------------------------------------------
1248 */
1249
1250/*
1251 * Invert the sign of a qsort-style comparison result, ie, exchange negative
1252 * and positive integer values, being careful not to get the wrong answer
1253 * for INT_MIN. The argument should be an integral variable.
1254 */
1255#define INVERT_COMPARE_RESULT(var) \
1256 ((var) = ((var) < 0) ? 1 : -(var))
1257
1258/*
1259 * Use this, not "char buf[BLCKSZ]", to declare a field or local variable
1260 * holding a page buffer, if that page might be accessed as a page. Otherwise
1261 * the variable might be under-aligned, causing problems on alignment-picky
1262 * hardware.
1264typedef struct PGAlignedBlock
1265{
1266 alignas(MAXIMUM_ALIGNOF) char data[BLCKSZ];
1268
1269/*
1270 * alignas with extended alignments is buggy in g++ < 9. As a simple
1271 * workaround, we disable these definitions in that case.
1272 *
1273 * <https://gcc.gnu.org/bugzilla/show_bug.cgi?id=89357>
1274 */
1275#if !(defined(__cplusplus) && defined(__GNUC__) && !defined(__clang__) && __GNUC__ < 9)
1276
1277/*
1278 * Use this to declare a field or local variable holding a page buffer, if that
1279 * page might be accessed as a page or passed to an SMgr I/O function. If
1280 * allocating using the MemoryContext API, the aligned allocation functions
1281 * should be used with PG_IO_ALIGN_SIZE. This alignment may be more efficient
1282 * for I/O in general, but may be strictly required on some platforms when
1283 * using direct I/O.
1285typedef struct PGIOAlignedBlock
1286{
1287 alignas(PG_IO_ALIGN_SIZE) char data[BLCKSZ];
1289
1290/* Same, but for an XLOG_BLCKSZ-sized buffer */
1292{
1293 alignas(PG_IO_ALIGN_SIZE) char data[XLOG_BLCKSZ];
1295
1296#else /* (g++ < 9) */
1297
1298/* Allow these types to be used as abstract types when using old g++ */
1299typedef struct PGIOAlignedBlock PGIOAlignedBlock;
1301
1302#endif /* !(g++ < 9) */
1304/* msb for char */
1305#define HIGHBIT (0x80)
1306#define IS_HIGHBIT_SET(ch) ((unsigned char)(ch) & HIGHBIT)
1307
1308/*
1309 * Support macros for escaping strings. escape_backslash should be true
1310 * if generating a non-standard-conforming string. Prefixing a string
1311 * with ESCAPE_STRING_SYNTAX guarantees it is non-standard-conforming.
1312 * Beware of multiple evaluation of the "ch" argument!
1313 */
1314#define SQL_STR_DOUBLE(ch, escape_backslash) \
1315 ((ch) == '\'' || ((ch) == '\\' && (escape_backslash)))
1316
1317#define ESCAPE_STRING_SYNTAX 'E'
1320#define STATUS_OK (0)
1321#define STATUS_ERROR (-1)
1322#define STATUS_EOF (-2)
1323
1324/*
1325 * gettext support
1326 */
1328#ifndef ENABLE_NLS
1329/* stuff we'd otherwise get from <libintl.h> */
1330#define gettext(x) (x)
1331#define dgettext(d,x) (x)
1332#define ngettext(s,p,n) ((n) == 1 ? (s) : (p))
1333#define dngettext(d,s,p,n) ((n) == 1 ? (s) : (p))
1334#endif
1335
1336#define _(x) gettext(x)
1337
1338/*
1339 * Use this to mark string constants as needing translation at some later
1340 * time, rather than immediately. This is useful for cases where you need
1341 * access to the original string and translated string, and for cases where
1342 * immediate translation is not possible, like when initializing global
1343 * variables.
1345 * https://www.gnu.org/software/gettext/manual/html_node/Special-cases.html
1346 */
1347#define gettext_noop(x) (x)
1348
1349/*
1350 * To better support parallel installations of major PostgreSQL
1351 * versions as well as parallel installations of major library soname
1352 * versions, we mangle the gettext domain name by appending those
1353 * version numbers. The coding rule ought to be that wherever the
1354 * domain name is mentioned as a literal, it must be wrapped into
1355 * PG_TEXTDOMAIN(). The macros below do not work on non-literals; but
1356 * that is somewhat intentional because it avoids having to worry
1357 * about multiple states of premangling and postmangling as the values
1358 * are being passed around.
1359 *
1360 * Make sure this matches the installation rules in nls-global.mk.
1361 */
1362#ifdef SO_MAJOR_VERSION
1363#define PG_TEXTDOMAIN(domain) (domain CppAsString2(SO_MAJOR_VERSION) "-" PG_MAJORVERSION)
1364#else
1365#define PG_TEXTDOMAIN(domain) (domain "-" PG_MAJORVERSION)
1366#endif
1367
1368/*
1369 * Macro that allows to cast constness and volatile away from an expression, but doesn't
1370 * allow changing the underlying type. Enforcement of the latter
1371 * currently only works for gcc like compilers.
1372 *
1373 * Please note IT IS NOT SAFE to cast constness away if the result will ever
1374 * be modified (it would be undefined behaviour). Doing so anyway can cause
1375 * compiler misoptimizations or runtime crashes (modifying readonly memory).
1376 * It is only safe to use when the result will not be modified, but API
1377 * design or language restrictions prevent you from declaring that
1378 * (e.g. because a function returns both const and non-const variables).
1379 *
1380 * Note that this only works in function scope, not for global variables (it'd
1381 * be nice, but not trivial, to improve that).
1382 */
1383#if defined(__cplusplus)
1384#define unconstify(underlying_type, expr) const_cast<underlying_type>(expr)
1385#define unvolatize(underlying_type, expr) const_cast<underlying_type>(expr)
1386#else
1387#define unconstify(underlying_type, expr) \
1388 (StaticAssertVariableIsOfTypeMacro(expr, const underlying_type), \
1389 (underlying_type) (expr))
1390#define unvolatize(underlying_type, expr) \
1391 (StaticAssertVariableIsOfTypeMacro(expr, volatile underlying_type), \
1392 (underlying_type) (expr))
1393#endif
1394
1395/*
1396 * SSE2 instructions are part of the spec for the 64-bit x86 ISA. We assume
1397 * that compilers targeting this architecture understand SSE2 intrinsics.
1398 */
1399#if defined(__x86_64__)
1400#define USE_SSE2
1401
1402#else /* ! x86_64 */
1403
1404/*
1405 * In "universal" macOS builds, it's possible for AVX-related symbols to
1406 * get defined if the build host is x86_64, but we mustn't try to build
1407 * that code when cross-compiling to aarch64.
1408 */
1409#undef USE_AVX2_WITH_RUNTIME_CHECK
1410#undef USE_AVX512_CRC32C_WITH_RUNTIME_CHECK
1411#undef USE_AVX512_POPCNT_WITH_RUNTIME_CHECK
1412
1413/*
1414 * We use the Neon instructions if the compiler provides access to them (as
1415 * indicated by __ARM_NEON) and we are on aarch64. While Neon support is
1416 * technically optional for aarch64, it appears that all available 64-bit
1417 * hardware does have it. Neon exists in some 32-bit hardware too, but we
1418 * could not realistically use it there without a run-time check, which seems
1419 * not worth the trouble for now.
1420 */
1421#if defined(__aarch64__) && defined(__ARM_NEON)
1422#define USE_NEON
1423#endif
1424#endif /* x86_64 */
1425
1426/* ----------------------------------------------------------------
1427 * Section 9: system-specific hacks
1428 *
1429 * This should be limited to things that absolutely have to be
1430 * included in every source file. The port-specific header file
1431 * is usually a better place for this sort of thing.
1432 * ----------------------------------------------------------------
1433 */
1434
1435/*
1436 * NOTE: this is also used for opening text files.
1437 * WIN32 treats Control-Z as EOF in files opened in text mode.
1438 * Therefore, we open files in binary mode on Win32 so we can read
1439 * literal control-Z. The other affect is that we see CRLF, but
1440 * that is OK because we can already handle those cleanly.
1441 */
1442#if defined(WIN32) || defined(__CYGWIN__)
1443#define PG_BINARY O_BINARY
1444#define PG_BINARY_A "ab"
1445#define PG_BINARY_R "rb"
1446#define PG_BINARY_W "wb"
1447#else
1448#define PG_BINARY 0
1449#define PG_BINARY_A "a"
1450#define PG_BINARY_R "r"
1451#define PG_BINARY_W "w"
1452#endif
1453
1454/*
1455 * Provide prototypes for routines not present in a particular machine's
1456 * standard C library.
1457 */
1458
1459#if !HAVE_DECL_FDATASYNC
1460extern int fdatasync(int fd);
1461#endif
1462
1463/*
1464 * Thin wrappers that convert strings to exactly 64-bit integers, matching our
1465 * definition of int64. (For the naming, compare that POSIX has
1466 * strtoimax()/strtoumax() which return intmax_t/uintmax_t.)
1467 */
1468#if SIZEOF_LONG == 8
1469#define strtoi64(str, endptr, base) ((int64) strtol(str, endptr, base))
1470#define strtou64(str, endptr, base) ((uint64) strtoul(str, endptr, base))
1471#elif SIZEOF_LONG_LONG == 8
1472#define strtoi64(str, endptr, base) ((int64) strtoll(str, endptr, base))
1473#define strtou64(str, endptr, base) ((uint64) strtoull(str, endptr, base))
1474#else
1475#error "cannot find integer type of the same size as int64_t"
1476#endif
1477
1478/*
1479 * Similarly, wrappers around labs()/llabs() matching our int64.
1480 */
1481#if SIZEOF_LONG == 8
1482#define i64abs(i) ((int64) labs(i))
1483#elif SIZEOF_LONG_LONG == 8
1484#define i64abs(i) ((int64) llabs(i))
1485#else
1486#error "cannot find integer type of the same size as int64_t"
1487#endif
1488
1489/*
1490 * Use "extern PGDLLIMPORT ..." to declare variables that are defined
1491 * in the core backend and need to be accessible by loadable modules.
1492 * No special marking is required on most ports.
1493 */
1494#ifndef PGDLLIMPORT
1495#define PGDLLIMPORT
1496#endif
1497
1498/*
1499 * Use "extern PGDLLEXPORT ..." to declare functions that are defined in
1500 * loadable modules and need to be callable by the core backend or other
1501 * loadable modules.
1502 * If the compiler knows __attribute__((visibility("*"))), we use that,
1503 * unless we already have a platform-specific definition. Otherwise,
1504 * no special marking is required.
1505 */
1506#ifndef PGDLLEXPORT
1507#ifdef HAVE_VISIBILITY_ATTRIBUTE
1508#define PGDLLEXPORT __attribute__((visibility("default")))
1509#else
1510#define PGDLLEXPORT
1511#endif
1512#endif
1513
1514/*
1515 * Platform independent struct representing additional information about the
1516 * received signal. If the system does not support the extended information,
1517 * or a field does not apply to the signal, the value is instead reset to the
1518 * documented default value.
1519 */
1521typedef struct pg_signal_info
1522{
1523 uint32_t pid; /* pid of sending process or 0 if unknown */
1524 uint32_t uid; /* uid of sending process; only meaningful
1525 * when pid is not 0 */
1527
1528/*
1529 * The following is used as the arg list for signal handlers. These days we
1530 * use the same argument to all signal handlers and hide the difference
1531 * between platforms in wrapper functions.
1532 *
1533 * SIGNAL_ARGS just exists separately from the pqsignal() definition for
1534 * historical reasons.
1535 */
1536#define SIGNAL_ARGS int postgres_signal_arg, const pg_signal_info *pg_siginfo
1537
1538/*
1539 * When there is no sigsetjmp, its functionality is provided by plain
1540 * setjmp. We now support the case only on Windows. However, it seems
1541 * that MinGW-64 has some longstanding issues in its setjmp support,
1542 * so on that toolchain we cheat and use gcc's builtins.
1543 */
1544#ifdef WIN32
1545#ifdef __MINGW64__
1546typedef intptr_t sigjmp_buf[5];
1547#define sigsetjmp(x,y) __builtin_setjmp(x)
1548#define siglongjmp __builtin_longjmp
1549#else /* !__MINGW64__ */
1550#define sigjmp_buf jmp_buf
1551#define sigsetjmp(x,y) setjmp(x)
1552#define siglongjmp longjmp
1553#endif /* __MINGW64__ */
1554#endif /* WIN32 */
1555
1556/* /port compatibility functions */
1557#include "port.h"
1558
1559/*
1560 * char16_t and char32_t
1561 * Unicode code points.
1562 *
1563 * uchar.h should always be available in C11, but it's not available on
1564 * Mac. However, these types are keywords in C++11, so when using C++, we
1565 * can't redefine the types.
1566 *
1567 * XXX: when uchar.h is available everywhere, we can remove this check and
1568 * just include uchar.h unconditionally.
1569 *
1570 * XXX: this section is out of place because uchar.h needs to be included
1571 * after port.h, due to an interaction with win32_port.h in some cases.
1572 */
1573#ifdef HAVE_UCHAR_H
1574#include <uchar.h>
1575#else
1576#ifndef __cplusplus
1577typedef uint16_t char16_t;
1578typedef uint32_t char32_t;
1579#endif
1580#endif
1581
1582/* IWYU pragma: end_exports */
1583
1584#endif /* C_H */
static Datum values[MAXATTR]
Definition bootstrap.c:190
uint64 Oid8
Definition c.h:815
NameData * Name
Definition c.h:892
int fdatasync(int fd)
uint8_t uint8
Definition c.h:681
uint32 SubTransactionId
Definition c.h:799
#define pg_noreturn
Definition c.h:249
pg_noreturn void ExceptionalCondition(const char *conditionName, const char *fileName, int lineNumber)
Definition assert.c:30
varlena BpChar
Definition c.h:849
int64_t int64
Definition c.h:680
Oid regproc
Definition c.h:792
double float8
Definition c.h:773
TransactionId MultiXactId
Definition c.h:805
#define FLEXIBLE_ARRAY_MEMBER
Definition c.h:617
int16_t int16
Definition c.h:678
regproc RegProcedure
Definition c.h:793
int8_t int8
Definition c.h:677
uint64 MultiXactOffset
Definition c.h:807
int32_t int32
Definition c.h:679
uint64_t uint64
Definition c.h:684
varlena bytea
Definition c.h:847
uint16_t uint16
Definition c.h:682
uint32_t uint32
Definition c.h:683
uint16_t char16_t
Definition c.h:1574
unsigned int Index
Definition c.h:757
float float4
Definition c.h:772
uint32 LocalTransactionId
Definition c.h:797
void * Pointer
Definition c.h:674
uint32 CommandId
Definition c.h:809
uint32 TransactionId
Definition c.h:795
signed int Offset
Definition c.h:767
uint32_t char32_t
Definition c.h:1575
varlena VarChar
Definition c.h:850
varlena text
Definition c.h:848
void(* pg_funcptr_t)(void)
Definition c.h:607
size_t Size
Definition c.h:748
struct nameData NameData
#define NAMEDATALEN
#define PG_IO_ALIGN_SIZE
unsigned int Oid
static int fd(const char *x, int i)
static int fb(int x)
char data[BLCKSZ]
Definition c.h:1263
char data[XLOG_BLCKSZ]
Definition c.h:1290
char data[BLCKSZ]
Definition c.h:1284
int32 vl_len_
Definition c.h:864
int ndim
Definition c.h:865
int dim1
Definition c.h:868
Oid elemtype
Definition c.h:867
int32 dataoffset
Definition c.h:866
int lbound1
Definition c.h:869
Definition c.h:889
char data[NAMEDATALEN]
Definition c.h:890
Definition c.h:874
int dim1
Definition c.h:879
int32 dataoffset
Definition c.h:877
Oid elemtype
Definition c.h:878
int lbound1
Definition c.h:880
int ndim
Definition c.h:876
int32 vl_len_
Definition c.h:875
uint32_t pid
Definition c.h:1520
uint32_t uid
Definition c.h:1521
Definition c.h:835
char vl_len_[4]
Definition c.h:836
char vl_dat[FLEXIBLE_ARRAY_MEMBER]
Definition c.h:837