PostgreSQL Source Code git master
mcxt.c File Reference
#include "postgres.h"
#include "mb/pg_wchar.h"
#include "miscadmin.h"
#include "nodes/pg_list.h"
#include "storage/lwlock.h"
#include "storage/ipc.h"
#include "utils/dsa.h"
#include "utils/hsearch.h"
#include "utils/memdebug.h"
#include "utils/memutils.h"
#include "utils/memutils_internal.h"
#include "utils/memutils_memorychunk.h"
Include dependency graph for mcxt.c:

Go to the source code of this file.

Macros

#define BOGUS_MCTX(id)
 
#define AssertNotInCriticalSection(context)    Assert(CritSectionCount == 0 || (context)->allowInCritSection)
 
#define MCXT_METHOD(pointer, method)    mcxt_methods[GetMemoryChunkMethodID(pointer)].method
 

Typedefs

typedef enum PrintDestination PrintDestination
 

Enumerations

enum  PrintDestination { PRINT_STATS_TO_STDERR = 0 , PRINT_STATS_TO_LOGS , PRINT_STATS_NONE }
 

Functions

static void BogusFree (void *pointer)
 
static void * BogusRealloc (void *pointer, Size size, int flags)
 
static MemoryContext BogusGetChunkContext (void *pointer)
 
static Size BogusGetChunkSpace (void *pointer)
 
static void MemoryContextDeleteOnly (MemoryContext context)
 
static void MemoryContextCallResetCallbacks (MemoryContext context)
 
static void MemoryContextStatsInternal (MemoryContext context, int level, int max_level, int max_children, MemoryContextCounters *totals, PrintDestination print_location, int *num_contexts)
 
static void MemoryContextStatsPrint (MemoryContext context, void *passthru, const char *stats_string, bool print_to_stderr)
 
static void PublishMemoryContext (MemoryStatsEntry *memcxt_info, int curr_id, MemoryContext context, List *path, MemoryContextCounters stat, int num_contexts, dsa_area *area, int max_levels)
 
static void compute_contexts_count_and_ids (List *contexts, HTAB *context_id_lookup, int *stats_count, bool summary)
 
static Listcompute_context_path (MemoryContext c, HTAB *context_id_lookup)
 
static void free_memorycontextstate_dsa (dsa_area *area, int total_stats, dsa_pointer prev_dsa_pointer)
 
static void end_memorycontext_reporting (void)
 
static MemoryContextMethodID GetMemoryChunkMethodID (const void *pointer)
 
static uint64 GetMemoryChunkHeader (const void *pointer)
 
static MemoryContext MemoryContextTraverseNext (MemoryContext curr, MemoryContext top)
 
void MemoryContextInit (void)
 
void MemoryContextReset (MemoryContext context)
 
void MemoryContextResetOnly (MemoryContext context)
 
void MemoryContextResetChildren (MemoryContext context)
 
void MemoryContextDelete (MemoryContext context)
 
void MemoryContextDeleteChildren (MemoryContext context)
 
void MemoryContextRegisterResetCallback (MemoryContext context, MemoryContextCallback *cb)
 
void MemoryContextSetIdentifier (MemoryContext context, const char *id)
 
void MemoryContextSetParent (MemoryContext context, MemoryContext new_parent)
 
void MemoryContextAllowInCriticalSection (MemoryContext context, bool allow)
 
MemoryContext GetMemoryChunkContext (void *pointer)
 
Size GetMemoryChunkSpace (void *pointer)
 
MemoryContext MemoryContextGetParent (MemoryContext context)
 
bool MemoryContextIsEmpty (MemoryContext context)
 
Size MemoryContextMemAllocated (MemoryContext context, bool recurse)
 
void MemoryContextMemConsumed (MemoryContext context, MemoryContextCounters *consumed)
 
void MemoryContextStats (MemoryContext context)
 
void MemoryContextStatsDetail (MemoryContext context, int max_level, int max_children, bool print_to_stderr)
 
void MemoryContextCreate (MemoryContext node, NodeTag tag, MemoryContextMethodID method_id, MemoryContext parent, const char *name)
 
void * MemoryContextAllocationFailure (MemoryContext context, Size size, int flags)
 
void MemoryContextSizeFailure (MemoryContext context, Size size, int flags)
 
void * MemoryContextAlloc (MemoryContext context, Size size)
 
void * MemoryContextAllocZero (MemoryContext context, Size size)
 
void * MemoryContextAllocExtended (MemoryContext context, Size size, int flags)
 
void HandleLogMemoryContextInterrupt (void)
 
void HandleGetMemoryContextInterrupt (void)
 
void ProcessLogMemoryContextInterrupt (void)
 
void ProcessGetMemoryContextInterrupt (void)
 
void AtProcExit_memstats_cleanup (int code, Datum arg)
 
void * palloc (Size size)
 
void * palloc0 (Size size)
 
void * palloc_extended (Size size, int flags)
 
void * MemoryContextAllocAligned (MemoryContext context, Size size, Size alignto, int flags)
 
void * palloc_aligned (Size size, Size alignto, int flags)
 
void pfree (void *pointer)
 
void * repalloc (void *pointer, Size size)
 
void * repalloc_extended (void *pointer, Size size, int flags)
 
void * repalloc0 (void *pointer, Size oldsize, Size size)
 
void * MemoryContextAllocHuge (MemoryContext context, Size size)
 
void * repalloc_huge (void *pointer, Size size)
 
char * MemoryContextStrdup (MemoryContext context, const char *string)
 
char * pstrdup (const char *in)
 
char * pnstrdup (const char *in, Size len)
 
char * pchomp (const char *in)
 

Variables

static const MemoryContextMethods mcxt_methods []
 
MemoryContext CurrentMemoryContext = NULL
 
MemoryContext TopMemoryContext = NULL
 
MemoryContext ErrorContext = NULL
 
MemoryContext PostmasterContext = NULL
 
MemoryContext CacheMemoryContext = NULL
 
MemoryContext MessageContext = NULL
 
MemoryContext TopTransactionContext = NULL
 
MemoryContext CurTransactionContext = NULL
 
MemoryContext PortalContext = NULL
 
dsa_areaMemoryStatsDsaArea = NULL
 

Macro Definition Documentation

◆ AssertNotInCriticalSection

#define AssertNotInCriticalSection (   context)     Assert(CritSectionCount == 0 || (context)->allowInCritSection)

Definition at line 206 of file mcxt.c.

◆ BOGUS_MCTX

#define BOGUS_MCTX (   id)
Value:
[id].free_p = BogusFree, \
[id].realloc = BogusRealloc, \
[id].get_chunk_context = BogusGetChunkContext, \
[id].get_chunk_space = BogusGetChunkSpace
static void * BogusRealloc(void *pointer, Size size, int flags)
Definition: mcxt.c:324
static Size BogusGetChunkSpace(void *pointer)
Definition: mcxt.c:340
static void BogusFree(void *pointer)
Definition: mcxt.c:317
static MemoryContext BogusGetChunkContext(void *pointer)
Definition: mcxt.c:332

Definition at line 45 of file mcxt.c.

◆ MCXT_METHOD

#define MCXT_METHOD (   pointer,
  method 
)     mcxt_methods[GetMemoryChunkMethodID(pointer)].method

Definition at line 213 of file mcxt.c.

Typedef Documentation

◆ PrintDestination

Enumeration Type Documentation

◆ PrintDestination

Enumerator
PRINT_STATS_TO_STDERR 
PRINT_STATS_TO_LOGS 
PRINT_STATS_NONE 

Definition at line 148 of file mcxt.c.

149{
PrintDestination
Definition: mcxt.c:149
@ PRINT_STATS_TO_LOGS
Definition: mcxt.c:151
@ PRINT_STATS_NONE
Definition: mcxt.c:152
@ PRINT_STATS_TO_STDERR
Definition: mcxt.c:150

Function Documentation

◆ AtProcExit_memstats_cleanup()

void AtProcExit_memstats_cleanup ( int  code,
Datum  arg 
)

Definition at line 1911 of file mcxt.c.

1912{
1913 int idx = MyProcNumber;
1914
1916 return;
1917
1919
1920 if (!DsaPointerIsValid(memCxtState[idx].memstats_dsa_pointer))
1921 {
1922 LWLockRelease(&memCxtState[idx].lw_lock);
1923 return;
1924 }
1925
1926 /* If the dsa mapping could not be found, attach to the area */
1927 if (MemoryStatsDsaArea == NULL)
1929
1930 /*
1931 * Free the memory context statistics, free the name, ident and path
1932 * pointers before freeing the pointer that contains these pointers and
1933 * integer statistics.
1934 */
1936 memCxtState[idx].memstats_dsa_pointer);
1937
1939 LWLockRelease(&memCxtState[idx].lw_lock);
1940}
Datum idx(PG_FUNCTION_ARGS)
Definition: _int_op.c:262
dsa_area * dsa_attach(dsa_handle handle)
Definition: dsa.c:510
void dsa_detach(dsa_area *area)
Definition: dsa.c:1952
#define DSA_HANDLE_INVALID
Definition: dsa.h:139
#define DsaPointerIsValid(x)
Definition: dsa.h:106
ProcNumber MyProcNumber
Definition: globals.c:91
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1182
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1902
@ LW_EXCLUSIVE
Definition: lwlock.h:114
static void free_memorycontextstate_dsa(dsa_area *area, int total_stats, dsa_pointer prev_dsa_pointer)
Definition: mcxt.c:1883
dsa_area * MemoryStatsDsaArea
Definition: mcxt.c:175
struct MemoryStatsBackendState * memCxtState
Definition: mcxtfuncs.c:37
struct MemoryStatsCtl * memCxtArea
Definition: mcxtfuncs.c:38
dsa_handle memstats_dsa_handle
Definition: memutils.h:366

References dsa_attach(), dsa_detach(), DSA_HANDLE_INVALID, DsaPointerIsValid, free_memorycontextstate_dsa(), idx(), LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), memCxtArea, memCxtState, MemoryStatsDsaArea, MemoryStatsCtl::memstats_dsa_handle, and MyProcNumber.

Referenced by BaseInit().

◆ BogusFree()

static void BogusFree ( void *  pointer)
static

Definition at line 317 of file mcxt.c.

318{
319 elog(ERROR, "pfree called with invalid pointer %p (header 0x%016" PRIx64 ")",
320 pointer, GetMemoryChunkHeader(pointer));
321}
#define ERROR
Definition: elog.h:39
#define elog(elevel,...)
Definition: elog.h:225
static uint64 GetMemoryChunkHeader(const void *pointer)
Definition: mcxt.c:251

References elog, ERROR, and GetMemoryChunkHeader().

◆ BogusGetChunkContext()

static MemoryContext BogusGetChunkContext ( void *  pointer)
static

Definition at line 332 of file mcxt.c.

333{
334 elog(ERROR, "GetMemoryChunkContext called with invalid pointer %p (header 0x%016" PRIx64 ")",
335 pointer, GetMemoryChunkHeader(pointer));
336 return NULL; /* keep compiler quiet */
337}

References elog, ERROR, and GetMemoryChunkHeader().

◆ BogusGetChunkSpace()

static Size BogusGetChunkSpace ( void *  pointer)
static

Definition at line 340 of file mcxt.c.

341{
342 elog(ERROR, "GetMemoryChunkSpace called with invalid pointer %p (header 0x%016" PRIx64 ")",
343 pointer, GetMemoryChunkHeader(pointer));
344 return 0; /* keep compiler quiet */
345}

References elog, ERROR, and GetMemoryChunkHeader().

◆ BogusRealloc()

static void * BogusRealloc ( void *  pointer,
Size  size,
int  flags 
)
static

Definition at line 324 of file mcxt.c.

325{
326 elog(ERROR, "repalloc called with invalid pointer %p (header 0x%016" PRIx64 ")",
327 pointer, GetMemoryChunkHeader(pointer));
328 return NULL; /* keep compiler quiet */
329}

References elog, ERROR, and GetMemoryChunkHeader().

◆ compute_context_path()

static List * compute_context_path ( MemoryContext  c,
HTAB context_id_lookup 
)
static

Definition at line 1719 of file mcxt.c.

1720{
1721 bool found;
1722 List *path = NIL;
1723 MemoryContext cur_context;
1724
1725 for (cur_context = c; cur_context != NULL; cur_context = cur_context->parent)
1726 {
1727 MemoryStatsContextId *cur_entry;
1728
1729 cur_entry = hash_search(context_id_lookup, &cur_context, HASH_FIND, &found);
1730
1731 if (!found)
1732 elog(ERROR, "hash table corrupted, can't construct path value");
1733
1734 path = lcons_int(cur_entry->context_id, path);
1735 }
1736
1737 return path;
1738}
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:956
@ HASH_FIND
Definition: hsearch.h:113
List * lcons_int(int datum, List *list)
Definition: list.c:513
#define NIL
Definition: pg_list.h:68
char * c
Definition: pg_list.h:54
MemoryContext parent
Definition: memnodes.h:127

References MemoryStatsContextId::context_id, elog, ERROR, HASH_FIND, hash_search(), lcons_int(), NIL, and MemoryContextData::parent.

Referenced by ProcessGetMemoryContextInterrupt().

◆ compute_contexts_count_and_ids()

static void compute_contexts_count_and_ids ( List contexts,
HTAB context_id_lookup,
int *  stats_count,
bool  summary 
)
static

Definition at line 1745 of file mcxt.c.

1747{
1749 {
1750 MemoryStatsContextId *entry;
1751 bool found;
1752
1753 entry = (MemoryStatsContextId *) hash_search(context_id_lookup, &cur,
1754 HASH_ENTER, &found);
1755 Assert(!found);
1756
1757 /*
1758 * context id starts with 1 so increment the stats_count before
1759 * assigning.
1760 */
1761 entry->context_id = ++(*stats_count);
1762
1763 /* Append the children of the current context to the main list. */
1764 for (MemoryContext c = cur->firstchild; c != NULL; c = c->nextchild)
1765 {
1766 if (summary)
1767 {
1768 entry = (MemoryStatsContextId *) hash_search(context_id_lookup, &c,
1769 HASH_ENTER, &found);
1770 Assert(!found);
1771
1772 entry->context_id = ++(*stats_count);
1773 }
1774
1775 contexts = lappend(contexts, c);
1776 }
1777
1778 /*
1779 * In summary mode only the first two level (from top) contexts are
1780 * displayed.
1781 */
1782 if (summary)
1783 break;
1784 }
1785}
struct cursor * cur
Definition: ecpg.c:29
Assert(PointerIsAligned(start, uint64))
@ HASH_ENTER
Definition: hsearch.h:114
List * lappend(List *list, void *datum)
Definition: list.c:339
#define foreach_ptr(type, var, lst)
Definition: pg_list.h:469

References Assert(), MemoryStatsContextId::context_id, cur, foreach_ptr, HASH_ENTER, hash_search(), and lappend().

Referenced by ProcessGetMemoryContextInterrupt().

◆ end_memorycontext_reporting()

static void end_memorycontext_reporting ( void  )
static

◆ free_memorycontextstate_dsa()

static void free_memorycontextstate_dsa ( dsa_area area,
int  total_stats,
dsa_pointer  prev_dsa_pointer 
)
static

Definition at line 1883 of file mcxt.c.

1885{
1886 MemoryStatsEntry *meminfo;
1887
1888 meminfo = (MemoryStatsEntry *) dsa_get_address(area, prev_dsa_pointer);
1889 Assert(meminfo != NULL);
1890 for (int i = 0; i < total_stats; i++)
1891 {
1892 if (DsaPointerIsValid(meminfo[i].name))
1893 dsa_free(area, meminfo[i].name);
1894
1895 if (DsaPointerIsValid(meminfo[i].ident))
1896 dsa_free(area, meminfo[i].ident);
1897
1898 if (DsaPointerIsValid(meminfo[i].path))
1899 dsa_free(area, meminfo[i].path);
1900 }
1901
1902 dsa_free(area, memCxtState[MyProcNumber].memstats_dsa_pointer);
1904}
void * dsa_get_address(dsa_area *area, dsa_pointer dp)
Definition: dsa.c:942
void dsa_free(dsa_area *area, dsa_pointer dp)
Definition: dsa.c:826
#define InvalidDsaPointer
Definition: dsa.h:78
#define ident
Definition: indent_codes.h:47
int i
Definition: isn.c:77
dsa_pointer memstats_dsa_pointer
Definition: memutils.h:381
const char * name

References Assert(), dsa_free(), dsa_get_address(), DsaPointerIsValid, i, ident, InvalidDsaPointer, memCxtState, MemoryStatsBackendState::memstats_dsa_pointer, MyProcNumber, and name.

Referenced by AtProcExit_memstats_cleanup(), and ProcessGetMemoryContextInterrupt().

◆ GetMemoryChunkContext()

MemoryContext GetMemoryChunkContext ( void *  pointer)

◆ GetMemoryChunkHeader()

static uint64 GetMemoryChunkHeader ( const void *  pointer)
inlinestatic

Definition at line 251 of file mcxt.c.

252{
253 uint64 header;
254
255 /* Allow access to the uint64 header */
256 VALGRIND_MAKE_MEM_DEFINED((char *) pointer - sizeof(uint64), sizeof(uint64));
257
258 header = *((const uint64 *) ((const char *) pointer - sizeof(uint64)));
259
260 /* Disallow access to the uint64 header */
261 VALGRIND_MAKE_MEM_NOACCESS((char *) pointer - sizeof(uint64), sizeof(uint64));
262
263 return header;
264}
uint64_t uint64
Definition: c.h:503
#define VALGRIND_MAKE_MEM_DEFINED(addr, size)
Definition: memdebug.h:26
#define VALGRIND_MAKE_MEM_NOACCESS(addr, size)
Definition: memdebug.h:27

References VALGRIND_MAKE_MEM_DEFINED, and VALGRIND_MAKE_MEM_NOACCESS.

Referenced by BogusFree(), BogusGetChunkContext(), BogusGetChunkSpace(), and BogusRealloc().

◆ GetMemoryChunkMethodID()

static MemoryContextMethodID GetMemoryChunkMethodID ( const void *  pointer)
inlinestatic

Definition at line 222 of file mcxt.c.

223{
224 uint64 header;
225
226 /*
227 * Try to detect bogus pointers handed to us, poorly though we can.
228 * Presumably, a pointer that isn't MAXALIGNED isn't pointing at an
229 * allocated chunk.
230 */
231 Assert(pointer == (const void *) MAXALIGN(pointer));
232
233 /* Allow access to the uint64 header */
234 VALGRIND_MAKE_MEM_DEFINED((char *) pointer - sizeof(uint64), sizeof(uint64));
235
236 header = *((const uint64 *) ((const char *) pointer - sizeof(uint64)));
237
238 /* Disallow access to the uint64 header */
239 VALGRIND_MAKE_MEM_NOACCESS((char *) pointer - sizeof(uint64), sizeof(uint64));
240
242}
#define MAXALIGN(LEN)
Definition: c.h:782
#define MEMORY_CONTEXT_METHODID_MASK
MemoryContextMethodID

References Assert(), MAXALIGN, MEMORY_CONTEXT_METHODID_MASK, VALGRIND_MAKE_MEM_DEFINED, and VALGRIND_MAKE_MEM_NOACCESS.

Referenced by pfree(), and repalloc().

◆ GetMemoryChunkSpace()

◆ HandleGetMemoryContextInterrupt()

void HandleGetMemoryContextInterrupt ( void  )

Definition at line 1367 of file mcxt.c.

1368{
1369 InterruptPending = true;
1371 /* latch will be set by procsignal_sigusr1_handler */
1372}
volatile sig_atomic_t InterruptPending
Definition: globals.c:32
volatile sig_atomic_t PublishMemoryContextPending
Definition: globals.c:42

References InterruptPending, and PublishMemoryContextPending.

Referenced by procsignal_sigusr1_handler().

◆ HandleLogMemoryContextInterrupt()

void HandleLogMemoryContextInterrupt ( void  )

Definition at line 1351 of file mcxt.c.

1352{
1353 InterruptPending = true;
1355 /* latch will be set by procsignal_sigusr1_handler */
1356}
volatile sig_atomic_t LogMemoryContextPending
Definition: globals.c:41

References InterruptPending, and LogMemoryContextPending.

Referenced by procsignal_sigusr1_handler().

◆ MemoryContextAlloc()

void * MemoryContextAlloc ( MemoryContext  context,
Size  size 
)

Definition at line 1260 of file mcxt.c.

1261{
1262 void *ret;
1263
1264 Assert(MemoryContextIsValid(context));
1266
1267 context->isReset = false;
1268
1269 /*
1270 * For efficiency reasons, we purposefully offload the handling of
1271 * allocation failures to the MemoryContextMethods implementation as this
1272 * allows these checks to be performed only when an actual malloc needs to
1273 * be done to request more memory from the OS. Additionally, not having
1274 * to execute any instructions after this call allows the compiler to use
1275 * the sibling call optimization. If you're considering adding code after
1276 * this call, consider making it the responsibility of the 'alloc'
1277 * function instead.
1278 */
1279 ret = context->methods->alloc(context, size, 0);
1280
1281 VALGRIND_MEMPOOL_ALLOC(context, ret, size);
1282
1283 return ret;
1284}
#define AssertNotInCriticalSection(context)
Definition: mcxt.c:206
#define VALGRIND_MEMPOOL_ALLOC(context, addr, size)
Definition: memdebug.h:29
#define MemoryContextIsValid(context)
Definition: memnodes.h:145
const MemoryContextMethods * methods
Definition: memnodes.h:126
void *(* alloc)(MemoryContext context, Size size, int flags)
Definition: memnodes.h:66

References MemoryContextMethods::alloc, Assert(), AssertNotInCriticalSection, MemoryContextData::isReset, MemoryContextIsValid, MemoryContextData::methods, and VALGRIND_MEMPOOL_ALLOC.

Referenced by _bt_getroot(), _bt_getrootheight(), _bt_metaversion(), _bt_preprocess_keys(), _fdvec_resize(), _hash_getcachedmetap(), AddInvalidationMessage(), afterTriggerAddEvent(), AfterTriggerBeginSubXact(), AfterTriggerEnlargeQueryState(), allocate_record_info(), array_agg_deserialize(), array_agg_serialize(), array_fill_internal(), array_in(), array_out(), array_position_common(), array_positions(), array_recv(), array_send(), array_to_text_internal(), Async_Notify(), AtSubCommit_childXids(), BackgroundWorkerMain(), be_tls_open_server(), bt_check_level_from_leftmost(), build_concat_foutcache(), build_dummy_expanded_header(), check_foreign_key(), check_primary_key(), compute_array_stats(), copy_byval_expanded_array(), CopySnapshot(), create_drop_transactional_internal(), dblink_connect(), dblink_init(), deconstruct_expanded_record(), dense_alloc(), domain_state_setup(), dsm_create_descriptor(), dsm_impl_sysv(), enlarge_list(), EventTriggerBeginCompleteQuery(), ExecHashBuildSkewHash(), ExecHashSkewTableInsert(), ExecParallelRetrieveJitInstrumentation(), ExecSetSlotDescriptor(), expand_array(), fetch_array_arg_replace_nulls(), gbt_enum_sortsupport(), get_attribute_options(), get_multirange_io_data(), get_range_io_data(), get_tablespace(), GetComboCommandId(), GetExplainExtensionId(), GetFdwRoutineForRelation(), GetLocalBufferStorage(), GetLockConflicts(), gtrgm_consistent(), gtrgm_distance(), gtrgm_penalty(), hash_create(), hash_record(), hash_record_extended(), hstore_from_record(), hstore_populate_record(), init_execution_state(), initArrayResultAny(), initArrayResultWithSize(), initBloomState(), initialize_reloptions(), InitializeClientEncoding(), InitializeParallelDSM(), InitIndexAmRoutine(), InitXLogInsert(), insertStatEntry(), intset_new_internal_node(), intset_new_leaf_node(), inv_open(), list_delete_first_n(), list_delete_nth_cell(), llvm_compile_module(), load_domaintype_info(), load_relcache_init_file(), LockAcquireExtended(), logical_rewrite_log_mapping(), lookup_ts_config_cache(), lookup_type_cache(), make_expanded_record_from_exprecord(), make_expanded_record_from_tupdesc(), make_expanded_record_from_typeid(), makeBoolAggState(), MemoryContextStrdup(), mergeruns(), mXactCachePut(), on_dsm_detach(), packGraph(), pg_column_compression(), pg_column_size(), pg_column_toast_chunk_id(), pg_input_is_valid_common(), pg_snapshot_xip(), pg_stat_get_backend_idset(), pgstat_build_snapshot(), pgstat_fetch_entry(), pgstat_get_entry_ref_cached(), pgstat_get_xact_stack_level(), pgstat_init_snapshot_fixed(), pgstat_read_current_status(), plpgsql_create_econtext(), plpgsql_start_datums(), PLy_push_execution_context(), PLy_subtransaction_enter(), PortalSetResultFormat(), pq_init(), PrepareClientEncoding(), PrepareSortSupportComparisonShim(), PrepareTempTablespaces(), PushActiveSnapshotWithLevel(), px_find_digest(), queue_listen(), record_cmp(), record_eq(), record_image_cmp(), record_image_eq(), record_in(), record_out(), record_recv(), record_send(), RegisterExprContextCallback(), RegisterExtensionExplainOption(), RegisterResourceReleaseCallback(), RegisterSubXactCallback(), RegisterXactCallback(), RelationBuildRuleLock(), RelationCacheInitialize(), RelationCreateStorage(), RelationDropStorage(), RelationParseRelOptions(), ReorderBufferAllocate(), ReorderBufferAllocChange(), ReorderBufferAllocRelids(), ReorderBufferAllocTupleBuf(), ReorderBufferAllocTXN(), ReorderBufferRestoreChange(), ReorderBufferSerializeReserve(), RequestNamedLWLockTranche(), RestoreSnapshot(), RT_ALLOC_LEAF(), RT_ALLOC_NODE(), setup_background_workers(), shm_mq_receive(), SnapBuildPurgeOlderTxn(), SPI_connect_ext(), SPI_palloc(), sql_compile_callback(), StoreIndexTuple(), sts_read_tuple(), tbm_begin_private_iterate(), test_enc_conversion(), tstoreStartupReceiver(), tts_virtual_materialize(), tuplesort_readtup_alloc(), and xactGetCommittedInvalidationMessages().

◆ MemoryContextAllocAligned()

void * MemoryContextAllocAligned ( MemoryContext  context,
Size  size,
Size  alignto,
int  flags 
)

Definition at line 2038 of file mcxt.c.

2040{
2041 MemoryChunk *alignedchunk;
2042 Size alloc_size;
2043 void *unaligned;
2044 void *aligned;
2045
2046 /* wouldn't make much sense to waste that much space */
2047 Assert(alignto < (128 * 1024 * 1024));
2048
2049 /* ensure alignto is a power of 2 */
2050 Assert((alignto & (alignto - 1)) == 0);
2051
2052 /*
2053 * If the alignment requirements are less than what we already guarantee
2054 * then just use the standard allocation function.
2055 */
2056 if (unlikely(alignto <= MAXIMUM_ALIGNOF))
2057 return MemoryContextAllocExtended(context, size, flags);
2058
2059 /*
2060 * We implement aligned pointers by simply allocating enough memory for
2061 * the requested size plus the alignment and an additional "redirection"
2062 * MemoryChunk. This additional MemoryChunk is required for operations
2063 * such as pfree when used on the pointer returned by this function. We
2064 * use this redirection MemoryChunk in order to find the pointer to the
2065 * memory that was returned by the MemoryContextAllocExtended call below.
2066 * We do that by "borrowing" the block offset field and instead of using
2067 * that to find the offset into the owning block, we use it to find the
2068 * original allocated address.
2069 *
2070 * Here we must allocate enough extra memory so that we can still align
2071 * the pointer returned by MemoryContextAllocExtended and also have enough
2072 * space for the redirection MemoryChunk. Since allocations will already
2073 * be at least aligned by MAXIMUM_ALIGNOF, we can subtract that amount
2074 * from the allocation size to save a little memory.
2075 */
2076 alloc_size = size + PallocAlignedExtraBytes(alignto);
2077
2078#ifdef MEMORY_CONTEXT_CHECKING
2079 /* ensure there's space for a sentinel byte */
2080 alloc_size += 1;
2081#endif
2082
2083 /* perform the actual allocation */
2084 unaligned = MemoryContextAllocExtended(context, alloc_size, flags);
2085
2086 /* set the aligned pointer */
2087 aligned = (void *) TYPEALIGN(alignto, (char *) unaligned +
2088 sizeof(MemoryChunk));
2089
2090 alignedchunk = PointerGetMemoryChunk(aligned);
2091
2092 /*
2093 * We set the redirect MemoryChunk so that the block offset calculation is
2094 * used to point back to the 'unaligned' allocated chunk. This allows us
2095 * to use MemoryChunkGetBlock() to find the unaligned chunk when we need
2096 * to perform operations such as pfree() and repalloc().
2097 *
2098 * We store 'alignto' in the MemoryChunk's 'value' so that we know what
2099 * the alignment was set to should we ever be asked to realloc this
2100 * pointer.
2101 */
2102 MemoryChunkSetHdrMask(alignedchunk, unaligned, alignto,
2104
2105 /* double check we produced a correctly aligned pointer */
2106 Assert((void *) TYPEALIGN(alignto, aligned) == aligned);
2107
2108#ifdef MEMORY_CONTEXT_CHECKING
2109 alignedchunk->requested_size = size;
2110 /* set mark to catch clobber of "unused" space */
2111 set_sentinel(aligned, size);
2112#endif
2113
2114 /* Mark the bytes before the redirection header as noaccess */
2116 (char *) alignedchunk - (char *) unaligned);
2117
2118 /* Disallow access to the redirection chunk header. */
2119 VALGRIND_MAKE_MEM_NOACCESS(alignedchunk, sizeof(MemoryChunk));
2120
2121 return aligned;
2122}
#define TYPEALIGN(ALIGNVAL, LEN)
Definition: c.h:775
#define unlikely(x)
Definition: c.h:347
size_t Size
Definition: c.h:576
void * MemoryContextAllocExtended(MemoryContext context, Size size, int flags)
Definition: mcxt.c:1317
#define PallocAlignedExtraBytes(alignto)
@ MCTX_ALIGNED_REDIRECT_ID
struct MemoryChunk MemoryChunk
#define PointerGetMemoryChunk(p)
static void MemoryChunkSetHdrMask(MemoryChunk *chunk, void *block, Size value, MemoryContextMethodID methodid)

References Assert(), MCTX_ALIGNED_REDIRECT_ID, MemoryChunkSetHdrMask(), MemoryContextAllocExtended(), PallocAlignedExtraBytes, PointerGetMemoryChunk, TYPEALIGN, unlikely, and VALGRIND_MAKE_MEM_NOACCESS.

Referenced by AlignedAllocRealloc(), PageSetChecksumCopy(), palloc_aligned(), and smgr_bulk_get_buf().

◆ MemoryContextAllocationFailure()

void * MemoryContextAllocationFailure ( MemoryContext  context,
Size  size,
int  flags 
)

Definition at line 1226 of file mcxt.c.

1227{
1228 if ((flags & MCXT_ALLOC_NO_OOM) == 0)
1229 {
1230 if (TopMemoryContext)
1232 ereport(ERROR,
1233 (errcode(ERRCODE_OUT_OF_MEMORY),
1234 errmsg("out of memory"),
1235 errdetail("Failed on request of size %zu in memory context \"%s\".",
1236 size, context->name)));
1237 }
1238 return NULL;
1239}
int errdetail(const char *fmt,...)
Definition: elog.c:1204
int errcode(int sqlerrcode)
Definition: elog.c:854
int errmsg(const char *fmt,...)
Definition: elog.c:1071
#define ereport(elevel,...)
Definition: elog.h:149
#define MCXT_ALLOC_NO_OOM
Definition: fe_memutils.h:29
MemoryContext TopMemoryContext
Definition: mcxt.c:165
void MemoryContextStats(MemoryContext context)
Definition: mcxt.c:845
const char * name
Definition: memnodes.h:131

References ereport, errcode(), errdetail(), errmsg(), ERROR, MCXT_ALLOC_NO_OOM, MemoryContextStats(), MemoryContextData::name, and TopMemoryContext.

Referenced by AllocSetAllocFromNewBlock(), AllocSetAllocLarge(), AllocSetRealloc(), BumpAllocFromNewBlock(), GenerationAllocFromNewBlock(), GenerationAllocLarge(), GenerationRealloc(), and SlabAllocFromNewBlock().

◆ MemoryContextAllocExtended()

void * MemoryContextAllocExtended ( MemoryContext  context,
Size  size,
int  flags 
)

Definition at line 1317 of file mcxt.c.

1318{
1319 void *ret;
1320
1321 Assert(MemoryContextIsValid(context));
1323
1324 if (!((flags & MCXT_ALLOC_HUGE) != 0 ? AllocHugeSizeIsValid(size) :
1325 AllocSizeIsValid(size)))
1326 elog(ERROR, "invalid memory alloc request size %zu", size);
1327
1328 context->isReset = false;
1329
1330 ret = context->methods->alloc(context, size, flags);
1331 if (unlikely(ret == NULL))
1332 return NULL;
1333
1334 VALGRIND_MEMPOOL_ALLOC(context, ret, size);
1335
1336 if ((flags & MCXT_ALLOC_ZERO) != 0)
1337 MemSetAligned(ret, 0, size);
1338
1339 return ret;
1340}
#define MemSetAligned(start, val, len)
Definition: c.h:1021
#define MCXT_ALLOC_ZERO
Definition: fe_memutils.h:30
#define MCXT_ALLOC_HUGE
Definition: fe_memutils.h:28
#define AllocHugeSizeIsValid(size)
Definition: memutils.h:52
#define AllocSizeIsValid(size)
Definition: memutils.h:45

References MemoryContextMethods::alloc, AllocHugeSizeIsValid, AllocSizeIsValid, Assert(), AssertNotInCriticalSection, elog, ERROR, MemoryContextData::isReset, MCXT_ALLOC_HUGE, MCXT_ALLOC_ZERO, MemoryContextIsValid, MemSetAligned, MemoryContextData::methods, unlikely, and VALGRIND_MEMPOOL_ALLOC.

Referenced by BackgroundWorkerStateChange(), DynaHashAlloc(), guc_malloc(), guc_realloc(), MemoryContextAllocAligned(), pagetable_allocate(), and RegisterBackgroundWorker().

◆ MemoryContextAllocHuge()

void * MemoryContextAllocHuge ( MemoryContext  context,
Size  size 
)

Definition at line 2269 of file mcxt.c.

2270{
2271 void *ret;
2272
2273 Assert(MemoryContextIsValid(context));
2275
2276 context->isReset = false;
2277
2278 /*
2279 * For efficiency reasons, we purposefully offload the handling of
2280 * allocation failures to the MemoryContextMethods implementation as this
2281 * allows these checks to be performed only when an actual malloc needs to
2282 * be done to request more memory from the OS. Additionally, not having
2283 * to execute any instructions after this call allows the compiler to use
2284 * the sibling call optimization. If you're considering adding code after
2285 * this call, consider making it the responsibility of the 'alloc'
2286 * function instead.
2287 */
2288 ret = context->methods->alloc(context, size, MCXT_ALLOC_HUGE);
2289
2290 VALGRIND_MEMPOOL_ALLOC(context, ret, size);
2291
2292 return ret;
2293}

References MemoryContextMethods::alloc, Assert(), AssertNotInCriticalSection, MemoryContextData::isReset, MCXT_ALLOC_HUGE, MemoryContextIsValid, MemoryContextData::methods, and VALGRIND_MEMPOOL_ALLOC.

Referenced by perform_default_encoding_conversion(), pg_buffercache_numa_pages(), pg_buffercache_pages(), pg_do_encoding_conversion(), and pgstat_read_current_status().

◆ MemoryContextAllocZero()

void * MemoryContextAllocZero ( MemoryContext  context,
Size  size 
)

Definition at line 1294 of file mcxt.c.

1295{
1296 void *ret;
1297
1298 Assert(MemoryContextIsValid(context));
1300
1301 context->isReset = false;
1302
1303 ret = context->methods->alloc(context, size, 0);
1304
1305 VALGRIND_MEMPOOL_ALLOC(context, ret, size);
1306
1307 MemSetAligned(ret, 0, size);
1308
1309 return ret;
1310}

References MemoryContextMethods::alloc, Assert(), AssertNotInCriticalSection, MemoryContextData::isReset, MemoryContextIsValid, MemSetAligned, MemoryContextData::methods, and VALGRIND_MEMPOOL_ALLOC.

Referenced by add_tabstat_xact_level(), AllocateAttribute(), array_set_element_expanded(), array_sort_internal(), AttrDefaultFetch(), cached_function_compile(), CheckNNConstraintFetch(), ClientAuthentication(), create_pg_locale_builtin(), create_pg_locale_icu(), create_pg_locale_libc(), CreatePortal(), CreateWaitEventSet(), DCH_cache_getnew(), ensure_record_cache_typmod_slot_exists(), ExecHashBuildSkewHash(), ExecParallelRetrieveJitInstrumentation(), expandColorTrigrams(), fmgr_security_definer(), gistAllocateNewPageBuffer(), index_form_tuple_context(), init_MultiFuncCall(), init_sql_fcache(), initArrayResultArr(), InitializeSession(), InitWalSender(), InitXLogInsert(), json_populate_type(), llvm_create_context(), load_relcache_init_file(), LookupOpclassInfo(), LWLockRegisterTranche(), make_expanded_record_from_datum(), newLOfd(), NUM_cache_getnew(), pg_decode_begin_prepare_txn(), pg_decode_begin_txn(), pg_decode_stream_start(), pgoutput_begin_txn(), pgstat_prep_pending_entry(), pgstat_register_kind(), PLy_exec_function(), PLy_function_save_args(), PLy_input_setup_func(), PLy_input_setup_tuple(), PLy_output_setup_func(), PLy_output_setup_tuple(), populate_record_worker(), populate_recordset_worker(), prepare_column_cache(), PrepareInvalidationState(), push_old_value(), PushTransaction(), px_find_cipher(), RehashCatCache(), RehashCatCacheLists(), RelationBuildPartitionDesc(), RelationBuildPartitionKey(), RelationBuildRowSecurity(), RelationBuildTupleDesc(), RelationInitIndexAccessInfo(), ReorderBufferCopySnap(), ReorderBufferIterTXNInit(), ReorderBufferRestoreChange(), ResourceOwnerCreate(), ResourceOwnerEnlarge(), satisfies_hash_partition(), SearchCatCacheList(), secure_open_gssapi(), SetConstraintStateCreate(), SnapBuildBuildSnapshot(), SnapBuildRestoreSnapshot(), spgGetCache(), sts_puttuple(), ts_accum(), ts_stat_sql(), and WinGetPartitionLocalMemory().

◆ MemoryContextAllowInCriticalSection()

void MemoryContextAllowInCriticalSection ( MemoryContext  context,
bool  allow 
)

Definition at line 725 of file mcxt.c.

726{
728
729 context->allowInCritSection = allow;
730}
bool allowInCritSection
Definition: memnodes.h:124

References MemoryContextData::allowInCritSection, Assert(), and MemoryContextIsValid.

Referenced by InitSync(), MemoryContextInit(), and XLOGShmemInit().

◆ MemoryContextCallResetCallbacks()

static void MemoryContextCallResetCallbacks ( MemoryContext  context)
static

Definition at line 616 of file mcxt.c.

617{
619
620 /*
621 * We pop each callback from the list before calling. That way, if an
622 * error occurs inside the callback, we won't try to call it a second time
623 * in the likely event that we reset or delete the context later.
624 */
625 while ((cb = context->reset_cbs) != NULL)
626 {
627 context->reset_cbs = cb->next;
628 cb->func(cb->arg);
629 }
630}
struct MemoryContextCallback * next
Definition: palloc.h:51
MemoryContextCallbackFunction func
Definition: palloc.h:49
MemoryContextCallback * reset_cbs
Definition: memnodes.h:133

References MemoryContextCallback::arg, MemoryContextCallback::func, MemoryContextCallback::next, and MemoryContextData::reset_cbs.

Referenced by MemoryContextDeleteOnly(), and MemoryContextResetOnly().

◆ MemoryContextCreate()

void MemoryContextCreate ( MemoryContext  node,
NodeTag  tag,
MemoryContextMethodID  method_id,
MemoryContext  parent,
const char *  name 
)

Definition at line 1175 of file mcxt.c.

1180{
1181 /* Creating new memory contexts is not allowed in a critical section */
1183
1184 /* Validate parent, to help prevent crazy context linkages */
1185 Assert(parent == NULL || MemoryContextIsValid(parent));
1186 Assert(node != parent);
1187
1188 /* Initialize all standard fields of memory context header */
1189 node->type = tag;
1190 node->isReset = true;
1191 node->methods = &mcxt_methods[method_id];
1192 node->parent = parent;
1193 node->firstchild = NULL;
1194 node->mem_allocated = 0;
1195 node->prevchild = NULL;
1196 node->name = name;
1197 node->ident = NULL;
1198 node->reset_cbs = NULL;
1199
1200 /* OK to link node into context tree */
1201 if (parent)
1202 {
1203 node->nextchild = parent->firstchild;
1204 if (parent->firstchild != NULL)
1205 parent->firstchild->prevchild = node;
1206 parent->firstchild = node;
1207 /* inherit allowInCritSection flag from parent */
1208 node->allowInCritSection = parent->allowInCritSection;
1209 }
1210 else
1211 {
1212 node->nextchild = NULL;
1213 node->allowInCritSection = false;
1214 }
1215
1216 VALGRIND_CREATE_MEMPOOL(node, 0, false);
1217}
volatile uint32 CritSectionCount
Definition: globals.c:46
static const MemoryContextMethods mcxt_methods[]
Definition: mcxt.c:51
#define VALGRIND_CREATE_MEMPOOL(context, redzones, zeroed)
Definition: memdebug.h:24
MemoryContext prevchild
Definition: memnodes.h:129
MemoryContext firstchild
Definition: memnodes.h:128
const char * ident
Definition: memnodes.h:132
MemoryContext nextchild
Definition: memnodes.h:130

References MemoryContextData::allowInCritSection, Assert(), CritSectionCount, MemoryContextData::firstchild, MemoryContextData::ident, MemoryContextData::isReset, mcxt_methods, MemoryContextData::mem_allocated, MemoryContextIsValid, MemoryContextData::methods, name, MemoryContextData::name, MemoryContextData::nextchild, MemoryContextData::parent, MemoryContextData::prevchild, MemoryContextData::reset_cbs, and VALGRIND_CREATE_MEMPOOL.

Referenced by AllocSetContextCreateInternal(), BumpContextCreate(), GenerationContextCreate(), and SlabContextCreate().

◆ MemoryContextDelete()

void MemoryContextDelete ( MemoryContext  context)

Definition at line 485 of file mcxt.c.

486{
487 MemoryContext curr;
488
490
491 /*
492 * Delete subcontexts from the bottom up.
493 *
494 * Note: Do not use recursion here. A "stack depth limit exceeded" error
495 * would be unpleasant if we're already in the process of cleaning up from
496 * transaction abort. We also cannot use MemoryContextTraverseNext() here
497 * because we modify the tree as we go.
498 */
499 curr = context;
500 for (;;)
501 {
502 MemoryContext parent;
503
504 /* Descend down until we find a leaf context with no children */
505 while (curr->firstchild != NULL)
506 curr = curr->firstchild;
507
508 /*
509 * We're now at a leaf with no children. Free it and continue from the
510 * parent. Or if this was the original node, we're all done.
511 */
512 parent = curr->parent;
514
515 if (curr == context)
516 break;
517 curr = parent;
518 }
519}
static void MemoryContextDeleteOnly(MemoryContext context)
Definition: mcxt.c:527

References Assert(), MemoryContextData::firstchild, MemoryContextDeleteOnly(), MemoryContextIsValid, and MemoryContextData::parent.

Referenced by _brin_parallel_merge(), AfterTriggerEndXact(), afterTriggerInvokeEvents(), ApplyLauncherMain(), AtEOSubXact_SPI(), AtEOXact_LargeObject(), AtSubCleanup_Memory(), AtSubCommit_Memory(), AttachPartitionEnsureIndexes(), AutoVacLauncherMain(), autovacuum_do_vac_analyze(), AutoVacWorkerMain(), AuxiliaryProcessMainCommon(), BackgroundWorkerMain(), blbuild(), blinsert(), brin_free_desc(), brin_minmax_multi_union(), bringetbitmap(), brininsert(), bt_check_every_level(), btendscan(), btree_xlog_cleanup(), btvacuumscan(), BuildParamLogString(), BuildRelationExtStatistics(), CloneRowTriggersToPartition(), cluster(), compactify_ranges(), compile_plperl_function(), compile_pltcl_function(), compute_expr_stats(), compute_index_stats(), ComputeExtStatisticsRows(), createTrgmNFA(), CreateTriggerFiringOn(), daitch_mokotoff(), decr_dcc_refcount(), DeleteExpandedObject(), DiscreteKnapsack(), do_analyze_rel(), do_start_worker(), DoCopyTo(), DropCachedPlan(), each_worker(), each_worker_jsonb(), elements_worker(), elements_worker_jsonb(), end_heap_rewrite(), EndCopy(), EndCopyFrom(), ensure_free_space_in_buffer(), EventTriggerEndCompleteQuery(), EventTriggerInvoke(), exec_simple_query(), ExecEndAgg(), ExecEndMemoize(), ExecEndRecursiveUnion(), ExecEndSetOp(), ExecEndWindowAgg(), ExecHashTableDestroy(), execute_sql_string(), ExecVacuum(), file_acquire_sample_rows(), fill_hba_view(), fill_ident_view(), free_auth_file(), free_plperl_function(), FreeCachedExpression(), FreeDecodingContext(), FreeExecutorState(), FreeExprContext(), freeGISTstate(), FreeSnapshotBuilder(), geqo_eval(), get_actual_variable_range(), get_rel_sync_entry(), GetWALRecordsInfo(), GetXLogSummaryStats(), gin_check_parent_keys_consistency(), gin_check_posting_tree_parent_keys_consistency(), gin_xlog_cleanup(), ginbuild(), ginbulkdelete(), ginendscan(), gininsert(), ginInsertCleanup(), ginPlaceToPage(), gist_xlog_cleanup(), gistbuild(), gistvacuumscan(), hash_destroy(), inline_function(), inline_set_returning_function(), libpqrcv_processTuples(), load_hba(), load_ident(), load_tzoffsets(), makeArrayResultArr(), makeMdArrayResult(), MemoryContextDeleteChildren(), NIFinishBuild(), pg_backup_stop(), pg_decode_shutdown(), pg_get_wal_block_info(), pgstat_clear_backend_activity_snapshot(), pgstat_clear_snapshot(), plperl_spi_freeplan(), plperl_spi_prepare(), plpgsql_free_function_memory(), pltcl_handler(), pltcl_SPI_prepare(), PLy_cursor_dealloc(), PLy_cursor_plan(), PLy_plan_dealloc(), PLy_pop_execution_context(), PLy_procedure_delete(), PLy_spi_execute_fetch_result(), PLy_spi_execute_plan(), PortalDrop(), PostgresMain(), postquel_end(), prepare_next_query(), printtup_shutdown(), ProcessConfigFile(), publicationListToArray(), RE_compile_and_cache(), rebuild_database_list(), ReindexMultipleTables(), ReindexPartitions(), ReindexRelationConcurrently(), RelationBuildDesc(), RelationBuildRuleLock(), RelationDestroyRelation(), ReleaseCachedPlan(), ReorderBufferFree(), ResetUnloggedRelations(), RevalidateCachedQuery(), serializeAnalyzeShutdown(), shdepReassignOwned(), shutdown_MultiFuncCall(), spg_xlog_cleanup(), spgbuild(), spgendscan(), spginsert(), SPI_finish(), SPI_freeplan(), SPI_freetuptable(), sql_delete_callback(), statext_dependencies_build(), strlist_to_textarray(), SysLoggerMain(), test_pattern(), TidStoreDestroy(), tokenize_auth_file(), tuplesort_end(), tuplestore_end(), union_tuples(), UploadManifest(), and validateForeignKeyConstraint().

◆ MemoryContextDeleteChildren()

void MemoryContextDeleteChildren ( MemoryContext  context)

Definition at line 570 of file mcxt.c.

571{
573
574 /*
575 * MemoryContextDelete will delink the child from me, so just iterate as
576 * long as there is a child.
577 */
578 while (context->firstchild != NULL)
580}
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:485

References Assert(), MemoryContextData::firstchild, MemoryContextDelete(), and MemoryContextIsValid.

Referenced by AtAbort_Portals(), AtSubAbort_Portals(), exec_stmt_block(), MemoryContextReset(), PersistHoldablePortal(), PortalRunMulti(), and RelationCloseCleanup().

◆ MemoryContextDeleteOnly()

static void MemoryContextDeleteOnly ( MemoryContext  context)
static

Definition at line 527 of file mcxt.c.

528{
530 /* We had better not be deleting TopMemoryContext ... */
531 Assert(context != TopMemoryContext);
532 /* And not CurrentMemoryContext, either */
533 Assert(context != CurrentMemoryContext);
534 /* All the children should've been deleted already */
535 Assert(context->firstchild == NULL);
536
537 /*
538 * It's not entirely clear whether 'tis better to do this before or after
539 * delinking the context; but an error in a callback will likely result in
540 * leaking the whole context (if it's not a root context) if we do it
541 * after, so let's do it before.
542 */
544
545 /*
546 * We delink the context from its parent before deleting it, so that if
547 * there's an error we won't have deleted/busted contexts still attached
548 * to the context tree. Better a leak than a crash.
549 */
550 MemoryContextSetParent(context, NULL);
551
552 /*
553 * Also reset the context's ident pointer, in case it points into the
554 * context. This would only matter if someone tries to get stats on the
555 * (already unlinked) context, which is unlikely, but let's be safe.
556 */
557 context->ident = NULL;
558
559 context->methods->delete_context(context);
560
562}
static void MemoryContextCallResetCallbacks(MemoryContext context)
Definition: mcxt.c:616
void MemoryContextSetParent(MemoryContext context, MemoryContext new_parent)
Definition: mcxt.c:668
MemoryContext CurrentMemoryContext
Definition: mcxt.c:159
#define VALGRIND_DESTROY_MEMPOOL(context)
Definition: memdebug.h:25
void(* delete_context)(MemoryContext context)
Definition: memnodes.h:86

References Assert(), CurrentMemoryContext, MemoryContextMethods::delete_context, MemoryContextData::firstchild, MemoryContextData::ident, MemoryContextCallResetCallbacks(), MemoryContextIsValid, MemoryContextSetParent(), MemoryContextData::methods, TopMemoryContext, and VALGRIND_DESTROY_MEMPOOL.

Referenced by MemoryContextDelete().

◆ MemoryContextGetParent()

MemoryContext MemoryContextGetParent ( MemoryContext  context)

◆ MemoryContextInit()

void MemoryContextInit ( void  )

Definition at line 370 of file mcxt.c.

371{
372 Assert(TopMemoryContext == NULL);
373
374 /*
375 * First, initialize TopMemoryContext, which is the parent of all others.
376 */
378 "TopMemoryContext",
380
381 /*
382 * Not having any other place to point CurrentMemoryContext, make it point
383 * to TopMemoryContext. Caller should change this soon!
384 */
386
387 /*
388 * Initialize ErrorContext as an AllocSetContext with slow growth rate ---
389 * we don't really expect much to be allocated in it. More to the point,
390 * require it to contain at least 8K at all times. This is the only case
391 * where retained memory in a context is *essential* --- we want to be
392 * sure ErrorContext still has some memory even if we've run out
393 * elsewhere! Also, allow allocations in ErrorContext within a critical
394 * section. Otherwise a PANIC will cause an assertion failure in the error
395 * reporting code, before printing out the real cause of the failure.
396 *
397 * This should be the last step in this function, as elog.c assumes memory
398 * management works once ErrorContext is non-null.
399 */
401 "ErrorContext",
402 8 * 1024,
403 8 * 1024,
404 8 * 1024);
406}
MemoryContext ErrorContext
Definition: mcxt.c:166
void MemoryContextAllowInCriticalSection(MemoryContext context, bool allow)
Definition: mcxt.c:725
#define AllocSetContextCreate
Definition: memutils.h:149
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:180

References ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, Assert(), CurrentMemoryContext, ErrorContext, MemoryContextAllowInCriticalSection(), and TopMemoryContext.

Referenced by main().

◆ MemoryContextIsEmpty()

bool MemoryContextIsEmpty ( MemoryContext  context)

Definition at line 774 of file mcxt.c.

775{
777
778 /*
779 * For now, we consider a memory context nonempty if it has any children;
780 * perhaps this should be changed later.
781 */
782 if (context->firstchild != NULL)
783 return false;
784 /* Otherwise use the type-specific inquiry */
785 return context->methods->is_empty(context);
786}
bool(* is_empty)(MemoryContext context)
Definition: memnodes.h:101

References Assert(), MemoryContextData::firstchild, MemoryContextMethods::is_empty, MemoryContextIsValid, and MemoryContextData::methods.

Referenced by AtSubCommit_Memory().

◆ MemoryContextMemAllocated()

Size MemoryContextMemAllocated ( MemoryContext  context,
bool  recurse 
)

Definition at line 793 of file mcxt.c.

794{
795 Size total = context->mem_allocated;
796
798
799 if (recurse)
800 {
801 for (MemoryContext curr = context->firstchild;
802 curr != NULL;
803 curr = MemoryContextTraverseNext(curr, context))
804 {
805 total += curr->mem_allocated;
806 }
807 }
808
809 return total;
810}
static MemoryContext MemoryContextTraverseNext(MemoryContext curr, MemoryContext top)
Definition: mcxt.c:288

References Assert(), MemoryContextData::firstchild, MemoryContextData::mem_allocated, MemoryContextIsValid, and MemoryContextTraverseNext().

Referenced by hash_agg_check_limits(), hash_agg_update_metrics(), and RT_MEMORY_USAGE().

◆ MemoryContextMemConsumed()

void MemoryContextMemConsumed ( MemoryContext  context,
MemoryContextCounters consumed 
)

Definition at line 817 of file mcxt.c.

819{
821
822 memset(consumed, 0, sizeof(*consumed));
823
824 /* Examine the context itself */
825 context->methods->stats(context, NULL, NULL, consumed, false);
826
827 /* Examine children, using iteration not recursion */
828 for (MemoryContext curr = context->firstchild;
829 curr != NULL;
830 curr = MemoryContextTraverseNext(curr, context))
831 {
832 curr->methods->stats(curr, NULL, NULL, consumed, false);
833 }
834}
void(* stats)(MemoryContext context, MemoryStatsPrintFunc printfunc, void *passthru, MemoryContextCounters *totals, bool print_to_stderr)
Definition: memnodes.h:102

References Assert(), MemoryContextData::firstchild, MemoryContextIsValid, MemoryContextTraverseNext(), MemoryContextData::methods, and MemoryContextMethods::stats.

Referenced by ExplainExecuteQuery(), and standard_ExplainOneQuery().

◆ MemoryContextRegisterResetCallback()

void MemoryContextRegisterResetCallback ( MemoryContext  context,
MemoryContextCallback cb 
)

Definition at line 599 of file mcxt.c.

601{
603
604 /* Push onto head so this will be called before older registrants. */
605 cb->next = context->reset_cbs;
606 context->reset_cbs = cb;
607 /* Mark the context as non-reset (it probably is already). */
608 context->isReset = false;
609}

References Assert(), MemoryContextData::isReset, MemoryContextIsValid, MemoryContextCallback::next, and MemoryContextData::reset_cbs.

Referenced by expanded_record_fetch_tupdesc(), init_sql_fcache(), InitDomainConstraintRef(), load_validator_library(), make_expanded_record_from_exprecord(), make_expanded_record_from_tupdesc(), make_expanded_record_from_typeid(), and PLy_exec_function().

◆ MemoryContextReset()

void MemoryContextReset ( MemoryContext  context)

Definition at line 414 of file mcxt.c.

415{
417
418 /* save a function call in common case where there are no children */
419 if (context->firstchild != NULL)
421
422 /* save a function call if no pallocs since startup or last reset */
423 if (!context->isReset)
424 MemoryContextResetOnly(context);
425}
void MemoryContextDeleteChildren(MemoryContext context)
Definition: mcxt.c:570
void MemoryContextResetOnly(MemoryContext context)
Definition: mcxt.c:433

References Assert(), MemoryContextData::firstchild, MemoryContextData::isReset, MemoryContextDeleteChildren(), MemoryContextIsValid, and MemoryContextResetOnly().

Referenced by _brin_parallel_merge(), _bt_preprocess_array_keys(), _SPI_end_call(), AfterTriggerExecute(), agg_refill_hash_table(), apply_spooled_messages(), AtCleanup_Memory(), AtCommit_Memory(), AtEOSubXact_SPI(), AtSubCleanup_Memory(), AutoVacLauncherMain(), BackgroundWriterMain(), bloomBuildCallback(), brin_memtuple_initialize(), bringetbitmap(), brininsert(), bt_check_level_from_leftmost(), btree_redo(), btvacuumpage(), BuildEventTriggerCache(), BuildRelationExtStatistics(), buildSubPlanHash(), cache_purge_all(), check_domain_for_new_field(), check_domain_for_new_tuple(), CheckpointerMain(), CloneRowTriggersToPartition(), compute_expr_stats(), compute_index_stats(), CopyOneRowTo(), CreateTriggerFiringOn(), do_analyze_rel(), do_autovacuum(), dumptuples(), each_object_field_end(), each_worker_jsonb(), elements_array_element_end(), elements_worker_jsonb(), errstart(), eval_windowaggregates(), EventTriggerInvoke(), exec_dynquery_with_params(), exec_replication_command(), exec_stmt_block(), exec_stmt_dynexecute(), exec_stmt_forc(), exec_stmt_foreach_a(), exec_stmt_open(), exec_stmt_raise(), exec_stmt_return_query(), ExecFindMatchingSubPlans(), ExecHashTableReset(), ExecMakeTableFunctionResult(), ExecProjectSet(), ExecQualAndReset(), ExecRecursiveUnion(), ExecReScanAgg(), ExecReScanRecursiveUnion(), ExecReScanSetOp(), execTuplesUnequal(), execute_foreign_modify(), expanded_record_set_field_internal(), expanded_record_set_tuple(), fetch_more_data(), file_acquire_sample_rows(), FlushErrorState(), get_rel_sync_entry(), get_short_term_cxt(), GetWALRecordsInfo(), GetXLogSummaryStats(), gin_redo(), ginBuildCallback(), ginFlushBuildState(), ginFreeScanKeys(), ginHeapTupleBulkInsert(), ginInsertCleanup(), ginVacuumPostingTreeLeaves(), gist_indexsortbuild(), gist_redo(), gistBuildCallback(), gistgetbitmap(), gistgettuple(), gistinsert(), gistProcessEmptyingQueue(), gistrescan(), gistScanPage(), gistSortedBuildCallback(), heapam_index_build_range_scan(), heapam_index_validate_scan(), IndexCheckExclusion(), init_execution_state(), initialize_windowaggregate(), InvalidateEventCacheCallback(), keyGetItem(), libpqrcv_processTuples(), LogicalParallelApplyLoop(), LogicalRepApplyLoop(), lookup_ts_dictionary_cache(), make_tuple_from_result_row(), perform_work_item(), pg_backup_start(), pg_decode_change(), pg_decode_truncate(), pg_get_wal_block_info(), pgarch_archiveXlog(), pgoutput_change(), pgoutput_truncate(), plperl_return_next_internal(), PLy_input_convert(), PLy_input_from_tuple(), PostgresMain(), printtup(), process_ordered_aggregate_single(), ProcessParallelApplyMessages(), ProcessParallelMessages(), release_partition(), ReScanExprContext(), resetSpGistScanOpaque(), RT_FREE(), scanPendingInsert(), sepgsql_avc_reset(), serializeAnalyzeReceive(), spcache_init(), spg_redo(), spginsert(), spgistBuildCallback(), spgWalk(), startScanKey(), statext_dependencies_build(), storeRow(), stream_stop_internal(), tfuncFetchRows(), tfuncLoadRows(), tuplesort_free(), tuplestore_clear(), UpdateCachedPlan(), validateForeignKeyConstraint(), WalSummarizerMain(), and WalWriterMain().

◆ MemoryContextResetChildren()

void MemoryContextResetChildren ( MemoryContext  context)

Definition at line 464 of file mcxt.c.

465{
467
468 for (MemoryContext curr = context->firstchild;
469 curr != NULL;
470 curr = MemoryContextTraverseNext(curr, context))
471 {
473 }
474}

References Assert(), MemoryContextData::firstchild, MemoryContextIsValid, MemoryContextResetOnly(), and MemoryContextTraverseNext().

◆ MemoryContextResetOnly()

void MemoryContextResetOnly ( MemoryContext  context)

Definition at line 433 of file mcxt.c.

434{
436
437 /* Nothing to do if no pallocs since startup or last reset */
438 if (!context->isReset)
439 {
441
442 /*
443 * If context->ident points into the context's memory, it will become
444 * a dangling pointer. We could prevent that by setting it to NULL
445 * here, but that would break valid coding patterns that keep the
446 * ident elsewhere, e.g. in a parent context. So for now we assume
447 * the programmer got it right.
448 */
449
450 context->methods->reset(context);
451 context->isReset = true;
453 VALGRIND_CREATE_MEMPOOL(context, 0, false);
454 }
455}
void(* reset)(MemoryContext context)
Definition: memnodes.h:83

References Assert(), MemoryContextData::isReset, MemoryContextCallResetCallbacks(), MemoryContextIsValid, MemoryContextData::methods, MemoryContextMethods::reset, VALGRIND_CREATE_MEMPOOL, and VALGRIND_DESTROY_MEMPOOL.

Referenced by AllocSetDelete(), JsonTableResetRowPattern(), MemoryContextReset(), MemoryContextResetChildren(), and mergeruns().

◆ MemoryContextSetIdentifier()

◆ MemoryContextSetParent()

void MemoryContextSetParent ( MemoryContext  context,
MemoryContext  new_parent 
)

Definition at line 668 of file mcxt.c.

669{
671 Assert(context != new_parent);
672
673 /* Fast path if it's got correct parent already */
674 if (new_parent == context->parent)
675 return;
676
677 /* Delink from existing parent, if any */
678 if (context->parent)
679 {
680 MemoryContext parent = context->parent;
681
682 if (context->prevchild != NULL)
683 context->prevchild->nextchild = context->nextchild;
684 else
685 {
686 Assert(parent->firstchild == context);
687 parent->firstchild = context->nextchild;
688 }
689
690 if (context->nextchild != NULL)
691 context->nextchild->prevchild = context->prevchild;
692 }
693
694 /* And relink */
695 if (new_parent)
696 {
697 Assert(MemoryContextIsValid(new_parent));
698 context->parent = new_parent;
699 context->prevchild = NULL;
700 context->nextchild = new_parent->firstchild;
701 if (new_parent->firstchild != NULL)
702 new_parent->firstchild->prevchild = context;
703 new_parent->firstchild = context;
704 }
705 else
706 {
707 context->parent = NULL;
708 context->prevchild = NULL;
709 context->nextchild = NULL;
710 }
711}

References Assert(), MemoryContextData::firstchild, MemoryContextIsValid, MemoryContextData::nextchild, MemoryContextData::parent, and MemoryContextData::prevchild.

Referenced by _SPI_save_plan(), BuildCachedPlan(), CachedPlanSetParentContext(), CompleteCachedPlan(), exec_parse_message(), GetCachedExpression(), GetCachedPlan(), load_domaintype_info(), MemoryContextDeleteOnly(), RE_compile_and_cache(), RelationBuildPartitionDesc(), RelationBuildPartitionKey(), RelationBuildRowSecurity(), RelationRebuildRelation(), RevalidateCachedQuery(), SaveCachedPlan(), SPI_keepplan(), sql_compile_callback(), TransferExpandedObject(), and UploadManifest().

◆ MemoryContextSizeFailure()

void MemoryContextSizeFailure ( MemoryContext  context,
Size  size,
int  flags 
)

Definition at line 1247 of file mcxt.c.

1248{
1249 elog(ERROR, "invalid memory alloc request size %zu", size);
1250}

References elog, and ERROR.

Referenced by MemoryContextCheckSize().

◆ MemoryContextStats()

void MemoryContextStats ( MemoryContext  context)

Definition at line 845 of file mcxt.c.

846{
847 /* Hard-wired limits are usually good enough */
848 MemoryContextStatsDetail(context, 100, 100, true);
849}
void MemoryContextStatsDetail(MemoryContext context, int max_level, int max_children, bool print_to_stderr)
Definition: mcxt.c:860

References MemoryContextStatsDetail().

Referenced by AllocSetContextCreateInternal(), BumpContextCreate(), finish_xact_command(), GenerationContextCreate(), MemoryContextAllocationFailure(), SlabContextCreate(), and test_pattern().

◆ MemoryContextStatsDetail()

void MemoryContextStatsDetail ( MemoryContext  context,
int  max_level,
int  max_children,
bool  print_to_stderr 
)

Definition at line 860 of file mcxt.c.

863{
864 MemoryContextCounters grand_totals;
865 int num_contexts;
866 PrintDestination print_location;
867
868 memset(&grand_totals, 0, sizeof(grand_totals));
869
870 if (print_to_stderr)
871 print_location = PRINT_STATS_TO_STDERR;
872 else
873 print_location = PRINT_STATS_TO_LOGS;
874
875 /* num_contexts report number of contexts aggregated in the output */
876 MemoryContextStatsInternal(context, 1, max_level, max_children,
877 &grand_totals, print_location, &num_contexts);
878
879 if (print_to_stderr)
880 fprintf(stderr,
881 "Grand total: %zu bytes in %zu blocks; %zu free (%zu chunks); %zu used\n",
882 grand_totals.totalspace, grand_totals.nblocks,
883 grand_totals.freespace, grand_totals.freechunks,
884 grand_totals.totalspace - grand_totals.freespace);
885 else
886 {
887 /*
888 * Use LOG_SERVER_ONLY to prevent the memory contexts from being sent
889 * to the connected client.
890 *
891 * We don't buffer the information about all memory contexts in a
892 * backend into StringInfo and log it as one message. That would
893 * require the buffer to be enlarged, risking an OOM as there could be
894 * a large number of memory contexts in a backend. Instead, we log
895 * one message per memory context.
896 */
898 (errhidestmt(true),
899 errhidecontext(true),
900 errmsg_internal("Grand total: %zu bytes in %zu blocks; %zu free (%zu chunks); %zu used",
901 grand_totals.totalspace, grand_totals.nblocks,
902 grand_totals.freespace, grand_totals.freechunks,
903 grand_totals.totalspace - grand_totals.freespace)));
904 }
905}
#define fprintf(file, fmt, msg)
Definition: cubescan.l:21
int errmsg_internal(const char *fmt,...)
Definition: elog.c:1158
int errhidestmt(bool hide_stmt)
Definition: elog.c:1433
int errhidecontext(bool hide_ctx)
Definition: elog.c:1452
#define LOG_SERVER_ONLY
Definition: elog.h:32
static void MemoryContextStatsInternal(MemoryContext context, int level, int max_level, int max_children, MemoryContextCounters *totals, PrintDestination print_location, int *num_contexts)
Definition: mcxt.c:916

References ereport, errhidecontext(), errhidestmt(), errmsg_internal(), fprintf, MemoryContextCounters::freechunks, MemoryContextCounters::freespace, LOG_SERVER_ONLY, MemoryContextStatsInternal(), MemoryContextCounters::nblocks, PRINT_STATS_TO_LOGS, PRINT_STATS_TO_STDERR, and MemoryContextCounters::totalspace.

Referenced by MemoryContextStats(), and ProcessLogMemoryContextInterrupt().

◆ MemoryContextStatsInternal()

static void MemoryContextStatsInternal ( MemoryContext  context,
int  level,
int  max_level,
int  max_children,
MemoryContextCounters totals,
PrintDestination  print_location,
int *  num_contexts 
)
static

Definition at line 916 of file mcxt.c.

920{
921 MemoryContext child;
922 int ichild;
923
925
926 /* Examine the context itself */
927 switch (print_location)
928 {
930 context->methods->stats(context,
932 &level,
933 totals, true);
934 break;
935
937 context->methods->stats(context,
939 &level,
940 totals, false);
941 break;
942
943 case PRINT_STATS_NONE:
944
945 /*
946 * Do not print the statistics if print_location is
947 * PRINT_STATS_NONE, only compute totals. This is used in
948 * reporting of memory context statistics via a sql function. Last
949 * parameter is not relevant.
950 */
951 context->methods->stats(context,
952 NULL,
953 NULL,
954 totals, false);
955 break;
956 }
957
958 /* Increment the context count for each of the recursive call */
959 *num_contexts = *num_contexts + 1;
960
961 /*
962 * Examine children.
963 *
964 * If we are past the recursion depth limit or already running low on
965 * stack, do not print them explicitly but just summarize them. Similarly,
966 * if there are more than max_children of them, we do not print the rest
967 * explicitly, but just summarize them.
968 */
969 child = context->firstchild;
970 ichild = 0;
971 if (level <= max_level && !stack_is_too_deep())
972 {
973 for (; child != NULL && ichild < max_children;
974 child = child->nextchild, ichild++)
975 {
976 MemoryContextStatsInternal(child, level + 1,
977 max_level, max_children,
978 totals,
979 print_location, num_contexts);
980 }
981 }
982
983 if (child != NULL)
984 {
985 /* Summarize the rest of the children, avoiding recursion. */
986 MemoryContextCounters local_totals;
987
988 memset(&local_totals, 0, sizeof(local_totals));
989
990 ichild = 0;
991 while (child != NULL)
992 {
993 child->methods->stats(child, NULL, NULL, &local_totals, false);
994 ichild++;
995 child = MemoryContextTraverseNext(child, context);
996 }
997
998 /*
999 * Add the count of children contexts which are traversed in the
1000 * non-recursive manner.
1001 */
1002 *num_contexts = *num_contexts + ichild;
1003
1004 if (print_location == PRINT_STATS_TO_STDERR)
1005 {
1006 for (int i = 0; i < level; i++)
1007 fprintf(stderr, " ");
1008 fprintf(stderr,
1009 "%d more child contexts containing %zu total in %zu blocks; %zu free (%zu chunks); %zu used\n",
1010 ichild,
1011 local_totals.totalspace,
1012 local_totals.nblocks,
1013 local_totals.freespace,
1014 local_totals.freechunks,
1015 local_totals.totalspace - local_totals.freespace);
1016 }
1017 else if (print_location == PRINT_STATS_TO_LOGS)
1019 (errhidestmt(true),
1020 errhidecontext(true),
1021 errmsg_internal("level: %d; %d more child contexts containing %zu total in %zu blocks; %zu free (%zu chunks); %zu used",
1022 level,
1023 ichild,
1024 local_totals.totalspace,
1025 local_totals.nblocks,
1026 local_totals.freespace,
1027 local_totals.freechunks,
1028 local_totals.totalspace - local_totals.freespace)));
1029
1030 if (totals)
1031 {
1032 totals->nblocks += local_totals.nblocks;
1033 totals->freechunks += local_totals.freechunks;
1034 totals->totalspace += local_totals.totalspace;
1035 totals->freespace += local_totals.freespace;
1036 }
1037 }
1038}
static void MemoryContextStatsPrint(MemoryContext context, void *passthru, const char *stats_string, bool print_to_stderr)
Definition: mcxt.c:1048
bool stack_is_too_deep(void)
Definition: stack_depth.c:109

References Assert(), ereport, errhidecontext(), errhidestmt(), errmsg_internal(), MemoryContextData::firstchild, fprintf, MemoryContextCounters::freechunks, MemoryContextCounters::freespace, i, LOG_SERVER_ONLY, MemoryContextIsValid, MemoryContextStatsInternal(), MemoryContextStatsPrint(), MemoryContextTraverseNext(), MemoryContextData::methods, MemoryContextCounters::nblocks, MemoryContextData::nextchild, PRINT_STATS_NONE, PRINT_STATS_TO_LOGS, PRINT_STATS_TO_STDERR, stack_is_too_deep(), MemoryContextMethods::stats, and MemoryContextCounters::totalspace.

Referenced by MemoryContextStatsDetail(), MemoryContextStatsInternal(), and ProcessGetMemoryContextInterrupt().

◆ MemoryContextStatsPrint()

static void MemoryContextStatsPrint ( MemoryContext  context,
void *  passthru,
const char *  stats_string,
bool  print_to_stderr 
)
static

Definition at line 1048 of file mcxt.c.

1051{
1052 int level = *(int *) passthru;
1053 const char *name = context->name;
1054 const char *ident = context->ident;
1055 char truncated_ident[110];
1056 int i;
1057
1058 /*
1059 * It seems preferable to label dynahash contexts with just the hash table
1060 * name. Those are already unique enough, so the "dynahash" part isn't
1061 * very helpful, and this way is more consistent with pre-v11 practice.
1062 */
1063 if (ident && strcmp(name, "dynahash") == 0)
1064 {
1065 name = ident;
1066 ident = NULL;
1067 }
1068
1069 truncated_ident[0] = '\0';
1070
1071 if (ident)
1072 {
1073 /*
1074 * Some contexts may have very long identifiers (e.g., SQL queries).
1075 * Arbitrarily truncate at 100 bytes, but be careful not to break
1076 * multibyte characters. Also, replace ASCII control characters, such
1077 * as newlines, with spaces.
1078 */
1079 int idlen = strlen(ident);
1080 bool truncated = false;
1081
1082 strcpy(truncated_ident, ": ");
1083 i = strlen(truncated_ident);
1084
1085 if (idlen > 100)
1086 {
1087 idlen = pg_mbcliplen(ident, idlen, 100);
1088 truncated = true;
1089 }
1090
1091 while (idlen-- > 0)
1092 {
1093 unsigned char c = *ident++;
1094
1095 if (c < ' ')
1096 c = ' ';
1097 truncated_ident[i++] = c;
1098 }
1099 truncated_ident[i] = '\0';
1100
1101 if (truncated)
1102 strcat(truncated_ident, "...");
1103 }
1104
1105 if (print_to_stderr)
1106 {
1107 for (i = 1; i < level; i++)
1108 fprintf(stderr, " ");
1109 fprintf(stderr, "%s: %s%s\n", name, stats_string, truncated_ident);
1110 }
1111 else
1113 (errhidestmt(true),
1114 errhidecontext(true),
1115 errmsg_internal("level: %d; %s: %s%s",
1116 level, name, stats_string, truncated_ident)));
1117}
int pg_mbcliplen(const char *mbstr, int len, int limit)
Definition: mbutils.c:1083

References ereport, errhidecontext(), errhidestmt(), errmsg_internal(), fprintf, i, MemoryContextData::ident, ident, LOG_SERVER_ONLY, name, MemoryContextData::name, and pg_mbcliplen().

Referenced by MemoryContextStatsInternal().

◆ MemoryContextStrdup()

◆ MemoryContextTraverseNext()

static MemoryContext MemoryContextTraverseNext ( MemoryContext  curr,
MemoryContext  top 
)
static

Definition at line 288 of file mcxt.c.

289{
290 /* After processing a node, traverse to its first child if any */
291 if (curr->firstchild != NULL)
292 return curr->firstchild;
293
294 /*
295 * After processing a childless node, traverse to its next sibling if
296 * there is one. If there isn't, traverse back up to the parent (which
297 * has already been visited, and now so have all its descendants). We're
298 * done if that is "top", otherwise traverse to its next sibling if any,
299 * otherwise repeat moving up.
300 */
301 while (curr->nextchild == NULL)
302 {
303 curr = curr->parent;
304 if (curr == top)
305 return NULL;
306 }
307 return curr->nextchild;
308}

References MemoryContextData::firstchild, MemoryContextData::nextchild, and MemoryContextData::parent.

Referenced by MemoryContextMemAllocated(), MemoryContextMemConsumed(), MemoryContextResetChildren(), and MemoryContextStatsInternal().

◆ palloc()

void * palloc ( Size  size)

Definition at line 1943 of file mcxt.c.

1944{
1945 /* duplicates MemoryContextAlloc to avoid increased overhead */
1946 void *ret;
1948
1949 Assert(MemoryContextIsValid(context));
1951
1952 context->isReset = false;
1953
1954 /*
1955 * For efficiency reasons, we purposefully offload the handling of
1956 * allocation failures to the MemoryContextMethods implementation as this
1957 * allows these checks to be performed only when an actual malloc needs to
1958 * be done to request more memory from the OS. Additionally, not having
1959 * to execute any instructions after this call allows the compiler to use
1960 * the sibling call optimization. If you're considering adding code after
1961 * this call, consider making it the responsibility of the 'alloc'
1962 * function instead.
1963 */
1964 ret = context->methods->alloc(context, size, 0);
1965 /* We expect OOM to be handled by the alloc function */
1966 Assert(ret != NULL);
1967 VALGRIND_MEMPOOL_ALLOC(context, ret, size);
1968
1969 return ret;
1970}

References MemoryContextMethods::alloc, Assert(), AssertNotInCriticalSection, CurrentMemoryContext, MemoryContextData::isReset, MemoryContextIsValid, MemoryContextData::methods, and VALGRIND_MEMPOOL_ALLOC.

Referenced by _bt_bottomupdel_pass(), _bt_deadblocks(), _bt_dedup_pass(), _bt_delitems_delete_check(), _bt_delitems_update(), _bt_findsplitloc(), _bt_load(), _bt_mkscankey(), _bt_newlevel(), _bt_pendingfsm_init(), _bt_preprocess_array_keys(), _bt_search(), _bt_simpledel_pass(), _gin_build_tuple(), _intbig_alloc(), _lca(), _ltree_compress(), _ltree_picksplit(), _metaphone(), _SPI_make_plan_non_temp(), _SPI_save_plan(), AbsorbSyncRequests(), accum_sum_copy(), accumArrayResultArr(), aclexplode(), aclitemin(), aclitemout(), aclmembers(), acquire_inherited_sample_rows(), add_exact_object_address_extra(), add_gin_entry(), add_local_reloption(), add_reloption(), add_rte_to_flat_rtable(), add_to_tsvector(), add_unique_group_var(), addArc(), addArcs(), addCompiledLexeme(), AddEnumLabel(), addFkRecurseReferenced(), addItemsToLeaf(), addKey(), addKeyToQueue(), addNode(), addNorm(), addNSItemForReturning(), addRangeClause(), addRangeTableEntryForFunction(), addRangeTableEntryForJoin(), AddRelationNewConstraints(), AddRoleMems(), addWrd(), alloc_chromo(), alloc_edge_table(), alloc_pool(), allocate_recordbuf(), allocate_reloption(), AllocateRelationDesc(), AlterPolicy(), AlterPublicationTables(), AlterSubscription_refresh(), anybit_typmodout(), anychar_typmodout(), append_nonpartial_cost(), appendJSONKeyValueFmt(), AppendStringCommandOption(), apply_spooled_messages(), apw_dump_now(), array_agg_array_combine(), array_agg_array_deserialize(), array_cat(), array_create_iterator(), array_exec_setup(), array_map(), array_out(), array_recv(), array_replace_internal(), array_set_element(), array_typanalyze(), array_unnest(), arrayconst_startup_fn(), arrayexpr_startup_fn(), ArrayGetIntegerTypmods(), AssignTransactionId(), Async_Notify(), ATExecAddColumn(), ATExecColumnDefault(), ATExecSetExpression(), attach_internal(), AttachPartitionEnsureIndexes(), autoinc(), BaseBackupAddTarget(), BaseBackupGetTargetHandle(), bbsink_copystream_begin_backup(), be_loread(), be_tls_get_certificate_hash(), begin_tup_output_tupdesc(), BeginCopyFrom(), binary_decode(), binary_encode(), binaryheap_allocate(), BipartiteMatch(), bit_and(), bit_catenate(), bit_or(), bit_out(), bit_recv(), bitfromint4(), bitfromint8(), bitnot(), bits_to_text(), bitsetbit(), bitshiftleft(), bitshiftright(), bitsubstring(), bitxor(), blbeginscan(), blbuild(), BlockRefTableEntryMarkBlockModified(), BlockRefTableReaderNextRelation(), bms_copy(), boolout(), BootStrapXLOG(), bottomup_sort_and_shrink(), box_add(), box_center(), box_circle(), box_copy(), box_diagonal(), box_div(), box_in(), box_intersect(), box_mul(), box_poly(), box_recv(), box_sub(), boxes_bound_box(), bpchar(), bpchar_input(), bqarr_in(), bqarr_out(), brin_build_desc(), brin_copy_tuple(), brin_form_tuple(), brin_minmax_multi_distance_inet(), brin_new_memtuple(), brin_page_items(), brin_range_deserialize(), brin_revmap_data(), bringetbitmap(), brinRevmapInitialize(), bt_multi_page_stats(), bt_normalize_tuple(), bt_page_items_bytea(), bt_page_items_internal(), bt_page_print_tuples(), btbeginscan(), btbuild(), btgettuple(), btree_xlog_dedup(), btree_xlog_updates(), btreevacuumposting(), btrescan(), BufferSync(), BufFileCreateFileSet(), BufFileOpenFileSet(), build_attnums_array(), build_column_frequencies(), build_datatype(), build_distinct_groups(), build_EvalXFuncInt(), build_function_result_tupdesc_d(), build_local_reloptions(), build_merged_partition_bounds(), build_minmax_path(), build_pertrans_for_aggref(), build_row_from_vars(), build_server_final_message(), build_server_first_message(), build_sorted_items(), build_tlist_index(), build_tlist_index_other_vars(), build_tuplestore_recursively(), BuildCachedPlan(), buildNSItemFromLists(), buildNSItemFromTupleDesc(), BuildSpeculativeIndexInfo(), BuildTupleFromCStrings(), BuildTupleHashTable(), bytea_catenate(), bytea_reverse(), bytea_string_agg_finalfn(), byteain(), byteaout(), bytearecv(), cache_lookup(), cache_store_tuple(), cached_scansel(), calc_distr(), calc_hist(), calc_hist_selectivity(), calc_word_similarity(), CatalogCacheCreateEntry(), catenate_stringinfo_string(), char_bpchar(), char_text(), charout(), check_foreign_key(), check_primary_key(), check_temp_tablespaces(), CheckAffix(), checkAllTheSame(), checkclass_str(), checkcondition_HL(), checkcondition_str(), checkSharedDependencies(), choose_bitmap_and(), chr(), cidout(), circle_add_pt(), circle_box(), circle_center(), circle_div_pt(), circle_in(), circle_mul_pt(), circle_recv(), circle_sub_pt(), classify_index_clause_usage(), clauselist_apply_dependencies(), cleanup_tsquery_stopwords(), clone_parse_state(), close_ls(), close_lseg(), close_pb(), close_pl(), close_ps(), close_sb(), collect_corrupt_items(), collectTSQueryValues(), combinebackup_per_wal_range_cb(), compileTheLexeme(), compileTheSubstitute(), CompleteCachedPlan(), complex_add(), complex_in(), complex_recv(), compute_array_stats(), compute_distinct_stats(), compute_expr_stats(), compute_index_stats(), compute_range_stats(), compute_scalar_stats(), compute_tsvector_stats(), computeLeafRecompressWALData(), concat_text(), connect_pg_server(), consider_groupingsets_paths(), construct_point(), convert_prep_stmt_params(), convert_requires_to_datum(), convert_string_datum(), convert_tuples_by_name_attrmap(), convert_tuples_by_position(), copy_file(), copy_pathtarget(), copy_plpgsql_datums(), CopyCachedPlan(), CopyErrorData(), CopyFromTextLikeStart(), CopyIndexAttOptions(), CopyIndexTuple(), copyJsonbValue(), CopyLimitPrintoutLength(), CopyMultiInsertBufferInit(), CopySearchPathMatcher(), copyTemplateDependencies(), copytext(), CopyTriggerDesc(), copyTSLexeme(), CopyVar(), copyVar(), core_yyalloc(), core_yyrealloc(), count_usable_fds(), cr_circle(), create_hash_bounds(), create_internal(), create_limit_plan(), create_list_bounds(), create_memoize_plan(), create_mergejoin_plan(), create_range_bounds(), create_secmsg(), create_unique_plan(), create_windowagg_plan(), CreateConstraintEntry(), CreateCopyDestReceiver(), CreateEmptyBlockRefTable(), CreateFunction(), CreatePartitionDirectory(), CreatePartitionPruneState(), createPostingTree(), CreateQueryDesc(), CreateTemplateTupleDesc(), CreateTriggerFiringOn(), CreateTupleDescCopyConstr(), cstring_to_text_with_len(), cube_recv(), current_database(), current_schemas(), currtid_internal(), dataBeginPlaceToPageLeaf(), dataPrepareDownlink(), datetime_format_has_tz(), datetime_to_char_body(), datumCopy(), datumRestore(), datumSerialize(), dead_items_alloc(), debackslash(), decodePageSplitRecord(), deconstruct_array(), DeescapeQuotedString(), DefineRelation(), DefineTSConfiguration(), deparse_lquery(), deparse_ltree(), dependencies_clauselist_selectivity(), dependency_degree(), DependencyGenerator_init(), deserialize_deflist(), detoast_attr(), detoast_attr_slice(), detoast_external_attr(), dibuild(), disassembleLeaf(), DiscreteKnapsack(), div_var(), do_analyze_rel(), do_pg_backup_start(), do_to_timestamp(), dobyteatrim(), DoCopyTo(), doPickSplit(), dotrim(), double_to_shortest_decimal(), downcase_convert(), downcase_identifier(), DropRelationFiles(), DropRelationsAllBuffers(), dshash_attach(), dshash_create(), dsynonym_init(), duplicate_numeric(), dxsyn_lexize(), encrypt_password(), entry_dealloc(), entryPrepareDownlink(), enum_range_internal(), EnumValuesCreate(), EventTriggerAlterTableStart(), EventTriggerCollectAlterOpFam(), EventTriggerCollectAlterTableSubcmd(), EventTriggerCollectAlterTSConfig(), EventTriggerCollectGrant(), EventTriggerCollectSimpleCommand(), ExecAggRetrieveInstrumentation(), ExecBitmapHeapRetrieveInstrumentation(), ExecBitmapIndexScanRetrieveInstrumentation(), ExecBuildHash32Expr(), ExecBuildHash32FromAttrs(), ExecComputeStoredGenerated(), ExecEvalArrayExpr(), ExecGather(), ExecGatherMerge(), ExecGetJsonValueItemString(), ExecHashJoinGetSavedTuple(), ExecHashRetrieveInstrumentation(), ExecIncrementalSortRetrieveInstrumentation(), ExecIndexBuildScanKeys(), ExecIndexOnlyScanRetrieveInstrumentation(), ExecIndexScanRetrieveInstrumentation(), ExecInitAgg(), ExecInitAppend(), ExecInitCoerceToDomain(), ExecInitExprRec(), ExecInitFunctionScan(), ExecInitIndexOnlyScan(), ExecInitIndexScan(), ExecInitJsonExpr(), ExecInitJunkFilter(), ExecInitMemoize(), ExecInitMergeAppend(), ExecInitModifyTable(), ExecInitPartitionDispatchInfo(), ExecInitProjectSet(), ExecInitRoutingInfo(), ExecInitSubPlan(), ExecInitTableFuncScan(), ExecInitValuesScan(), ExecInsert(), ExecMakeTableFunctionResult(), ExecMemoizeRetrieveInstrumentation(), ExecOpenIndices(), ExecParallelCreateReaders(), ExecParallelRetrieveInstrumentation(), ExecParallelSetupTupleQueues(), ExecSortRetrieveInstrumentation(), execTuplesHashPrepare(), execTuplesMatchPrepare(), executeBinaryArithmExpr(), executeDateTimeMethod(), executeItemOptUnwrapTarget(), executeNumericItemMethod(), ExecuteTruncateGuts(), ExplainCreateWorkersState(), ExportSnapshot(), ExprEvalPushStep(), extract_autovac_opts(), extract_grouping_collations(), extract_grouping_cols(), extract_grouping_ops(), extract_rollup_sets(), fallbackSplit(), FetchTableStates(), file_acquire_sample_rows(), fileBeginForeignScan(), fileGetForeignRelSize(), filter_list_to_array(), find_appinfos_by_relids(), find_hash_columns(), find_in_path(), find_inheritance_children_extended(), find_partition_scheme(), find_plan(), find_tabstat_entry(), find_window_functions(), findDependentObjects(), findJsonbValueFromContainer(), FinishWalRecovery(), fix_merged_indexes(), flagInhTables(), float4_to_char(), float4out(), float8_to_char(), Float8GetDatum(), float8out_internal(), float_to_shortest_decimal(), FlushRelationsAllBuffers(), format_operator_extended(), format_procedure_extended(), formTextDatum(), FreezeMultiXactId(), FuncnameGetCandidates(), g_cube_decompress(), g_cube_picksplit(), g_int_compress(), g_int_decompress(), g_int_picksplit(), g_intbig_compress(), g_intbig_picksplit(), gbt_bit_xfrm(), gbt_bool_union(), gbt_cash_union(), gbt_date_union(), gbt_enum_union(), gbt_float4_union(), gbt_float8_union(), gbt_inet_compress(), gbt_inet_union(), gbt_int2_union(), gbt_int4_union(), gbt_int8_union(), gbt_intv_compress(), gbt_intv_decompress(), gbt_intv_union(), gbt_num_compress(), gbt_num_fetch(), gbt_num_picksplit(), gbt_oid_union(), gbt_time_union(), gbt_timetz_compress(), gbt_ts_union(), gbt_tstz_compress(), gbt_uuid_compress(), gbt_uuid_union(), gbt_var_compress(), gbt_var_decompress(), gbt_var_fetch(), gbt_var_key_from_datum(), gbt_var_picksplit(), gen_random_uuid(), generate_append_tlist(), generate_matching_part_pairs(), generate_normalized_query(), generate_series_step_int4(), generate_series_step_int8(), generate_series_step_numeric(), generate_series_timestamp(), generate_series_timestamptz_internal(), generate_subscripts(), generate_trgm(), generate_trgm_only(), generate_uuidv7(), generate_wildcard_trgm(), generateHeadline(), generator_init(), genericPickSplit(), get_attribute_options(), get_database_list(), get_docrep(), get_environ(), get_explain_guc_options(), get_ext_ver_info(), get_extension_aux_control_filename(), get_extension_control_directories(), get_extension_script_directory(), get_extension_script_filename(), get_func_arg_info(), get_func_input_arg_names(), get_func_signature(), get_func_trftypes(), get_guc_variables(), get_name_for_var_field(), get_op_index_interpretation(), get_page_from_raw(), get_path_all(), get_raw_page_internal(), get_relation_info(), get_rels_with_domain(), get_str_from_var(), get_str_from_var_sci(), get_tables_to_cluster(), get_tables_to_cluster_partitioned(), get_tsearch_config_filename(), get_val(), get_worker(), GetBlockerStatusData(), GetBulkInsertState(), GetCachedExpression(), getColorInfo(), GetConfFilesInDir(), GetCurrentVirtualXIDs(), GetFdwRoutineForRelation(), GetForeignDataWrapperExtended(), GetForeignServerExtended(), GetForeignTable(), getIthJsonbValueFromContainer(), getJsonEncodingConst(), GetJsonPathVar(), getKeyJsonValueFromContainer(), GetLockStatusData(), GetMultiXactIdMembers(), GetPermutation(), GetPredicateLockStatusData(), GetPreparedTransactionList(), GetPublication(), getQuadrantArea(), getRangeBox(), GetRunningTransactionLocks(), GetSQLCurrentTime(), GetSubscription(), GetSubscriptionRelations(), gettoken_tsvector(), GetUserMapping(), GetVirtualXIDsDelayingChkpt(), GetWaitEventCustomNames(), GetWALBlockInfo(), GetWalSummaries(), ghstore_alloc(), ghstore_compress(), ghstore_picksplit(), gimme_tree(), gin_bool_consistent(), gin_btree_extract_query(), gin_btree_extract_value(), gin_check_parent_keys_consistency(), gin_check_posting_tree_parent_keys_consistency(), gin_extract_hstore(), gin_extract_hstore_query(), gin_extract_jsonb_path(), gin_extract_jsonb_query(), gin_extract_query_trgm(), gin_extract_tsquery(), gin_extract_tsvector(), gin_extract_value_trgm(), gin_leafpage_items(), gin_trgm_triconsistent(), ginAllocEntryAccumulator(), ginbeginscan(), GinBufferStoreTuple(), ginbuild(), ginCompressPostingList(), GinDataLeafPageGetItems(), ginExtractEntries(), ginFillScanEntry(), ginFillScanKey(), ginFindLeafPage(), ginFindParents(), GinFormInteriorTuple(), ginHeapTupleFastInsert(), gininsert(), ginInsertBAEntry(), ginint4_queryextract(), ginMergeItemPointers(), ginPostingListDecodeAllSegments(), ginReadTuple(), ginReadTupleWithoutState(), ginRedoRecompress(), ginVacuumItemPointers(), ginVacuumPostingTreeLeaf(), gist_box_picksplit(), gist_box_union(), gist_circle_compress(), gist_indexsortbuild(), gist_indexsortbuild_levelstate_flush(), gist_page_items_bytea(), gist_point_compress(), gist_point_fetch(), gist_poly_compress(), gistbeginscan(), gistbufferinginserttuples(), gistbuild(), gistextractpage(), gistfillitupvec(), gistfixsplit(), gistGetItupFromPage(), gistgettuple(), gistInitBuildBuffers(), gistMakeUnionItVec(), gistplacetopage(), gistRelocateBuildBuffersOnSplit(), gistrescan(), gistScanPage(), gistSplit(), gistSplitByKey(), gistSplitHalf(), gistunionsubkeyvec(), group_similar_or_args(), gseg_picksplit(), gtrgm_alloc(), gtrgm_compress(), gtrgm_consistent(), gtrgm_decompress(), gtrgm_picksplit(), gtsquery_compress(), gtsquery_picksplit(), gtsvector_alloc(), gtsvector_compress(), gtsvector_decompress(), gtsvector_penalty(), gtsvector_picksplit(), hash_agg_enter_spill_mode(), hash_object_field_end(), hash_page_items(), hash_record(), hash_record_extended(), hashagg_batch_read(), hashbeginscan(), hashbpchar(), hashbpcharextended(), hashbuild(), hashgettuple(), hashtext(), hashtextextended(), heap_beginscan(), heap_copy_minimal_tuple(), heap_copy_tuple_as_datum(), heap_copytuple(), heap_copytuple_with_tuple(), heap_modify_tuple(), heap_modify_tuple_by_cols(), heap_multi_insert(), heap_page_items(), heap_tuple_from_minimal_tuple(), heap_vacuum_rel(), heapam_relation_copy_for_cluster(), hladdword(), hmac_finish(), hstore_akeys(), hstore_avals(), hstore_concat(), hstore_delete(), hstore_delete_array(), hstore_delete_hstore(), hstore_from_array(), hstore_from_arrays(), hstore_from_record(), hstore_out(), hstore_populate_record(), hstore_recv(), hstore_slice_to_array(), hstore_slice_to_hstore(), hstore_subscript_assign(), hstore_to_array_internal(), hstoreArrayToPairs(), hstorePairs(), icu_language_tag(), identify_opfamily_groups(), ImportSnapshot(), index_compute_xid_horizon_for_tuples(), index_register(), inet_gist_compress(), inet_gist_fetch(), inet_gist_picksplit(), inet_set_masklen(), inet_spg_inner_consistent(), inet_spg_picksplit(), infix(), init_gin_entries(), init_partition_map(), init_sexpr(), init_slab_allocator(), init_tsvector_parser(), InitCatCache(), InitDeadLockChecking(), initGISTstate(), initialize_revoke_actions(), InitJumble(), InitPlan(), InitPostmasterChildSlots(), initRectBox(), initStringInfoInternal(), initTrie(), InitWalRecovery(), inplaceGetInvalidationMessages(), InsertPgAttributeTuples(), int2out(), int2vectorout(), int44in(), int44out(), int4_to_char(), int4out(), Int64GetDatum(), int8_to_char(), int8out(), int_list_to_array(), int_to_roman(), interpret_AS_clause(), interpret_function_parameter_list(), interval_avg(), interval_div(), interval_in(), interval_justify_days(), interval_justify_hours(), interval_justify_interval(), interval_mi(), interval_mul(), interval_pl(), interval_recv(), interval_scale(), interval_sum(), interval_trunc(), interval_um(), intervaltypmodout(), intset_create(), irbt_alloc(), iterate_word_similarity(), json_agg_transfn_worker(), json_manifest_finalize_file(), json_object_agg_transfn_worker(), json_object_keys(), json_parse_manifest_incremental_init(), json_unique_object_start(), jsonb_agg_transfn_worker(), jsonb_object_agg_transfn_worker(), jsonb_object_keys(), jsonb_ops__add_path_item(), JsonbDeepContains(), JsonbValueToJsonb(), JsonEncodeDateTime(), jsonpath_yyalloc(), jsonpath_yyrealloc(), JsonTableInitOpaque(), lca(), leafRepackItems(), leftmostvalue_interval(), leftmostvalue_timetz(), LexizeAddLemm(), libpqrcv_readtimelinehistoryfile(), like_fixed_prefix(), line_construct_pp(), line_in(), line_interpt(), line_recv(), litbufdup(), llvm_copy_attributes_at_index(), lo_get_fragment_internal(), load_categories_hash(), load_domaintype_info(), load_enum_cache_data(), load_relcache_init_file(), load_tzoffsets(), LocalProcessControlFile(), logfile_getname(), logical_heap_rewrite_flush_mappings(), logicalrep_partition_open(), logicalrep_read_attrs(), logicalrep_read_rel(), logicalrep_read_tuple(), logicalrep_relmap_update(), LogicalRepSyncTableStart(), LogicalTapeFreeze(), LogicalTapeSetCreate(), LogicalTapeWrite(), lookup_var_attr_stats(), lpad(), lrq_alloc(), lseg_center(), lseg_construct(), lseg_in(), lseg_interpt(), lseg_recv(), ltree2text(), ltree_compress(), ltree_decompress(), ltree_gist_alloc(), ltree_picksplit(), ltsCreateTape(), ltsGetPreallocBlock(), ltsInitReadBuffer(), ltxtq_out(), ltxtq_send(), lz4_compress_datum(), lz4_decompress_datum(), lz4_decompress_datum_slice(), macaddr8_out(), macaddr_and(), macaddr_in(), macaddr_not(), macaddr_or(), macaddr_out(), macaddr_recv(), macaddr_sortsupport(), macaddr_trunc(), main(), make_build_data(), make_callstmt_target(), make_colname_unique(), make_greater_string(), make_interval(), make_jsp_entry_node(), make_jsp_expr_node(), make_partitionedrel_pruneinfo(), make_pathtarget_from_tlist(), make_positional_trgm(), make_recursive_union(), make_result_opt_error(), make_row_comparison_op(), make_SAOP_expr(), make_setop(), make_sort_from_groupcols(), make_sort_from_sortclauses(), make_text_key(), make_tuple_from_result_row(), make_tuple_indirect(), make_unique_from_pathkeys(), make_unique_from_sortclauses(), makeaclitem(), makeBufFile(), makeBufFileCommon(), MakeConfigurationMapping(), makeitem(), makeObjectName(), makeParamList(), makepoint(), makeStringInfoInternal(), MakeTidOpExpr(), maketree(), manifest_process_wal_range(), map_variable_attnos_mutator(), mark_hl_fragments(), match_clause_to_partition_key(), MatchNamedCall(), MatchText(), mbuf_create(), mbuf_create_from_data(), mcelem_array_contained_selec(), mcelem_tsquery_selec(), mcv_get_match_bitmap(), minimal_tuple_from_heap_tuple(), mock_scram_secret(), moveLeafs(), mul_var(), multirange_deserialize(), multirange_gist_compress(), multirange_in(), multirange_recv(), multirange_unnest(), MultiXactIdExpand(), mXactCacheGetById(), ndistinct_for_combination(), network_sortsupport(), new_list(), new_object_addresses(), newLexeme(), newTParserPosition(), nextRectBox(), NIAddAffix(), NISortAffixes(), nodeRead(), normal_rand(), NormalizeSubWord(), NUM_cache(), numeric_sortsupport(), numeric_to_char(), numeric_to_number(), numerictypmodout(), offset_to_interval(), oidout(), oidvectorout(), oidvectortypes(), OpenTableList(), OpernameGetCandidates(), optionListToArray(), order_qual_clauses(), ordered_set_startup(), packGraph(), pad_eme_pkcs1_v15(), PageGetTempPage(), PageGetTempPageCopy(), PageGetTempPageCopySpecial(), pairingheap_allocate(), palloc_btree_page(), parse_compress_specification(), parse_datetime(), parse_fcall_arguments(), parse_hstore(), parse_key_value_arrays(), parse_ltree(), parse_one_reloption(), parse_scram_secret(), parse_tsquery(), ParseConfigFp(), parseLocalRelOptions(), ParseLongOption(), parseRelOptions(), partition_bounds_copy(), partition_bounds_create(), path_add(), path_in(), path_poly(), path_recv(), percentile_cont_multi_final_common(), percentile_disc_multi_final(), perform_pruning_base_step(), PerformRadiusTransaction(), pg_armor(), pg_blocking_pids(), pg_buffercache_numa_pages(), pg_buffercache_pages(), pg_convert(), pg_current_snapshot(), pg_dearmor(), pg_decrypt(), pg_decrypt_iv(), pg_detoast_datum_copy(), pg_digest(), pg_encrypt(), pg_encrypt_iv(), pg_get_catalog_foreign_keys(), pg_get_constraintdef_worker(), pg_get_logical_snapshot_info(), pg_get_multixact_members(), pg_get_process_memory_contexts(), pg_get_publication_tables(), pg_get_shmem_allocations_numa(), pg_get_userbyid(), pg_hmac(), pg_import_system_collations(), pg_lock_status(), pg_prepared_xact(), pg_random_bytes(), pg_safe_snapshot_blocking_pids(), pg_snapshot_recv(), pg_timezone_abbrevs_abbrevs(), pg_timezone_abbrevs_zone(), PgArchiverMain(), pgfnames(), pglz_compress_datum(), pglz_decompress_datum(), pglz_decompress_datum_slice(), pgp_armor_headers(), pgp_create_pkt_reader(), pgp_extract_armor_headers(), pgp_key_id_w(), pgp_mpi_alloc(), pgrowlocks(), pgss_shmem_startup(), pgstat_fetch_entry(), pgstat_get_transactional_drops(), pkt_stream_init(), placeChar(), plaintree(), plperl_build_tuple_result(), plperl_ref_from_pg_array(), plperl_spi_exec_prepared(), plperl_spi_prepare(), plperl_spi_query_prepared(), plperl_to_hstore(), plpgsql_add_initdatums(), plpgsql_compile_callback(), plpgsql_finish_datums(), plpgsql_fulfill_promise(), plpgsql_ns_additem(), plpgsql_parse_err_condition(), plpython_to_hstore(), pltcl_quote(), pltcl_SPI_execute_plan(), pltcl_SPI_prepare(), PLy_cursor_plan(), PLy_procedure_munge_source(), PLy_spi_execute_plan(), PLyGenericObject_ToComposite(), PLyMapping_ToComposite(), PLyObject_ToBytea(), PLyObject_ToJsonbValue(), PLySequence_ToComposite(), pnstrdup(), point_add(), point_box(), point_div(), point_in(), point_mul(), point_recv(), point_sub(), points_box(), policy_role_list_to_array(), poly_box(), poly_center(), poly_circle(), poly_path(), populate_array(), populate_array_assign_ndims(), populate_record(), populate_recordset_object_field_end(), populate_scalar(), populate_typ_list(), postmaster_child_launch(), PostmasterMain(), pq_getmsgtext(), prepare_sort_from_pathkeys(), prepare_sql_fn_parse_info(), preparePresortedCols(), PrepareSkipSupportFromOpclass(), preprocess_grouping_sets(), PrescanPreparedTransactions(), ProcArrayApplyRecoveryInfo(), process_pipe_input(), process_startup_options(), ProcessStartupPacket(), prs_setup_firstcall(), prsd_lextype(), psprintf(), publicationListToArray(), pull_up_sublinks_jointree_recurse(), pullf_create(), pushf_create(), pushJsonbValueScalar(), pushquery(), pushState(), pushval_morph(), px_find_cipher(), px_find_digest(), px_find_hmac(), QTNCopy(), queryin(), queue_listen(), quote_identifier(), quote_literal(), quote_literal_cstr(), range_gist_double_sorting_split(), range_gist_picksplit(), range_gist_single_sorting_split(), rbt_create(), RE_compile(), RE_compile_and_cache(), RE_execute(), read_binary_file(), read_client_final_message(), read_dictionary(), read_extension_aux_control_file(), read_stream_begin_impl(), read_whole_file(), readDatum(), readstoplist(), readTimeLineHistory(), readtup_heap(), ReadTwoPhaseFile(), rebuild_database_list(), record_cmp(), record_config_file_error(), record_eq(), record_image_cmp(), record_image_eq(), record_in(), record_out(), record_recv(), record_send(), recordMultipleDependencies(), reduce_expanded_ranges(), reduce_outer_joins_pass1(), regclassout(), regcollationout(), regcomp_auth_token(), regconfigout(), regdictionaryout(), regexec_auth_token(), regexp_fixed_prefix(), regexp_match(), regexp_matches(), register_label_provider(), register_on_commit_action(), RegisterDynamicBackgroundWorker(), regnamespaceout(), regoperout(), regprocout(), regroleout(), regtypeout(), RelationBuildPartitionDesc(), RelationBuildPublicationDesc(), RelationBuildTriggers(), RelationGetExclusionInfo(), RelationGetIndexScan(), RelationGetNotNullConstraints(), RememberManyTestResources(), RememberSyncRequest(), RememberToFreeTupleDescAtEOX(), remove_dbtablespaces(), remove_self_joins_recurse(), RemoveRoleFromObjectPolicy(), ReorderBufferAddInvalidations(), ReorderBufferGetCatalogChangesXacts(), ReorderBufferQueueMessage(), reorderqueue_push(), repeat(), replace_auto_config_value(), replace_text_regexp(), report_json_context(), report_reduced_full_join(), resizeString(), RewriteQuery(), rmtree(), rot13_passphrase(), rpad(), save_state_data(), scanner_init(), scanPendingInsert(), ScanSourceDatabasePgClassTuple(), scram_build_secret(), scram_verify_plain_password(), SearchCatCacheList(), searchRangeTableForCol(), secure_open_server(), seg_in(), seg_inter(), seg_out(), seg_union(), select_active_windows(), select_outer_pathkeys_for_merge(), selectColorTrigrams(), sendDir(), sepgsql_fmgr_hook(), seq_redo(), serialize_expr_stats(), SerializeTransactionState(), set_baserel_partition_key_exprs(), set_plan_references(), set_relation_column_names(), set_rtable_names(), set_var_from_str(), setup_firstcall(), setup_parse_fixed_parameters(), setup_parse_variable_parameters(), setup_pct_info(), setup_regexp_matches(), setup_test_matches(), shm_mq_attach(), show_trgm(), SignalBackends(), similar_escape_internal(), slot_compile_deform(), slot_fill_defaults(), smgr_bulk_start_smgr(), smgrDoPendingDeletes(), smgrDoPendingSyncs(), smgrdounlinkall(), smgrGetPendingDeletes(), SnapBuildInitialSnapshot(), SortAndUniqItems(), spg_box_quad_inner_consistent(), spg_box_quad_picksplit(), spg_kd_inner_consistent(), spg_kd_picksplit(), spg_key_orderbys_distances(), spg_poly_quad_compress(), spg_quad_inner_consistent(), spg_quad_picksplit(), spg_range_quad_inner_consistent(), spg_range_quad_picksplit(), spg_text_choose(), spg_text_inner_consistent(), spg_text_leaf_consistent(), spg_text_picksplit(), spgAddPendingTID(), spgAllocSearchItem(), spgbeginscan(), spgExtractNodeLabels(), spgInnerTest(), spgist_name_choose(), spgist_name_inner_consistent(), spgNewHeapItem(), spgRedoVacuumRedirect(), spgSplitNodeAction(), spi_dest_startup(), SPI_modifytuple(), SPI_register_trigger_data(), split_pathtarget_walker(), SplitToVariants(), ssl_extension_info(), StartPrepare(), startScanKey(), statext_mcv_build(), statext_mcv_clauselist_selectivity(), statext_mcv_deserialize(), statext_ndistinct_build(), statext_ndistinct_deserialize(), statext_ndistinct_serialize(), std_typanalyze(), store_flush_position(), storeGettuple(), StoreRelCheck(), str_casefold(), str_initcap(), str_time(), str_tolower(), str_toupper(), str_udeescape(), stream_start_internal(), string_to_bytea_const(), strlist_to_textarray(), strlower_libc_mb(), strncoll_libc(), strnxfrm_libc(), strtitle_libc_mb(), strupper_libc_mb(), subxact_info_add(), subxact_info_read(), SV_to_JsonbValue(), sync_queue_init(), SyncRepGetCandidateStandbys(), SyncRepGetNthLatestSyncRecPtr(), systable_beginscan(), systable_beginscan_ordered(), table_recheck_autovac(), tablesample_init(), tbm_begin_private_iterate(), test_basic(), test_enc_conversion(), test_pattern(), test_random(), test_re_compile(), test_regex(), test_resowner_many(), test_resowner_priorities(), test_single_value_and_filler(), testdelete(), testprs_lextype(), text_catenate(), text_reverse(), text_substring(), text_to_bits(), text_to_cstring(), thesaurus_lexize(), tidin(), TidListEval(), tidrecv(), time_interval(), time_mi_time(), time_timetz(), timestamp_age(), timestamp_mi(), timestamptz_age(), timestamptz_timetz(), timetz_in(), timetz_izone(), timetz_mi_interval(), timetz_pl_interval(), timetz_recv(), timetz_scale(), timetz_zone(), to_tsvector_byid(), toast_fetch_datum(), toast_fetch_datum_slice(), toast_open_indexes(), toast_save_datum(), TParserInit(), transformFromClauseItem(), transformRangeTableFunc(), transformRelOptions(), translate(), ts_dist(), ts_headline_byid_opt(), ts_headline_json_byid_opt(), ts_headline_jsonb_byid_opt(), ts_lexize(), TS_phrase_output(), ts_process_call(), tsqueryout(), tsqueryrecv(), tsquerytree(), tstz_dist(), tsvector_setweight(), tsvector_setweight_by_filter(), tsvector_to_array(), tsvector_unnest(), tsvector_update_trigger(), tsvectorin(), tsvectorout(), tt_setup_firstcall(), tuple_data_split_internal(), TupleDescGetAttInMetadata(), tuplesort_begin_batch(), tuplesort_begin_datum(), tuplesort_begin_index_btree(), tuplesort_begin_index_gist(), tuplesort_begin_index_hash(), tuplesort_putbrintuple(), tuplesort_putgintuple(), tuplestore_begin_common(), typenameTypeMod(), unicode_is_normalized(), unicode_normalize_func(), uniqueWORD(), update_attstats(), UpdateLogicalMappings(), uuid_decrement(), uuid_in(), uuid_increment(), uuid_out(), uuid_recv(), uuid_skipsupport(), uuid_sortsupport(), vac_open_indexes(), varbit(), varbit_out(), varbit_recv(), varstr_levenshtein(), varstr_sortsupport(), verifybackup_per_wal_range_cb(), widget_in(), worker_spi_main(), WriteBlockRefTable(), xid8out(), xidout(), XLogInsertRecord(), XLogReadRecordAlloc(), XlogReadTwoPhaseData(), xml_recv(), xpath_string(), xpath_table(), xslt_process(), yyalloc(), and yyrealloc().

◆ palloc0()

void * palloc0 ( Size  size)

Definition at line 1973 of file mcxt.c.

1974{
1975 /* duplicates MemoryContextAllocZero to avoid increased overhead */
1976 void *ret;
1978
1979 Assert(MemoryContextIsValid(context));
1981
1982 context->isReset = false;
1983
1984 ret = context->methods->alloc(context, size, 0);
1985 /* We expect OOM to be handled by the alloc function */
1986 Assert(ret != NULL);
1987 VALGRIND_MEMPOOL_ALLOC(context, ret, size);
1988
1989 MemSetAligned(ret, 0, size);
1990
1991 return ret;
1992}

References MemoryContextMethods::alloc, Assert(), AssertNotInCriticalSection, CurrentMemoryContext, MemoryContextData::isReset, MemoryContextIsValid, MemSetAligned, MemoryContextData::methods, and VALGRIND_MEMPOOL_ALLOC.

Referenced by _brin_begin_parallel(), _brin_parallel_scan_and_build(), _bt_begin_parallel(), _bt_buildadd(), _bt_form_posting(), _bt_leader_participate_as_worker(), _bt_load(), _bt_pagestate(), _bt_parallel_build_main(), _bt_parallel_scan_and_sort(), _bt_spools_heapscan(), _bt_truncate(), _bt_update_posting(), _gin_begin_parallel(), _gin_build_tuple(), _gin_parallel_scan_and_build(), _h_spoolinit(), _ltq_extract_regex(), _ltree_extract_isparent(), _ltree_extract_risparent(), _ltxtq_extract_exec(), _SPI_make_plan_non_temp(), _SPI_save_plan(), accum_sum_rescale(), add_column_to_pathtarget(), add_dummy_return(), add_foreign_final_paths(), add_foreign_ordered_paths(), add_sp_item_to_pathtarget(), addFkRecurseReferencing(), allocacl(), AllocateRelationDesc(), allocateReloptStruct(), AllocateSnapshotBuilder(), AlterObjectNamespace_internal(), AlterObjectOwner_internal(), AlterObjectRename_internal(), AlterOpFamilyAdd(), AlterOpFamilyDrop(), appendSCRAMKeysInfo(), array_cat(), array_create_iterator(), array_get_slice(), array_in(), array_map(), array_recv(), array_replace_internal(), array_set_element(), array_set_slice(), array_to_tsvector(), astreamer_extractor_new(), astreamer_gzip_decompressor_new(), astreamer_gzip_writer_new(), astreamer_lz4_compressor_new(), astreamer_lz4_decompressor_new(), astreamer_plain_writer_new(), astreamer_recovery_injector_new(), astreamer_tar_archiver_new(), astreamer_tar_parser_new(), astreamer_tar_terminator_new(), astreamer_verify_content_new(), astreamer_zstd_compressor_new(), astreamer_zstd_decompressor_new(), ATAddCheckNNConstraint(), ATExecAddColumn(), ATExecAlterConstrEnforceability(), ATExecSetExpression(), ATGetQueueEntry(), ATPrepAlterColumnType(), bbsink_copystream_new(), bbsink_gzip_new(), bbsink_lz4_new(), bbsink_progress_new(), bbsink_server_new(), bbsink_throttle_new(), bbsink_zstd_new(), begin_heap_rewrite(), BeginCopyFrom(), BeginCopyTo(), bernoulli_initsamplescan(), BipartiteMatch(), bit(), bit_in(), blbulkdelete(), blgetbitmap(), BlockRefTableEntryMarkBlockModified(), bloom_create(), bloom_init(), BloomFormTuple(), blvacuumcleanup(), bms_add_range(), bms_make_singleton(), bpchar_name(), brin_bloom_opcinfo(), brin_form_placeholder_tuple(), brin_form_tuple(), brin_inclusion_opcinfo(), brin_minmax_multi_opcinfo(), brin_minmax_multi_union(), brin_minmax_opcinfo(), brin_new_memtuple(), brin_range_serialize(), brinbuild(), bt_check_every_level(), bt_page_print_tuples(), btbulkdelete(), btvacuumcleanup(), build_distances(), build_expanded_ranges(), build_expr_data(), build_inet_union_key(), build_pertrans_for_aggref(), build_row_from_vars(), build_simple_rel(), build_sorted_items(), BuildEventTriggerCache(), buildint2vector(), buildNSItemFromLists(), buildNSItemFromTupleDesc(), buildoidvector(), calc_rank_and(), calc_rank_cd(), calc_word_similarity(), check_hba(), check_ident_usermap(), check_tuple_attribute(), cidr_set_masklen_internal(), circle_poly(), collect_corrupt_items(), collect_visibility_data(), combo_init(), compact_palloc0(), CompactCheckpointerRequestQueue(), compile_plperl_function(), compile_pltcl_function(), compute_partition_bounds(), connect_pg_server(), construct_empty_array(), construct_md_array(), copy_ltree(), CopyCachedPlan(), create_array_envelope(), create_edata_for_relation(), create_foreign_modify(), create_groupingsets_plan(), create_hash_bounds(), create_list_bounds(), create_queryEnv(), create_range_bounds(), CreateBlockRefTableEntry(), CreateBlockRefTableReader(), CreateBlockRefTableWriter(), CreateCachedPlan(), CreateExplainSerializeDestReceiver(), CreateFakeRelcacheEntry(), CreateIncrementalBackupInfo(), CreateIntoRelDestReceiver(), CreateOneShotCachedPlan(), CreateParallelContext(), CreateSQLFunctionDestReceiver(), CreateTransientRelDestReceiver(), CreateTupleDescCopyConstr(), CreateTupleQueueDestReceiver(), CreateTupleQueueReader(), CreateTuplestoreDestReceiver(), crosstab(), cryptohash_internal(), cube_a_f8(), cube_a_f8_f8(), cube_c_f8(), cube_c_f8_f8(), cube_enlarge(), cube_f8(), cube_f8_f8(), cube_inter(), cube_subset(), cube_union_v0(), deconstruct_array(), DefineOpClass(), deparse_context_for(), deparse_context_for_plan_tree(), DependencyGenerator_init(), dintdict_init(), dintdict_lexize(), disassembleLeaf(), dispell_init(), do_analyze_rel(), doPickSplit(), dsimple_init(), dsimple_lexize(), dsm_impl_mmap(), dsnowball_init(), dsnowball_lexize(), dsynonym_init(), dsynonym_lexize(), dxsyn_init(), each_worker(), elements_worker(), encrypt_init(), EnumValuesCreate(), eqjoinsel_inner(), eqjoinsel_semi(), estimate_multivariate_bucketsize(), EvalPlanQualInit(), EvalPlanQualStart(), EventTriggerCollectAlterDefPrivs(), EventTriggerCollectAlterTSConfig(), EventTriggerCollectCreateOpClass(), EventTriggerSQLDropAddObject(), examine_attribute(), examine_expression(), ExecBuildAuxRowMark(), ExecBuildGroupingEqual(), ExecBuildHash32Expr(), ExecBuildHash32FromAttrs(), ExecBuildParamSetEqual(), ExecEvalArrayExpr(), ExecEvalHashedScalarArrayOp(), ExecGrant_Relation(), ExecIndexBuildScanKeys(), ExecInitAgg(), ExecInitAppend(), ExecInitBitmapAnd(), ExecInitBitmapOr(), ExecInitExprRec(), ExecInitFunc(), ExecInitGatherMerge(), ExecInitGenerated(), ExecInitHashJoin(), ExecInitIndexScan(), ExecInitJsonExpr(), ExecInitJunkFilterConversion(), ExecInitMergeAppend(), ExecInitParallelPlan(), ExecInitRangeTable(), ExecInitResultRelation(), ExecInitSetOp(), ExecInitSubscriptingRef(), ExecInitValuesScan(), ExecInitWindowAgg(), ExecReScanHashJoin(), ExecSetupPartitionTupleRouting(), expand_partitioned_rtentry(), expand_tuple(), expand_virtual_generated_columns(), ExplainCreateWorkersState(), extract_jsp_query(), extract_rollup_sets(), extract_variadic_args(), fetch_more_data(), fetch_remote_table_info(), fetch_statentries_for_relation(), fillFakeState(), find_partition_scheme(), find_window_functions(), findeq(), formrdesc(), g_intbig_consistent(), gather_merge_setup(), gbt_macad8_union(), gbt_macad_union(), gbt_num_bin_union(), gbt_num_compress(), gbt_var_key_copy(), gbt_var_node_truncate(), generate_base_implied_equalities_no_const(), generate_combinations(), generate_dependencies(), get_crosstab_tuplestore(), get_json_object_as_hash(), get_matching_hash_bounds(), get_matching_list_bounds(), get_matching_partitions(), get_matching_range_bounds(), get_relation_info(), get_subscription_list(), get_worker(), GetAccessStrategyWithSize(), GetAfterTriggersTableData(), getColorInfo(), GetLockConflicts(), GetSearchPathMatcher(), getTokenTypes(), GetWALBlockInfo(), gin_check_parent_keys_consistency(), gin_check_posting_tree_parent_keys_consistency(), gin_extract_tsquery(), GinBufferInit(), ginbuild(), ginbulkdelete(), ginExtractEntries(), ginFillScanKey(), ginScanToDelete(), ginvacuumcleanup(), gist_box_picksplit(), gist_indexsortbuild(), gist_indexsortbuild_levelstate_add(), gist_indexsortbuild_levelstate_flush(), gistbeginscan(), gistbulkdelete(), gistdoinsert(), gistFindPath(), gistUserPicksplit(), gistvacuumcleanup(), hash_array(), hashagg_batch_new(), hashagg_spill_init(), hashbulkdelete(), heap_form_minimal_tuple(), heap_form_tuple(), heap_toast_insert_or_update(), heap_tuple_infomask_flags(), heap_vacuum_rel(), heapam_index_fetch_begin(), hmac_init(), identify_join_columns(), index_concurrently_create_copy(), inet_gist_compress(), inet_gist_fetch(), inetand(), inetnot(), inetor(), init_returning_filter(), InitCatCache(), InitExecPartitionPruneContexts(), initHyperLogLog(), initialize_brin_insertstate(), InitializeParallelDSM(), InitPartitionPruneContext(), InitPlan(), InitResultRelInfo(), initSpGistState(), inittapes(), InitWalRecovery(), InitXLogReaderState(), inline_function(), inner_subltree(), InstrAlloc(), int2vectorin(), internal_inetpl(), interpret_AS_clause(), interpret_function_parameter_list(), interval_avg_deserialize(), iterate_json_values(), iteratorFromContainer(), join_tsqueries(), json_array_length(), json_object_keys(), json_strip_nulls(), jsonb_agg_transfn_worker(), jsonb_exec_setup(), jsonb_object_agg_transfn_worker(), jsonb_set_element(), JsonTableInitOpaque(), JsonTableInitPlan(), LaunchParallelWorkers(), lca_inner(), leader_takeover_tapes(), leftmostvalue_macaddr(), leftmostvalue_macaddr8(), leftmostvalue_name(), leftmostvalue_uuid(), libpqrcv_connect(), libpqrcv_exec(), llvm_resolve_symbols(), load_relcache_init_file(), load_validator_library(), LoadArchiveLibrary(), logicalrep_read_tuple(), ltree_concat(), ltree_picksplit(), ltree_union(), macaddr8_and(), macaddr8_in(), macaddr8_not(), macaddr8_or(), macaddr8_recv(), macaddr8_set7bit(), macaddr8_trunc(), macaddr8tomacaddr(), macaddrtomacaddr8(), make_attrmap(), make_auth_token(), make_callstmt_target(), make_inh_translation_list(), make_multirange(), make_one_partition_rbound(), make_parsestate(), make_partition_pruneinfo(), make_partitionedrel_pruneinfo(), make_setop_translation_list(), make_sort_input_target(), make_tsvector(), make_tuple_from_result_row(), make_tuple_indirect(), makeArrayResultArr(), makeDefaultBloomOptions(), makeIntervalAggState(), makeNumericAggState(), makeNumericAggStateCurrentContext(), MakeTransitionCaptureState(), MakeTupleTableSlot(), mcv_clause_selectivity_or(), mdcbuf_init(), mergeruns(), minmax_multi_init(), MJExamineQuals(), mkVoidAffix(), multi_sort_init(), multirange_constructor2(), multirange_get_range(), multirange_intersect_internal(), multirange_minus_internal(), multirange_union(), nameconcatoid(), namein(), namerecv(), ndistinct_for_combination(), network_broadcast(), network_hostmask(), network_in(), network_netmask(), network_network(), network_recv(), new_intArrayType(), NewExplainState(), newNode(), newRegisNode(), NIImportOOAffixes(), NISortDictionary(), oauth_init(), oidvectorin(), ordered_set_startup(), overexplain_ensure_options(), pa_launch_parallel_worker(), parallel_vacuum_end(), parallel_vacuum_init(), ParallelSlotsSetup(), parse_hba_line(), parse_ident_line(), parse_lquery(), parse_ltree(), parse_tsquery(), perform_base_backup(), perform_pruning_combine_step(), pg_backup_start(), pg_buffercache_numa_pages(), pg_crypt(), pg_decode_startup(), pg_get_shmem_allocations_numa(), pg_logical_slot_get_changes_guts(), pg_stat_get_wal_receiver(), pg_tzenumerate_start(), pgoutput_startup(), pgoutput_truncate(), pgp_cfb_create(), pgp_init(), pgp_key_alloc(), placeChar(), plperl_build_tuple_result(), plperl_modify_tuple(), plperl_ref_from_pg_array(), plperl_spi_prepare(), plpgsql_build_recfield(), plpgsql_build_record(), plpgsql_build_variable(), plpgsql_compile_inline(), plsample_func_handler(), pltcl_build_tuple_result(), pltcl_SPI_prepare(), PLy_modify_tuple(), PLy_procedure_create(), PLy_spi_prepare(), poly_in(), poly_recv(), populate_array_assign_ndims(), populate_recordset_worker(), postgresBeginDirectModify(), postgresBeginForeignScan(), postgresGetForeignJoinPaths(), postgresGetForeignRelSize(), postgresGetForeignUpperPaths(), pq_init(), prepare_query_params(), prepare_sql_fn_parse_info(), PrepareForIncrementalBackup(), PrepareInplaceInvalidationState(), preparePresortedCols(), preprocess_grouping_sets(), printtup_create_DR(), printtup_prepare_info(), ProcessCopyOptions(), prune_append_rel_partitions(), pull_up_constant_function(), pull_up_simple_subquery(), pull_up_simple_values(), pullf_create(), push_path(), pushf_create(), pushOperator(), pushStop(), pushValue_internal(), px_crypt_shacrypt(), px_find_combo(), QT2QTN(), QTN2QT(), QTNBinary(), queryin(), QueueCheckConstraintValidation(), QueueFKConstraintValidation(), range_agg_finalfn(), range_serialize(), read_tablespace_map(), refresh_by_match_merge(), regcomp_auth_token(), RelationBuildLocalRelation(), RelationBuildPartitionKey(), RelationBuildTriggers(), RelationFindReplTupleByIndex(), RelationFindReplTupleSeq(), RelationGetIndexAttOptions(), remap_groupColIdx(), remove_useless_groupby_columns(), ReorderBufferProcessTXN(), ReorderBufferToastReplace(), retrieve_objects(), reverse_name(), rewriteTargetListIU(), rewriteValuesRTE(), RT_BEGIN_ITERATE(), save_state_data(), scram_init(), selectColorTrigrams(), sepgsql_avc_compute(), sepgsql_set_client_label(), serialize_prepare_info(), set_append_rel_size(), set_baserel_partition_key_exprs(), set_deparse_for_query(), set_join_column_names(), set_joinrel_partition_key_exprs(), set_plan_references(), set_simple_column_names(), set_subquery_pathlist(), SetExplainExtensionState(), setup_regexp_matches(), setup_simple_rel_arrays(), setup_test_matches(), shell_get_sink(), SnapBuildSerialize(), spg_quad_picksplit(), spgbeginscan(), spgbuild(), spgbulkdelete(), spgFormInnerTuple(), spgFormLeafTuple(), spgFormNodeTuple(), spgist_name_leaf_consistent(), spgvacuumcleanup(), spi_dest_startup(), standard_ExecutorStart(), standard_join_search(), StartPrepare(), StartupDecodingContext(), statext_dependencies_build(), statext_dependencies_deserialize(), statext_dependencies_serialize(), statext_mcv_build(), statext_mcv_deserialize(), statext_mcv_serialize(), statext_ndistinct_deserialize(), sts_attach(), sts_initialize(), SummarizeWAL(), synchronize_slots(), system_initsamplescan(), system_rows_initsamplescan(), system_time_initsamplescan(), tbm_attach_shared_iterate(), test_create(), test_rls_hooks_permissive(), test_rls_hooks_restrictive(), testdelete(), testprs_start(), text_name(), thesaurus_init(), TidExprListCreate(), TidStoreAttach(), TidStoreBeginIterate(), TidStoreCreateLocal(), TidStoreCreateShared(), toast_flatten_tuple_to_datum(), tokenize_auth_file(), TParserCopyInit(), TParserInit(), transform_json_string_values(), transformFromClauseItem(), transformSetOperationStmt(), transformValuesClause(), transformWithClause(), trgm_presence_map(), ts_headline_json_byid_opt(), ts_headline_jsonb_byid_opt(), ts_setup_firstcall(), tsquery_not(), tsqueryrecv(), tsvector_concat(), tsvector_delete_arr(), tsvector_delete_by_indices(), tsvector_filter(), tsvector_strip(), tsvectorin(), tsvectorrecv(), TupleDescGetAttInMetadata(), tuplesort_begin_cluster(), tuplesort_begin_common(), tuplesort_begin_datum(), tuplesort_begin_heap(), tuplesort_begin_index_btree(), tuplesort_begin_index_gin(), tuplesort_begin_index_gist(), tuplestore_begin_common(), unaccent_lexize(), vacuum_all_databases(), validate(), varbit_in(), XLogPrefetcherAllocate(), and XmlTableInitOpaque().

◆ palloc_aligned()

void * palloc_aligned ( Size  size,
Size  alignto,
int  flags 
)

Definition at line 2140 of file mcxt.c.

2141{
2142 return MemoryContextAllocAligned(CurrentMemoryContext, size, alignto, flags);
2143}
void * MemoryContextAllocAligned(MemoryContext context, Size size, Size alignto, int flags)
Definition: mcxt.c:2038

References CurrentMemoryContext, and MemoryContextAllocAligned().

Referenced by _mdfd_getseg(), GenericXLogStart(), InitCatCache(), and modify_rel_block().

◆ palloc_extended()

void * palloc_extended ( Size  size,
int  flags 
)

Definition at line 1995 of file mcxt.c.

1996{
1997 /* duplicates MemoryContextAllocExtended to avoid increased overhead */
1998 void *ret;
2000
2001 Assert(MemoryContextIsValid(context));
2003
2004 context->isReset = false;
2005
2006 ret = context->methods->alloc(context, size, flags);
2007 if (unlikely(ret == NULL))
2008 {
2009 /* NULL can be returned only when using MCXT_ALLOC_NO_OOM */
2010 Assert(flags & MCXT_ALLOC_NO_OOM);
2011 return NULL;
2012 }
2013
2014 VALGRIND_MEMPOOL_ALLOC(context, ret, size);
2015
2016 if ((flags & MCXT_ALLOC_ZERO) != 0)
2017 MemSetAligned(ret, 0, size);
2018
2019 return ret;
2020}

References MemoryContextMethods::alloc, Assert(), AssertNotInCriticalSection, CurrentMemoryContext, MemoryContextData::isReset, MCXT_ALLOC_NO_OOM, MCXT_ALLOC_ZERO, MemoryContextIsValid, MemSetAligned, MemoryContextData::methods, unlikely, and VALGRIND_MEMPOOL_ALLOC.

Referenced by AllocDeadEndChild(), pg_clean_ascii(), and XLogReaderAllocate().

◆ pchomp()

◆ pfree()

void pfree ( void *  pointer)

Definition at line 2150 of file mcxt.c.

2151{
2152#ifdef USE_VALGRIND
2154 MemoryContext context = GetMemoryChunkContext(pointer);
2155#endif
2156
2157 MCXT_METHOD(pointer, free_p) (pointer);
2158
2159#ifdef USE_VALGRIND
2160 if (method != MCTX_ALIGNED_REDIRECT_ID)
2161 VALGRIND_MEMPOOL_FREE(context, pointer);
2162#endif
2163}
static MemoryContextMethodID GetMemoryChunkMethodID(const void *pointer)
Definition: mcxt.c:222
MemoryContext GetMemoryChunkContext(void *pointer)
Definition: mcxt.c:738
#define VALGRIND_MEMPOOL_FREE(context, addr)
Definition: memdebug.h:30

References GetMemoryChunkContext(), GetMemoryChunkMethodID(), MCTX_ALIGNED_REDIRECT_ID, MCXT_METHOD, and VALGRIND_MEMPOOL_FREE.

Referenced by _brin_parallel_merge(), _bt_array_decrement(), _bt_array_increment(), _bt_array_set_low_or_high(), _bt_bottomupdel_pass(), _bt_buildadd(), _bt_dedup_finish_pending(), _bt_dedup_pass(), _bt_delitems_delete(), _bt_delitems_delete_check(), _bt_delitems_vacuum(), _bt_doinsert(), _bt_findsplitloc(), _bt_freestack(), _bt_getroot(), _bt_gettrueroot(), _bt_insert_parent(), _bt_insertonpg(), _bt_load(), _bt_newlevel(), _bt_parallel_restore_arrays(), _bt_pendingfsm_finalize(), _bt_preprocess_array_keys(), _bt_simpledel_pass(), _bt_skiparray_set_element(), _bt_skiparray_set_isnull(), _bt_sort_dedup_finish_pending(), _bt_split(), _bt_spooldestroy(), _bt_truncate(), _bt_uppershutdown(), _fdvec_resize(), _gin_build_tuple(), _gin_process_worker_data(), _h_spooldestroy(), _hash_splitbucket(), _hash_squeezebucket(), _int_contains(), _int_inter(), _int_overlap(), _int_same(), _int_union(), _lca(), _mdfd_getseg(), AbsorbSyncRequests(), accum_sum_rescale(), accumArrayResultArr(), aclmerge(), add_partial_path(), add_path(), addArcs(), AddEnumLabel(), AddFileToBackupManifest(), addFkRecurseReferenced(), addHLParsedLex(), addItemPointersToLeafTuple(), addKey(), adjust_appendrel_attrs_multilevel(), adjust_child_relids_multilevel(), advance_windowaggregate(), advance_windowaggregate_base(), afterTriggerDeleteHeadEventChunk(), AfterTriggerEndSubXact(), afterTriggerFreeEventList(), afterTriggerRestoreEventList(), agg_refill_hash_table(), AlignedAllocFree(), AlignedAllocRealloc(), allocate_recordbuf(), AlterObjectNamespace_internal(), AlterObjectOwner_internal(), AlterObjectRename_internal(), amvalidate(), appendJSONKeyValueFmt(), appendSCRAMKeysInfo(), AppendStringCommandOption(), appendStringInfoStringQuoted(), apply_scanjoin_target_to_paths(), apw_dump_now(), array_free_iterator(), array_in(), array_map(), array_out(), array_recv(), array_replace_internal(), array_reverse_n(), array_send(), array_set_element_expanded(), array_shuffle_n(), array_to_json_internal(), array_to_jsonb_internal(), array_to_text_internal(), arrayconst_cleanup_fn(), arrayexpr_cleanup_fn(), ArrayGetIntegerTypmods(), ASN1_STRING_to_text(), assign_simple_var(), AssignTransactionId(), astreamer_extractor_free(), astreamer_plain_writer_free(), astreamer_recovery_injector_free(), astreamer_tar_archiver_free(), astreamer_tar_parser_free(), astreamer_tar_terminator_free(), astreamer_verify_free(), Async_Notify(), AtEOSubXact_Inval(), AtEOSubXact_on_commit_actions(), AtEOSubXact_PgStat(), AtEOSubXact_PgStat_DroppedStats(), AtEOSubXact_PgStat_Relations(), AtEOXact_GUC(), AtEOXact_on_commit_actions(), AtEOXact_PgStat_DroppedStats(), AtEOXact_RelationCache(), ATPrepAlterColumnType(), AtSubAbort_childXids(), AtSubAbort_Notify(), AtSubAbort_Snapshot(), AtSubCommit_childXids(), AtSubCommit_Notify(), AttrDefaultFetch(), autoinc(), BackendInitialize(), bbsink_server_begin_archive(), bbsink_server_begin_manifest(), bbsink_server_end_manifest(), be_tls_close(), be_tls_open_server(), binaryheap_free(), bind_param_error_callback(), BipartiteMatchFree(), blendscan(), blgetbitmap(), BlockRefTableEntryMarkBlockModified(), BlockRefTableFreeEntry(), BlockRefTableReaderNextRelation(), bloom_free(), blrescan(), bms_add_members(), bms_del_member(), bms_del_members(), bms_free(), bms_int_members(), bms_intersect(), bms_join(), bms_replace_members(), boolop(), BootstrapModeMain(), BootStrapXLOG(), bottomup_sort_and_shrink(), bpcharfastcmp_c(), bpcharrecv(), bqarr_in(), brin_bloom_union(), brin_build_desc(), brin_form_tuple(), brin_free_tuple(), brin_inclusion_add_value(), brin_inclusion_union(), brin_minmax_add_value(), brin_minmax_multi_distance_inet(), brin_minmax_multi_union(), brin_minmax_union(), brin_page_items(), brinendscan(), brininsertcleanup(), brinRevmapTerminate(), brinsummarize(), bt_check_level_from_leftmost(), bt_child_check(), bt_child_highkey_check(), bt_downlink_missing_check(), bt_leftmost_ignoring_half_dead(), bt_normalize_tuple(), bt_page_print_tuples(), bt_right_page_check_scankey(), bt_rootdescend(), bt_target_page_check(), bt_tuple_present_callback(), btendscan(), btinsert(), btree_xlog_updates(), btvacuumpage(), buf_finalize(), BufferSync(), BufFileClose(), BufFileOpenFileSet(), build_backup_content(), build_child_join_sjinfo(), build_EvalXFuncInt(), build_index_paths(), build_local_reloptions(), build_pertrans_for_aggref(), build_reloptions(), build_sorted_items(), buildFreshLeafTuple(), BuildRestoreCommand(), BuildTupleFromCStrings(), cache_single_string(), calc_arraycontsel(), calc_distr(), calc_rank_and(), calc_rank_cd(), calc_rank_or(), calc_word_similarity(), cancel_on_dsm_detach(), casefold(), cash_words(), CatalogCloseIndexes(), CatCacheFreeKeys(), CatCacheRemoveCList(), CatCacheRemoveCTup(), char2wchar(), check_application_name(), check_circularity(), check_cluster_name(), check_control_files(), check_createrole_self_grant(), check_datestyle(), check_db_file_conflict(), check_debug_io_direct(), check_default_text_search_config(), check_ident_usermap(), check_locale(), check_log_connections(), check_log_destination(), check_oauth_validator(), check_publications_origin(), check_relation_privileges(), check_restrict_nonsystem_relation_kind(), check_schema_perms(), check_search_path(), check_synchronized_standby_slots(), check_temp_tablespaces(), check_timezone(), check_wal_consistency_checking(), CheckAffix(), CheckAlterSubOption(), checkclass_str(), checkcondition_str(), CheckForBufferLeaks(), CheckForLocalBufferLeaks(), CheckIndexCompatible(), CheckMD5Auth(), CheckNNConstraintFetch(), CheckPasswordAuth(), CheckPointTwoPhase(), CheckPWChallengeAuth(), CheckRADIUSAuth(), CheckSASLAuth(), checkSharedDependencies(), ChooseConstraintName(), ChooseExtendedStatisticName(), ChooseRelationName(), citext_eq(), citext_hash(), citext_hash_extended(), citext_ne(), citextcmp(), clauselist_apply_dependencies(), clauselist_selectivity_ext(), clean_NOT_intree(), clean_stopword_intree(), cleanup_directories_atexit(), cleanup_subxact_info(), clear_and_pfree(), close_tsvector_parser(), ClosePostmasterPorts(), collectMatchBitmap(), combo_free(), combo_init(), CompactCheckpointerRequestQueue(), compareJsonbContainers(), compareStrings(), compile_plperl_function(), compile_pltcl_function(), compileTheLexeme(), compileTheSubstitute(), compute_array_stats(), compute_tsvector_stats(), concat_internal(), connect_pg_server(), construct_empty_expanded_array(), ConstructTupleDescriptor(), convert_any_priv_string(), convert_charset(), convert_column_name(), convert_string_datum(), convert_to_scalar(), convertPgWchar(), copy_dest_destroy(), copy_file(), copy_table(), CopyArrayEls(), CopyFromErrorCallback(), CopyFromTextLikeOneRow(), CopyMultiInsertBufferCleanup(), copyTemplateDependencies(), core_yyfree(), count_usable_fds(), create_cursor(), create_hash_bounds(), create_list_bounds(), create_partitionwise_grouping_paths(), create_range_bounds(), create_script_for_old_cluster_deletion(), create_secmsg(), create_tablespace_directories(), CreateCheckPoint(), CreateDatabaseUsingFileCopy(), CreateDatabaseUsingWalLog(), createdb(), createNewConnection(), createPostingTree(), CreateStatistics(), CreateTableSpace(), CreateTriggerFiringOn(), croak_cstr(), crosstab(), cstr2sv(), datetime_format_has_tz(), datetime_to_char_body(), datum_image_eq(), datum_image_hash(), datum_to_json_internal(), datum_to_jsonb_internal(), datumSerialize(), db_encoding_convert(), dbase_redo(), dblink_connect(), dblink_disconnect(), dblink_security_check(), DCH_to_char(), deallocate_query(), DecodeTextArrayToBitmapset(), DeconstructFkConstraintRow(), DefineDomain(), DefineEnum(), DefineIndex(), DefineRange(), DefineType(), deparseConst(), dependencies_clauselist_selectivity(), DependencyGenerator_free(), deserialize_deflist(), destroy_tablespace_directories(), DestroyBlockRefTableReader(), DestroyBlockRefTableWriter(), DestroyParallelContext(), destroyStringInfo(), DestroyTupleQueueReader(), detoast_attr(), detoast_attr_slice(), digest_free(), dintdict_lexize(), dir_realloc(), dispell_lexize(), div_var(), do_analyze_rel(), do_autovacuum(), Do_MultiXactIdWait(), do_pg_backup_start(), do_pg_backup_stop(), do_text_output_multiline(), do_to_timestamp(), DoesMultiXactIdConflict(), dofindsubquery(), dotrim(), DropRelationFiles(), DropRelationsAllBuffers(), dsa_detach(), dshash_destroy(), dshash_detach(), dsimple_lexize(), dsm_create(), dsm_detach(), dsm_impl_sysv(), dsnowball_lexize(), dsynonym_init(), dsynonym_lexize(), dxsyn_lexize(), ecpg_filter_source(), ecpg_filter_stderr(), ecpg_postprocess_result(), elog_node_display(), emit_audit_message(), encrypt_free(), end_tup_output(), EndCopy(), EndCopyFrom(), enlarge_list(), entry_dealloc(), entry_purge_tuples(), entryLoadMoreItems(), enum_range_internal(), enum_recv(), EnumValuesCreate(), eqjoinsel_inner(), eqjoinsel_semi(), escape_json_text(), eval_windowaggregates(), EventTriggerAlterTableEnd(), EventTriggerSQLDropAddObject(), examine_attribute(), examine_expression(), exec_bind_message(), exec_command_conninfo(), exec_object_restorecon(), exec_stmt_foreach_a(), Exec_UnlistenCommit(), ExecAggCopyTransValue(), ExecDropSingleTupleTableSlot(), ExecEndWindowAgg(), ExecEvalPreOrderedDistinctSingle(), ExecEvalXmlExpr(), ExecFetchSlotHeapTupleDatum(), ExecForceStoreHeapTuple(), ExecForceStoreMinimalTuple(), ExecGrant_Attribute(), ExecGrant_common(), ExecGrant_Largeobject(), ExecGrant_Parameter(), ExecGrant_Relation(), ExecHashIncreaseNumBatches(), ExecHashRemoveNextSkewBucket(), ExecHashTableDestroy(), ExecIndexBuildScanKeys(), ExecInitGenerated(), ExecInitHashJoin(), ExecInitMemoize(), ExecParallelCleanup(), ExecParallelFinish(), ExecParallelHashCloseBatchAccessors(), ExecParallelHashRepartitionRest(), ExecReScanTidScan(), ExecResetTupleTable(), ExecSetParamPlan(), ExecSetSlotDescriptor(), ExecShutdownGatherMergeWorkers(), ExecShutdownGatherWorkers(), execute_foreign_modify(), executeDateTimeMethod(), executeItemOptUnwrapTarget(), ExecuteRecoveryCommand(), expand_dynamic_library_name(), expanded_record_set_field_internal(), expanded_record_set_fields(), expanded_record_set_tuple(), ExplainFlushWorkersState(), ExplainProperty(), ExplainPropertyFloat(), ExplainPropertyList(), ExplainQuery(), extract_autovac_opts(), extract_rollup_sets(), fetch_finfo_record(), fetch_function_defaults(), fetch_remote_table_info(), fetch_statentries_for_relation(), fetch_table_list(), file_acquire_sample_rows(), filter_list_to_array(), finalize_aggregates(), FinalizeIncrementalManifest(), find_in_path(), find_inheritance_children_extended(), find_other_exec(), find_provider(), findDependentObjects(), findeq(), findJsonbValueFromContainer(), finish_edata(), FinishPreparedTransaction(), fix_merged_indexes(), fixup_inherited_columns(), flush_pipe_input(), FlushRelationsAllBuffers(), fmgr_info_C_lang(), fmgr_info_cxt_security(), ForgetBackgroundWorker(), ForgetManyTestResources(), form_and_insert_tuple(), form_and_spill_tuple(), free_attrmap(), free_attstatsslot(), free_child_join_sjinfo(), free_chromo(), free_conversion_map(), free_edge_table(), free_object_addresses(), free_openssl_cipher(), free_openssl_digest(), free_parsestate(), free_partition_map(), free_pool(), free_sort_tuple(), FreeAccessStrategy(), freeAndGetParent(), FreeBulkInsertState(), FreeConfigVariable(), FreeErrorData(), FreeErrorDataContents(), FreeExprContext(), FreeFakeRelcacheEntry(), freeGinBtreeStack(), freeHyperLogLog(), FreeQueryDesc(), FreeSnapshot(), FreeSubscription(), freetree(), FreeTriggerDesc(), FreeTupleDesc(), FreeWaitEventSet(), FreeWaitEventSetAfterFork(), FreezeMultiXactId(), func_get_detail(), FuncnameGetCandidates(), g_int_compress(), g_int_consistent(), g_int_decompress(), g_int_penalty(), g_int_picksplit(), g_intbig_consistent(), g_intbig_picksplit(), gather_merge_clear_tuples(), gbt_bit_l2n(), gen_ossl_free(), generate_append_tlist(), generate_base_implied_equalities_no_const(), generate_combinations(), generate_dependencies(), generate_error_response(), generate_matching_part_pairs(), generate_trgm_only(), generate_wildcard_trgm(), generateClonedExtStatsStmt(), generateHeadline(), generator_free(), GenericXLogAbort(), GenericXLogFinish(), get_attstatsslot(), get_const_expr(), get_control_dbstate(), get_docrep(), get_extension_aux_control_filename(), get_extension_control_directories(), get_extension_script_filename(), get_flush_position(), get_from_clause(), get_opmethod_canorder(), get_relation_statistics(), get_reloptions(), get_sql_insert(), get_sql_update(), get_str_from_var_sci(), get_target_list(), get_tuple_of_interest(), get_typdefault(), GetAggInitVal(), getColorInfo(), GetConfFilesInDir(), GetMultiXactIdHintBits(), getNextNearest(), getObjectDescription(), getObjectIdentityParts(), getPublicationSchemaInfo(), GetTempNamespaceProcNumber(), GetWALRecordsInfo(), gin_check_parent_keys_consistency(), gin_check_posting_tree_parent_keys_consistency(), gin_extract_jsonb_path(), gin_leafpage_items(), gin_trgm_triconsistent(), GinBufferFree(), GinBufferReset(), GinBufferStoreTuple(), ginCompressPostingList(), ginendscan(), ginEntryFillRoot(), ginEntryInsert(), ginExtractEntries(), ginFinishSplit(), ginFlushBuildState(), GinFormTuple(), ginFreeScanKeys(), ginPostingListDecodeAllSegmentsToTbm(), ginVacuumEntryPage(), ginVacuumPostingTree(), ginVacuumPostingTreeLeaf(), gist_indexsortbuild(), gist_indexsortbuild_levelstate_flush(), gist_ischild(), gistgetbitmap(), gistgettuple(), gistPopItupFromNodeBuffer(), gistRelocateBuildBuffersOnSplit(), gistrescan(), gistunionsubkeyvec(), gistUnloadNodeBuffer(), group_similar_or_args(), gtrgm_consistent(), gtrgm_distance(), gtrgm_penalty(), gtsvector_penalty(), guc_free(), GUCArrayReset(), hash_record(), hash_record_extended(), hashagg_finish_initial_spills(), hashagg_reset_spill_state(), hashagg_spill_finish(), hashagg_spill_tuple(), hashbpchar(), hashbpcharextended(), hashbuildCallback(), hashendscan(), hashinsert(), hashtext(), hashtextextended(), heap_create_with_catalog(), heap_endscan(), heap_force_common(), heap_free_minimal_tuple(), heap_freetuple(), heap_lock_tuple(), heap_lock_updated_tuple_rec(), heap_modify_tuple(), heap_modify_tuple_by_cols(), heap_tuple_infomask_flags(), heap_tuple_should_freeze(), heap_vacuum_rel(), heapam_index_fetch_end(), heapam_relation_copy_for_cluster(), heapam_tuple_complete_speculative(), heapam_tuple_insert(), heapam_tuple_insert_speculative(), heapam_tuple_update(), hmac_finish(), hmac_free(), hmac_init(), hstoreUniquePairs(), hv_fetch_string(), hv_store_string(), icu_language_tag(), index_compute_xid_horizon_for_tuples(), index_concurrently_create_copy(), index_form_tuple_context(), index_store_float8_orderby_distances(), index_truncate_tuple(), IndexScanEnd(), IndexSupportsBackwardScan(), infix(), initcap(), InitExecPartitionPruneContexts(), initialize_reloptions(), InitializeSystemUser(), InitIndexAmRoutine(), InitPostgres(), initTrie(), InitWalRecovery(), inner_int_inter(), insert_username(), InsertOneTuple(), InsertPgAttributeTuples(), internal_citext_pattern_cmp(), internalerrquery(), intorel_destroy(), intset_subtract(), inv_close(), inv_getsize(), inv_read(), inv_truncate(), inv_write(), InvalidateAttoptCacheCallback(), InvalidateTableSpaceCacheCallback(), irbt_free(), isAnyTempNamespace(), isolation_start_test(), isRelDataFile(), iterate_jsonb_values(), iterate_word_similarity(), jit_release_context(), json_manifest_finalize_file(), json_manifest_finalize_wal_range(), json_manifest_object_field_start(), json_manifest_scalar(), json_object(), json_object_keys(), json_object_two_arg(), json_parse_manifest_incremental_shutdown(), json_unique_object_end(), json_unique_object_field_start(), jsonb_object(), jsonb_object_two_arg(), jsonb_set_element(), JsonbDeepContains(), JsonbValue_to_SV(), JsonItemFromDatum(), jsonpath_send(), jsonpath_yyfree(), KnownAssignedXidsDisplay(), lazy_cleanup_one_index(), lazy_vacuum_one_index(), lca(), leafRepackItems(), libpq_destroy(), libpqrcv_alter_slot(), libpqrcv_connect(), libpqrcv_create_slot(), libpqrcv_disconnect(), libpqrcv_get_dbname_from_conninfo(), libpqrcv_startstreaming(), like_fixed_prefix(), list_delete_first_n(), list_delete_nth_cell(), list_free_private(), llvm_compile_module(), llvm_copy_attributes_at_index(), llvm_release_context(), llvm_resolve_symbol(), llvm_resolve_symbols(), lo_manage(), load_backup_manifest(), load_enum_cache_data(), load_external_function(), load_file(), load_libraries(), load_relcache_init_file(), local_destroy(), LockAcquireExtended(), log_status_format(), logfile_rotate_dest(), logical_heap_rewrite_flush_mappings(), logicalrep_relmap_free_entry(), logicalrep_write_tuple(), LogicalTapeClose(), LogicalTapeFreeze(), LogicalTapeRewindForRead(), LogicalTapeSetClose(), LogRecoveryConflict(), LogStandbySnapshot(), lookup_ts_config_cache(), lookup_var_attr_stats(), LookupGXact(), lower(), lquery_recv(), lquery_send(), lrq_free(), ltree_addtext(), ltree_picksplit(), ltree_recv(), ltree_send(), ltree_strncasecmp(), ltree_textadd(), ltxtq_recv(), ltxtq_send(), lz4_compress_datum(), main(), make_greater_string(), make_partition_pruneinfo(), make_partitionedrel_pruneinfo(), make_SAOP_expr(), make_scalar_key(), make_tsvector(), make_tuple_indirect(), makeArrayTypeName(), makeMultirangeConstructors(), map_sql_value_to_xml_value(), mark_hl_fragments(), MatchText(), MaybeRemoveOldWalSummaries(), mbuf_free(), mcelem_array_contained_selec(), mcelem_array_selec(), mcelem_tsquery_selec(), mcv_clause_selectivity_or(), mcv_get_match_bitmap(), mdcbuf_free(), merge_acl_with_grant(), merge_clump(), mergeruns(), mkANode(), moddatetime(), mode_final(), moveArrayTypeName(), movedb(), movedb_failure_callback(), mul_var(), multirange_recv(), MultiXactIdExpand(), MultiXactIdGetUpdateXid(), MultiXactIdIsRunning(), mXactCachePut(), mxid_to_string(), namerecv(), next_field_expand(), NIImportAffixes(), NIImportDictionary(), NIImportOOAffixes(), NINormalizeWord(), NormalizeSubWord(), NUM_cache(), numeric_abbrev_convert(), numeric_fast_cmp(), numeric_float4(), numeric_float8(), numeric_to_number(), numericvar_to_double_no_overflow(), object_aclmask_ext(), overexplain_alias(), overexplain_bitmapset(), overexplain_intlist(), pa_free_worker_info(), pa_launch_parallel_worker(), pad_eme_pkcs1_v15(), PageRestoreTempPage(), pagetable_free(), pair_encode(), pairingheap_free(), parallel_vacuum_end(), parallel_vacuum_init(), parallel_vacuum_process_one_index(), ParameterAclLookup(), parse_and_validate_value(), parse_args(), parse_compress_specification(), parse_extension_control_file(), parse_fcall_arguments(), parse_hba_line(), parse_lquery(), parse_ltree(), parse_manifest_file(), parse_one_reloption(), parse_subscription_options(), parse_tsquery(), parseCommandLine(), ParseConfigFile(), ParseConfigFp(), parseNameAndArgTypes(), parseRelOptionsInternal(), parsetext(), patternsel_common(), pclose_check(), perform_base_backup(), perform_work_item(), PerformAuthentication(), PerformRadiusTransaction(), PerformWalRecovery(), pg_armor(), pg_attribute_aclcheck_all_ext(), pg_attribute_aclmask_ext(), pg_backup_stop(), pg_be_scram_build_secret(), pg_class_aclmask_ext(), pg_convert(), pg_crypt(), pg_dearmor(), pg_decode_commit_txn(), pg_decode_stream_abort(), pg_decode_stream_commit(), pg_encrypt(), pg_extension_update_paths(), pg_get_constraintdef_worker(), pg_get_expr_worker(), pg_get_function_arg_default(), pg_get_indexdef_worker(), pg_get_line(), pg_get_multixact_members(), pg_get_partkeydef_worker(), pg_get_statisticsobj_worker(), pg_get_statisticsobjdef_expressions(), pg_get_wal_block_info(), pg_get_wal_record_info(), pg_identify_object_as_address(), pg_largeobject_aclmask_snapshot(), pg_namespace_aclmask_ext(), pg_parameter_acl_aclmask(), pg_parameter_aclmask(), pg_parse_query(), pg_plan_query(), pg_replication_origin_create(), pg_replication_origin_drop(), pg_replication_origin_oid(), pg_replication_origin_session_setup(), pg_rewrite_query(), pg_split_opts(), pg_stat_file(), pg_stat_get_activity(), pg_stat_get_backend_activity(), pg_stat_statements_internal(), pg_sync_replication_slots(), pg_tablespace_databases(), pg_type_aclmask_ext(), pg_tzenumerate_end(), pg_tzenumerate_next(), pgfnames_cleanup(), pglz_compress_datum(), pgoutput_commit_txn(), pgp_cfb_free(), pgp_create_pkt_reader(), pgp_free(), pgp_key_free(), pgp_mpi_free(), pgss_shmem_startup(), pgss_store(), pgstat_delete_pending_entry(), pgstat_release_entry_ref(), pkt_stream_free(), pktreader_free(), plainnode(), plperl_build_tuple_result(), plperl_call_perl_func(), plperl_hash_from_tuple(), plperl_modify_tuple(), plperl_spi_exec_prepared(), plperl_spi_prepare(), plperl_spi_query_prepared(), plperl_sv_to_datum(), plperl_trigger_handler(), plperl_util_elog(), plpgsql_compile_callback(), plpgsql_destroy_econtext(), plpgsql_extra_checks_check_hook(), plpgsql_subxact_cb(), pltcl_build_tuple_argument(), pltcl_func_handler(), pltcl_quote(), pltcl_set_tuple_values(), pltcl_trigger_handler(), PLy_abort_open_subtransactions(), PLy_elog_impl(), PLy_function_drop_args(), PLy_function_restore_args(), PLy_input_setup_tuple(), PLy_modify_tuple(), PLy_output(), PLy_output_setup_tuple(), PLy_pop_execution_context(), PLy_procedure_compile(), PLy_procedure_create(), PLy_quote_literal(), PLy_quote_nullable(), PLy_subtransaction_exit(), PLy_traceback(), PLy_trigger_build_args(), PLyGenericObject_ToComposite(), PLyMapping_ToComposite(), PLyNumber_ToJsonbValue(), PLySequence_ToComposite(), PLyUnicode_Bytes(), PLyUnicode_FromScalar(), PLyUnicode_FromStringAndSize(), PopActiveSnapshot(), PopTransaction(), populate_array(), populate_record(), populate_scalar(), PortalDrop(), postgresExecForeignTruncate(), postgresGetForeignJoinPaths(), PostmasterMain(), PostPrepare_smgr(), pprint(), pq_endmessage(), pq_puttextmessage(), pq_sendcountedtext(), pq_sendstring(), pq_sendtext(), pq_writestring(), PrepareTempTablespaces(), preprocessNamespacePath(), PrescanPreparedTransactions(), print(), print_expr(), print_function_arguments(), printtup_destroy(), printtup_prepare_info(), printtup_shutdown(), ProcArrayApplyRecoveryInfo(), process_directory_recursively(), process_ordered_aggregate_single(), process_pipe_input(), process_postgres_switches(), process_target_wal_block_change(), ProcessCommittedInvalidationMessages(), ProcessConfigFileInternal(), ProcessGUCArray(), ProcessParallelApplyMessages(), ProcessParallelMessages(), ProcessPgArchInterrupts(), ProcessStandbyHSFeedbackMessage(), ProcessStandbyReplyMessage(), ProcessWalSndrMessage(), ProcSleep(), prs_process_call(), prune_element_hashtable(), prune_lexemes_hashtable(), psprintf(), psql_add_command(), psql_start_test(), pullf_free(), pushf_free(), PushTransaction(), pushval_morph(), px_crypt_shacrypt(), px_find_cipher(), px_find_combo(), px_find_digest(), QTNFree(), QTNTernary(), queryin(), range_fast_cmp(), range_recv(), rbt_populate(), RE_compile(), RE_compile_and_cache(), RE_execute(), read_client_final_message(), read_dictionary(), read_pg_version_file(), read_stream_end(), ReadArrayStr(), readfile(), readstoplist(), reconstruct_from_incremental_file(), record_cmp(), record_eq(), record_image_cmp(), record_image_eq(), record_in(), record_out(), record_recv(), record_send(), recordMultipleDependencies(), RecordTransactionAbort(), RecordTransactionCommit(), RecoverPreparedTransactions(), recursive_revoke(), recv_password_packet(), regcomp_auth_token(), regex_fixed_prefix(), regexec_auth_token(), regexp_fixed_prefix(), regression_main(), RehashCatCache(), RehashCatCacheLists(), reindex_one_database(), ReinitializeParallelDSM(), RelationBuildPartitionKey(), RelationBuildPublicationDesc(), RelationBuildRowSecurity(), RelationBuildRuleLock(), RelationBuildTriggers(), RelationBuildTupleDesc(), RelationCacheInitializePhase3(), RelationDestroyRelation(), RelationGetDummyIndexExpressions(), RelationGetIndexAttOptions(), RelationGetIndexExpressions(), RelationGetIndexPredicate(), RelationInvalidateRelation(), RelationParseRelOptions(), RelationPreserveStorage(), RelationReloadIndexInfo(), ReleaseDummy(), ReleaseManyTestResource(), ReleasePostmasterChildSlot(), relmap_redo(), remove_cache_entry(), remove_dbtablespaces(), remove_leftjoinrel_from_query(), remove_self_join_rel(), RemoveLocalLock(), RenameTypeInternal(), ReorderBufferFreeChange(), ReorderBufferFreeRelids(), ReorderBufferFreeSnap(), ReorderBufferFreeTupleBuf(), ReorderBufferFreeTXN(), ReorderBufferIterTXNFinish(), ReorderBufferToastReplace(), ReorderBufferToastReset(), reorderqueue_pop(), replace_auto_config_value(), replace_text(), replace_text_regexp(), replication_scanner_finish(), ReplicationSlotDropAtPubNode(), ReplicationSlotRelease(), ReplSlotSyncWorkerMain(), report_corruption_internal(), report_triggers(), reportDependentObjects(), ReportGUCOption(), ReportSlotInvalidation(), reset_directory_cleanup_list(), reset_on_dsm_detach(), ResetDecoder(), resetSpGistScanOpaque(), resolve_aggregate_transtype(), ResourceOwnerDelete(), ResourceOwnerEnlarge(), ResourceOwnerReleaseAll(), restore_all_databases(), RestoreArchivedFile(), rewriteTargetListIU(), rewriteValuesRTE(), rm_redo_error_callback(), rmtree(), RS_free(), RT_END_ITERATE(), RT_FREE(), RT_FREE_LEAF(), RT_FREE_NODE(), run_ssl_passphrase_command(), scanner_finish(), scanPendingInsert(), scram_verify_plain_password(), secure_open_server(), select_active_windows(), select_outer_pathkeys_for_merge(), send_message_to_frontend(), send_message_to_server_log(), sendDir(), SendFunctionResult(), sepgsql_attribute_drop(), sepgsql_attribute_post_create(), sepgsql_attribute_relabel(), sepgsql_attribute_setattr(), sepgsql_avc_check_perms(), sepgsql_avc_compute(), sepgsql_avc_reclaim(), sepgsql_database_drop(), sepgsql_database_post_create(), sepgsql_database_relabel(), sepgsql_database_setattr(), sepgsql_proc_drop(), sepgsql_proc_execute(), sepgsql_proc_post_create(), sepgsql_proc_relabel(), sepgsql_proc_setattr(), sepgsql_relation_drop(), sepgsql_relation_post_create(), sepgsql_relation_relabel(), sepgsql_relation_setattr(), sepgsql_relation_truncate(), sepgsql_schema_drop(), sepgsql_schema_post_create(), sepgsql_schema_relabel(), sepgsql_xact_callback(), seq_redo(), seq_search_localized(), serialize_deflist(), serialize_prepare_info(), serializeAnalyzeDestroy(), serializeAnalyzeShutdown(), set_append_rel_size(), set_customscan_references(), set_foreignscan_references(), set_indexonlyscan_references(), set_join_references(), set_plan_refs(), set_returning_clause_references(), set_subquery_pathlist(), set_upper_references(), set_var_from_str(), set_windowagg_runcondition_references(), SetClientEncoding(), setCorrLex(), setNewTmpRes(), setup_regexp_matches(), setup_test_matches(), shdepLockAndCheckObject(), shell_archive_file(), shell_finish_command(), shm_mq_detach(), shm_mq_receive(), show_memoize_info(), show_trgm(), show_window_def(), show_window_keys(), ShowAllGUCConfig(), ShowTransactionStateRec(), ShowUsage(), ShutdownExprContext(), SignalBackends(), similarity(), single_encode(), slotsync_reread_config(), smgr_bulk_flush(), smgrDoPendingDeletes(), smgrDoPendingSyncs(), smgrdounlinkall(), SnapBuildFreeSnapshot(), SnapBuildPurgeOlderTxn(), SnapBuildRestore(), SnapBuildSerialize(), spg_box_quad_inner_consistent(), spgClearPendingList(), spgdoinsert(), spgendscan(), spgFreeSearchItem(), spggettuple(), spgRedoVacuumRedirect(), SPI_cursor_open(), SPI_modifytuple(), SPI_pfree(), split_text(), SplitIdentifierString(), SplitToVariants(), sqlfunction_destroy(), StandbyRecoverPreparedTransactions(), StandbyTransactionIdIsPrepared(), start_table_sync(), StartPrepare(), startScanEntry(), StartupRereadConfig(), statext_mcv_build(), statext_mcv_deserialize(), statext_mcv_serialize(), StoreAttrDefault(), storeObjectDescription(), StorePartitionKey(), StoreRelCheck(), storeRow(), string_to_text(), stringToQualifiedNameList(), strlower_libc_mb(), strncoll_libc(), strnxfrm_libc(), strtitle_libc_mb(), strupper_libc_mb(), sts_end_write(), sts_read_tuple(), SummarizeWAL(), sync_queue_destroy(), synchronize_slots(), SyncPostCheckpoint(), syncrep_scanner_finish(), SyncRepGetNthLatestSyncRecPtr(), SyncRepGetSyncRecPtr(), SysLogger_Start(), SysLoggerMain(), systable_beginscan(), systable_beginscan_ordered(), systable_endscan(), systable_endscan_ordered(), tablesample_init(), TablespaceCreateDbspace(), tbm_end_private_iterate(), tbm_end_shared_iterate(), tbm_free(), terminate_brin_buildstate(), test_basic(), test_destroy(), test_enc_conversion(), test_random(), test_re_compile(), test_shm_mq_setup(), test_singlerowmode(), testdelete(), testprs_end(), text2ltree(), text_format(), text_format_string_conversion(), text_substring(), text_to_cstring(), text_to_cstring_buffer(), text_to_stavalues(), textrecv(), textToQualifiedNameList(), thesaurus_lexize(), thesaurusRead(), TidListEval(), TidStoreDestroy(), TidStoreDetach(), TidStoreEndIterate(), toast_build_flattened_tuple(), toast_close_indexes(), toast_compress_datum(), toast_flatten_tuple(), toast_flatten_tuple_to_datum(), toast_tuple_cleanup(), toast_tuple_externalize(), toast_tuple_try_compression(), tokenize_auth_file(), tokenize_expand_file(), tokenize_include_file(), TParserClose(), TParserCopyClose(), TParserGet(), tqueueDestroyReceiver(), tqueueReceiveSlot(), TransformGUCArray(), transformRangeTableFunc(), transientrel_destroy(), try_partitionwise_join(), ts_accum(), TS_execute_locations_recurse(), ts_headline_byid_opt(), ts_headline_json_byid_opt(), ts_headline_jsonb_byid_opt(), ts_lexize(), ts_match_tq(), ts_match_tt(), ts_process_call(), ts_stat_sql(), tsearch_readline(), tsearch_readline_end(), tsquery_rewrite_query(), tsqueryrecv(), tsquerytree(), tstoreDestroyReceiver(), tstoreReceiveSlot_detoast(), tstoreShutdownReceiver(), tsvector_delete_arr(), tsvector_to_array(), tsvector_update_trigger(), tsvectorin(), tt_process_call(), tts_virtual_clear(), tuple_data_split(), tuple_data_split_internal(), tuplesort_begin_batch(), tuplesort_begin_cluster(), tuplesort_begin_index_btree(), tuplestore_advance(), tuplestore_end(), tuplestore_skiptuples(), tuplestore_trim(), typeDepNeeded(), typenameTypeMod(), unaccent_dict(), uniqueentry(), uniqueWORD(), unistr(), UnregisterExprContextCallback(), UnregisterResourceReleaseCallback(), UnregisterSubXactCallback(), UnregisterXactCallback(), updateAclDependenciesWorker(), UpdateIndexRelation(), UpdateLogicalMappings(), upper(), uuid_decrement(), uuid_increment(), vac_close_indexes(), validate(), validate_remote_info(), varcharrecv(), varlenafastcmp_locale(), varstr_abbrev_convert(), varstrfastcmp_c(), verify_backup_checksums(), verify_cb(), verify_control_file(), verify_plain_backup_directory(), verify_tar_backup(), wait_for_connection_state(), WaitForOlderSnapshots(), WaitForParallelWorkersToExit(), walrcv_clear_result(), WalRcvFetchTimeLineHistoryFiles(), WalReceiverMain(), worker_freeze_result_tape(), write_auto_conf_file(), write_console(), write_csvlog(), write_jsonlog(), write_reconstructed_file(), X509_NAME_field_to_text(), X509_NAME_to_cstring(), XLogDecodeNextRecord(), XLogDumpDisplayRecord(), XLogInsertRecord(), XLogPrefetcherFree(), XLogReaderAllocate(), XLogReaderFree(), XLogReleasePreviousRecord(), XLOGShmemInit(), xml_encode_special_chars(), xml_out_internal(), xml_recv(), xml_send(), xmlconcat(), xmlpi(), xpath_bool(), xpath_list(), xpath_nodeset(), xpath_number(), xpath_string(), xpath_table(), and yyfree().

◆ pnstrdup()

◆ ProcessGetMemoryContextInterrupt()

void ProcessGetMemoryContextInterrupt ( void  )

Definition at line 1436 of file mcxt.c.

1437{
1438 List *contexts;
1439 HASHCTL ctl;
1440 HTAB *context_id_lookup;
1441 int context_id = 0;
1442 MemoryStatsEntry *meminfo;
1443 bool summary = false;
1444 int max_stats;
1445 int idx = MyProcNumber;
1446 int stats_count = 0;
1447 int stats_num = 0;
1449 int num_individual_stats = 0;
1450
1452
1453 /*
1454 * The hash table is used for constructing "path" column of the view,
1455 * similar to its local backend counterpart.
1456 */
1457 ctl.keysize = sizeof(MemoryContext);
1458 ctl.entrysize = sizeof(MemoryStatsContextId);
1460
1461 context_id_lookup = hash_create("pg_get_remote_backend_memory_contexts",
1462 256,
1463 &ctl,
1465
1466 /* List of contexts to process in the next round - start at the top. */
1467 contexts = list_make1(TopMemoryContext);
1468
1469 /* Compute the number of stats that can fit in the defined limit */
1470 max_stats =
1473 summary = memCxtState[idx].summary;
1474 LWLockRelease(&memCxtState[idx].lw_lock);
1475
1476 /*
1477 * Traverse the memory context tree to find total number of contexts. If
1478 * summary is requested report the total number of contexts at level 1 and
1479 * 2 from the top. Also, populate the hash table of context ids.
1480 */
1481 compute_contexts_count_and_ids(contexts, context_id_lookup, &stats_count,
1482 summary);
1483
1484 /*
1485 * Allocate memory in this process's DSA for storing statistics of the
1486 * memory contexts upto max_stats, for contexts that don't fit within a
1487 * limit, a cumulative total is written as the last record in the DSA
1488 * segment.
1489 */
1490 stats_num = Min(stats_count, max_stats);
1491
1493
1494 /*
1495 * Create a DSA and send handle to the client process after storing the
1496 * context statistics. If number of contexts exceed a predefined
1497 * limit(8MB), a cumulative total is stored for such contexts.
1498 */
1500 {
1502 dsa_handle handle;
1503
1505
1507
1509 MemoryContextSwitchTo(oldcontext);
1510
1512
1513 /*
1514 * Pin the DSA area, this is to make sure the area remains attachable
1515 * even if current backend exits. This is done so that the statistics
1516 * are published even if the process exits while a client is waiting.
1517 */
1519
1520 /* Set the handle in shared memory */
1522 }
1523
1524 /*
1525 * If DSA exists, created by another process publishing statistics, attach
1526 * to it.
1527 */
1528 else if (MemoryStatsDsaArea == NULL)
1529 {
1531
1534 MemoryContextSwitchTo(oldcontext);
1536 }
1538
1539 /*
1540 * Hold the process lock to protect writes to process specific memory. Two
1541 * processes publishing statistics do not block each other.
1542 */
1545
1546 if (DsaPointerIsValid(memCxtState[idx].memstats_dsa_pointer))
1547 {
1548 /*
1549 * Free any previous allocations, free the name, ident and path
1550 * pointers before freeing the pointer that contains them.
1551 */
1553 memCxtState[idx].memstats_dsa_pointer);
1554 }
1555
1556 /*
1557 * Assigning total stats before allocating memory so that memory cleanup
1558 * can run if any subsequent dsa_allocate call to allocate name/ident/path
1559 * fails.
1560 */
1561 memCxtState[idx].total_stats = stats_num;
1564
1565 meminfo = (MemoryStatsEntry *)
1566 dsa_get_address(MemoryStatsDsaArea, memCxtState[idx].memstats_dsa_pointer);
1567
1568 if (summary)
1569 {
1570 int cxt_id = 0;
1571 List *path = NIL;
1572
1573 /* Copy TopMemoryContext statistics to DSA */
1574 memset(&stat, 0, sizeof(stat));
1576 &stat, true);
1577 path = lcons_int(1, path);
1578 PublishMemoryContext(meminfo, cxt_id, TopMemoryContext, path, stat,
1579 1, MemoryStatsDsaArea, 100);
1580 cxt_id = cxt_id + 1;
1581
1582 /*
1583 * Copy statistics for each of TopMemoryContexts children. This
1584 * includes statistics of at most 100 children per node, with each
1585 * child node limited to a depth of 100 in its subtree.
1586 */
1587 for (MemoryContext c = TopMemoryContext->firstchild; c != NULL;
1588 c = c->nextchild)
1589 {
1590 MemoryContextCounters grand_totals;
1591 int num_contexts = 0;
1592
1593 path = NIL;
1594 memset(&grand_totals, 0, sizeof(grand_totals));
1595
1596 MemoryContextStatsInternal(c, 1, 100, 100, &grand_totals,
1597 PRINT_STATS_NONE, &num_contexts);
1598
1599 path = compute_context_path(c, context_id_lookup);
1600
1601 /*
1602 * Register the stats entry first, that way the cleanup handler
1603 * can reach it in case of allocation failures of one or more
1604 * members.
1605 */
1606 memCxtState[idx].total_stats = cxt_id++;
1607 PublishMemoryContext(meminfo, cxt_id, c, path,
1608 grand_totals, num_contexts, MemoryStatsDsaArea, 100);
1609 }
1610 memCxtState[idx].total_stats = cxt_id;
1611
1613
1614 /* Notify waiting backends and return */
1615 hash_destroy(context_id_lookup);
1616
1617 return;
1618 }
1619
1621 {
1622 List *path = NIL;
1623
1624 /*
1625 * Figure out the transient context_id of this context and each of its
1626 * ancestors, to compute a path for this context.
1627 */
1628 path = compute_context_path(cur, context_id_lookup);
1629
1630 /* Examine the context stats */
1631 memset(&stat, 0, sizeof(stat));
1632 (*cur->methods->stats) (cur, NULL, NULL, &stat, true);
1633
1634 /* Account for saving one statistics slot for cumulative reporting */
1635 if (context_id < (max_stats - 1) || stats_count <= max_stats)
1636 {
1637 /* Copy statistics to DSA memory */
1638 PublishMemoryContext(meminfo, context_id, cur, path, stat, 1, MemoryStatsDsaArea, 100);
1639 }
1640 else
1641 {
1642 meminfo[max_stats - 1].totalspace += stat.totalspace;
1643 meminfo[max_stats - 1].nblocks += stat.nblocks;
1644 meminfo[max_stats - 1].freespace += stat.freespace;
1645 meminfo[max_stats - 1].freechunks += stat.freechunks;
1646 }
1647
1648 /*
1649 * DSA max limit per process is reached, write aggregate of the
1650 * remaining statistics.
1651 *
1652 * We can store contexts from 0 to max_stats - 1. When stats_count is
1653 * greater than max_stats, we stop reporting individual statistics
1654 * when context_id equals max_stats - 2. As we use max_stats - 1 array
1655 * slot for reporting cumulative statistics or "Remaining Totals".
1656 */
1657 if (stats_count > max_stats && context_id == (max_stats - 2))
1658 {
1659 char *nameptr;
1660 int namelen = strlen("Remaining Totals");
1661
1662 num_individual_stats = context_id + 1;
1663 meminfo[max_stats - 1].name = dsa_allocate(MemoryStatsDsaArea, namelen + 1);
1664 nameptr = dsa_get_address(MemoryStatsDsaArea, meminfo[max_stats - 1].name);
1665 strncpy(nameptr, "Remaining Totals", namelen);
1666 meminfo[max_stats - 1].ident = InvalidDsaPointer;
1667 meminfo[max_stats - 1].path = InvalidDsaPointer;
1668 meminfo[max_stats - 1].type = 0;
1669 }
1670 context_id++;
1671 }
1672
1673 /*
1674 * Statistics are not aggregated, i.e individual statistics reported when
1675 * stats_count <= max_stats.
1676 */
1677 if (stats_count <= max_stats)
1678 {
1679 memCxtState[idx].total_stats = context_id;
1680 }
1681 /* Report number of aggregated memory contexts */
1682 else
1683 {
1684 meminfo[max_stats - 1].num_agg_stats = context_id -
1685 num_individual_stats;
1686
1687 /*
1688 * Total stats equals num_individual_stats + 1 record for cumulative
1689 * statistics.
1690 */
1691 memCxtState[idx].total_stats = num_individual_stats + 1;
1692 }
1693
1694 /* Notify waiting backends and return */
1696
1697 hash_destroy(context_id_lookup);
1698}
#define Min(x, y)
Definition: c.h:975
void dsa_pin_mapping(dsa_area *area)
Definition: dsa.c:635
dsa_handle dsa_get_handle(dsa_area *area)
Definition: dsa.c:498
void dsa_pin(dsa_area *area)
Definition: dsa.c:975
#define dsa_allocate0(area, size)
Definition: dsa.h:113
#define dsa_allocate(area, size)
Definition: dsa.h:109
dsm_handle dsa_handle
Definition: dsa.h:136
#define dsa_create(tranch_id)
Definition: dsa.h:117
void hash_destroy(HTAB *hashp)
Definition: dynahash.c:866
HTAB * hash_create(const char *tabname, long nelem, const HASHCTL *info, int flags)
Definition: dynahash.c:352
int MyProcPid
Definition: globals.c:48
#define HASH_CONTEXT
Definition: hsearch.h:102
#define HASH_ELEM
Definition: hsearch.h:95
#define HASH_BLOBS
Definition: hsearch.h:97
static void compute_contexts_count_and_ids(List *contexts, HTAB *context_id_lookup, int *stats_count, bool summary)
Definition: mcxt.c:1745
static void PublishMemoryContext(MemoryStatsEntry *memcxt_info, int curr_id, MemoryContext context, List *path, MemoryContextCounters stat, int num_contexts, dsa_area *area, int max_levels)
Definition: mcxt.c:1793
static void end_memorycontext_reporting(void)
Definition: mcxt.c:1705
static List * compute_context_path(MemoryContext c, HTAB *context_id_lookup)
Definition: mcxt.c:1719
#define MEMORY_CONTEXT_REPORT_MAX_PER_BACKEND
Definition: memutils.h:61
struct MemoryStatsContextId MemoryStatsContextId
#define MAX_MEMORY_CONTEXT_STATS_SIZE
Definition: memutils.h:69
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:124
struct MemoryContextData * MemoryContext
Definition: palloc.h:36
#define list_make1(x1)
Definition: pg_list.h:212
tree ctl
Definition: radixtree.h:1838
Definition: dynahash.c:220
uint16 tranche
Definition: lwlock.h:43
LWLock lw_lock
Definition: memutils.h:367
int64 totalspace
Definition: memutils.h:351
dsa_pointer ident
Definition: memutils.h:346
dsa_pointer name
Definition: memutils.h:345
int64 freechunks
Definition: memutils.h:354
dsa_pointer path
Definition: memutils.h:347
NodeTag type
Definition: memutils.h:348
#define stat
Definition: win32_port.h:274

References compute_context_path(), compute_contexts_count_and_ids(), ctl, cur, CurrentMemoryContext, dsa_allocate, dsa_allocate0, dsa_attach(), dsa_create, dsa_get_address(), dsa_get_handle(), DSA_HANDLE_INVALID, dsa_pin(), dsa_pin_mapping(), DsaPointerIsValid, end_memorycontext_reporting(), MemoryContextData::firstchild, foreach_ptr, free_memorycontextstate_dsa(), MemoryStatsEntry::freechunks, MemoryStatsEntry::freespace, HASH_BLOBS, HASH_CONTEXT, hash_create(), hash_destroy(), HASH_ELEM, MemoryStatsEntry::ident, idx(), InvalidDsaPointer, lcons_int(), list_make1, LW_EXCLUSIVE, MemoryStatsCtl::lw_lock, LWLockAcquire(), LWLockRelease(), MAX_MEMORY_CONTEXT_STATS_SIZE, memCxtArea, memCxtState, MEMORY_CONTEXT_REPORT_MAX_PER_BACKEND, MemoryContextStatsInternal(), MemoryContextSwitchTo(), MemoryStatsDsaArea, MemoryStatsCtl::memstats_dsa_handle, MemoryStatsBackendState::memstats_dsa_pointer, MemoryContextData::methods, Min, MyProcNumber, MyProcPid, name, MemoryStatsEntry::name, MemoryStatsEntry::nblocks, MemoryContextData::nextchild, NIL, MemoryStatsEntry::num_agg_stats, MemoryStatsEntry::path, PRINT_STATS_NONE, MemoryStatsBackendState::proc_id, PublishMemoryContext(), PublishMemoryContextPending, stat, MemoryContextMethods::stats, MemoryStatsBackendState::summary, TopMemoryContext, MemoryStatsBackendState::total_stats, MemoryStatsEntry::totalspace, LWLock::tranche, and MemoryStatsEntry::type.

Referenced by ProcessAutoVacLauncherInterrupts(), ProcessCheckpointerInterrupts(), ProcessInterrupts(), ProcessMainLoopInterrupts(), ProcessPgArchInterrupts(), ProcessStartupProcInterrupts(), and ProcessWalSummarizerInterrupts().

◆ ProcessLogMemoryContextInterrupt()

void ProcessLogMemoryContextInterrupt ( void  )

Definition at line 1384 of file mcxt.c.

1385{
1387
1388 /*
1389 * Use LOG_SERVER_ONLY to prevent this message from being sent to the
1390 * connected client.
1391 */
1393 (errhidestmt(true),
1394 errhidecontext(true),
1395 errmsg("logging memory contexts of PID %d", MyProcPid)));
1396
1397 /*
1398 * When a backend process is consuming huge memory, logging all its memory
1399 * contexts might overrun available disk space. To prevent this, we limit
1400 * the depth of the hierarchy, as well as the number of child contexts to
1401 * log per parent to 100.
1402 *
1403 * As with MemoryContextStats(), we suppose that practical cases where the
1404 * dump gets long will typically be huge numbers of siblings under the
1405 * same parent context; while the additional debugging value from seeing
1406 * details about individual siblings beyond 100 will not be large.
1407 */
1409}

References ereport, errhidecontext(), errhidestmt(), errmsg(), LOG_SERVER_ONLY, LogMemoryContextPending, MemoryContextStatsDetail(), MyProcPid, and TopMemoryContext.

Referenced by ProcessAutoVacLauncherInterrupts(), ProcessCheckpointerInterrupts(), ProcessInterrupts(), ProcessMainLoopInterrupts(), ProcessPgArchInterrupts(), ProcessStartupProcInterrupts(), and ProcessWalSummarizerInterrupts().

◆ pstrdup()

char * pstrdup ( const char *  in)

Definition at line 2325 of file mcxt.c.

2326{
2328}
char * MemoryContextStrdup(MemoryContext context, const char *string)
Definition: mcxt.c:2312

References CurrentMemoryContext, and MemoryContextStrdup().

Referenced by AbsoluteConfigLocation(), accesstype_arg_to_string(), add_row_identity_var(), add_with_check_options(), addCompiledLexeme(), addFkConstraint(), addRangeTableEntryForFunction(), addRangeTableEntryForGroup(), addRangeTableEntryForSubquery(), addRangeTableEntryForTableFunc(), addRangeTableEntryForValues(), AddRelationNotNullConstraints(), addToResult(), allocate_reloption(), AlterRole(), analyzeCTETargetList(), anytime_typmodout(), anytimestamp_typmodout(), append_database_pattern(), append_relation_pattern_helper(), append_schema_pattern(), ApplyRetrieveRule(), array_out(), astreamer_extractor_new(), astreamer_gzip_writer_new(), astreamer_plain_writer_new(), ATExecAddIndexConstraint(), ATExecAlterConstraint(), ATExecAlterConstrEnforceability(), ATParseTransformCmd(), BaseBackupAddTarget(), BeginCopyFrom(), BeginCopyTo(), BootstrapModeMain(), BufFileCreateFileSet(), BufFileOpenFileSet(), build_datatype(), build_minmax_path(), build_server_first_message(), buildDefItem(), BuildOnConflictExcludedTargetlist(), buildRelationAliases(), BuildRestoreCommand(), CatalogCacheInitializeCache(), check_createrole_self_grant(), check_datestyle(), check_debug_io_direct(), check_hostname(), check_locale(), check_log_connections(), check_log_destination(), check_oauth_validator(), check_restrict_nonsystem_relation_kind(), check_search_path(), check_selective_binary_conversion(), check_synchronized_standby_slots(), check_temp_tablespaces(), check_timezone(), check_tuple_header(), check_tuple_visibility(), check_valid_internal_signature(), check_wal_consistency_checking(), checkInsertTargets(), ChooseExtendedStatisticNameAddition(), ChooseForeignKeyConstraintNameAddition(), ChooseIndexColumnNames(), ChooseIndexNameAddition(), CloneRowTriggersToPartition(), compile_database_list(), compile_plperl_function(), compile_pltcl_function(), compile_relation_list_one_db(), compileTheSubstitute(), connectby_text(), connectby_text_serial(), convert_GUC_name_for_parameter_acl(), convert_string_datum(), CopyCachedPlan(), CopyErrorData(), CopyLimitPrintoutLength(), CopyTriggerDesc(), copyTSLexeme(), CopyVar(), create_foreign_modify(), CreateCachedPlan(), CreateLockFile(), createNewConnection(), CreateParallelContext(), CreateSchemaCommand(), CreateTableSpace(), CreateTupleDescCopyConstr(), cstring_in(), cstring_out(), datasegpath(), date_out(), dbase_redo(), defGetString(), DefineQueryRewrite(), DefineView(), DefineViewRules(), deleteConnection(), destroy_tablespace_directories(), DetachPartitionFinalize(), determineNotNullFlags(), determineRecursiveColTypes(), do_pg_backup_start(), DoCopy(), DropSubscription(), dsynonym_init(), ean13_out(), encrypt_password(), enum_out(), EventTriggerSQLDropAddObject(), exec_bind_message(), exec_execute_message(), Exec_ListenCommit(), executeItemOptUnwrapTarget(), expand_dynamic_library_name(), expand_inherited_rtentry(), expand_insert_targetlist(), expand_single_inheritance_child(), ExpandRowReference(), expandRTE(), expandTableLikeClause(), expandTupleDesc(), ExportSnapshot(), extension_file_exists(), ExtractExtensionList(), fetch_statentries_for_relation(), fill_hba_line(), filter_list_to_array(), find_plan(), float4in_internal(), float8in_internal(), fmgr_symbol(), format_operator_parts(), format_procedure_parts(), format_type_extended(), from_char_seq_search(), generate_append_tlist(), generate_setop_tlist(), generateClonedIndexStmt(), generateJsonTablePathName(), get_am_name(), get_attname(), get_collation(), get_collation_actual_version_libc(), get_collation_name(), get_configdata(), get_connect_string(), get_constraint_name(), get_database_list(), get_database_name(), get_ext_ver_info(), get_ext_ver_list(), get_extension_control_directories(), get_extension_name(), get_extension_script_directory(), get_file_fdw_attribute_options(), get_func_name(), get_language_name(), get_namespace_name(), get_namespace_name_or_temp(), get_opclass(), get_opfamily_name(), get_opname(), get_publication_name(), get_rel_name(), get_rolespec_name(), get_source_line(), get_sql_insert(), get_sql_update(), get_string_attr(), get_subscription_list(), get_subscription_name(), get_tablespace_name(), getAdditionalACLs(), GetConfFilesInDir(), GetConfigOptionValues(), getConnectionByName(), GetDatabasePath(), GetForeignDataWrapperExtended(), GetForeignServerExtended(), GetJsonBehaviorValueString(), getNamespaces(), getObjectIdentityParts(), getOpFamilyIdentity(), GetPublication(), getRecoveryStopReason(), getRelationIdentity(), getRelationStatistics(), GetSubscription(), getTokenTypes(), GetUserNameFromId(), GetWaitEventCustomNames(), gtsvectorout(), heap_vacuum_rel(), hstore_out(), ImportForeignSchema(), indent_lines(), injection_points_attach(), internal_yylex(), interpret_AS_clause(), interpret_function_parameter_list(), interval_out(), isn_out(), iterate_values_object_field_start(), json_build_object_worker(), JsonbUnquote(), JsonTableInitOpaque(), lazy_cleanup_one_index(), lazy_vacuum_one_index(), libpqrcv_check_conninfo(), libpqrcv_create_slot(), libpqrcv_get_conninfo(), libpqrcv_get_dbname_from_conninfo(), libpqrcv_get_senderinfo(), libpqrcv_identify_system(), libpqrcv_readtimelinehistoryfile(), llvm_error_message(), llvm_function_reference(), llvm_set_target(), llvm_split_symbol_name(), load_domaintype_info(), load_libraries(), Lock_AF_UNIX(), logicalrep_partition_open(), logicalrep_read_attrs(), logicalrep_read_origin(), logicalrep_read_rel(), logicalrep_read_typ(), logicalrep_relmap_update(), main(), make_rfile(), makeAlias(), makeColumnDef(), makeJsonTablePathSpec(), makeMultirangeTypeName(), map_sql_value_to_xml_value(), MarkGUCPrefixReserved(), MergeAttributes(), MergeCheckConstraint(), name_active_windows(), nameout(), network_out(), new_ExtensionControlFile(), NINormalizeWord(), NormalizeSubWord(), nullable_string(), numeric_normalize(), numeric_out(), numeric_out_sci(), oauth_exchange(), object_to_string(), okeys_object_field_start(), parallel_vacuum_main(), parallel_vacuum_process_one_index(), parse_compress_specification(), parse_extension_control_file(), parse_hba_auth_opt(), parse_hba_line(), parse_ident_line(), parse_scram_secret(), parse_subscription_options(), ParseConfigFp(), ParseLongOption(), parseNameAndArgTypes(), ParseTzFile(), perform_base_backup(), PerformCursorOpen(), pg_available_extension_versions(), pg_available_extensions(), pg_import_system_collations(), pg_lsn_out(), pg_split_opts(), pg_split_walfile_name(), pg_tzenumerate_next(), pg_tzenumerate_start(), pgfnames(), pgrowlocks(), pgstatindex_impl(), plperl_init_interp(), plperl_to_hstore(), plpgsql_build_recfield(), plpgsql_build_record(), plpgsql_build_variable(), plpgsql_compile_callback(), plpgsql_compile_inline(), plpgsql_extra_checks_check_hook(), plsample_func_handler(), plsample_trigger_handler(), pltcl_set_tuple_values(), PLy_output(), PLy_procedure_create(), PLyObject_AsString(), PLyUnicode_AsString(), populate_scalar(), postgresImportForeignSchema(), PostmasterMain(), pq_parse_errornotice(), precheck_tar_backup_file(), prepare_foreign_modify(), prepare_sql_fn_parse_info(), PrepareTempTablespaces(), preprocess_targetlist(), preprocessNamespacePath(), print_function_sqlbody(), process_integer_literal(), process_psqlrc(), ProcessConfigFileInternal(), ProcessParallelApplyMessage(), ProcessParallelMessage(), ProcessPgArchInterrupts(), ProcessStandbyHSFeedbackMessage(), ProcessStandbyReplyMessage(), ProcessStartupPacket(), ProcessWalSndrMessage(), prsd_headline(), prsd_lextype(), pset_value_string(), px_find_combo(), QueueFKConstraintValidation(), QueueNNConstraintValidation(), range_deparse(), read_client_final_message(), read_client_first_message(), read_dictionary(), read_tablespace_map(), RebuildConstraintComment(), record_config_file_error(), regclassout(), regcollationout(), regconfigout(), regdictionaryout(), register_label_provider(), regnamespaceout(), regoperatorout(), regoperout(), regprocedureout(), regprocout(), REGRESS_exec_check_perms(), REGRESS_object_access_hook_str(), REGRESS_utility_command(), regroleout(), regtypeout(), ReindexPartitions(), RelationBuildTriggers(), RelationGetNotNullConstraints(), RemoveInheritance(), ReorderBufferFinishPrepared(), ReorderBufferPrepare(), ReorderBufferQueueMessage(), replace_auto_config_value(), ReplicationSlotRelease(), ReThrowError(), rewriteTargetListIU(), rewriteTargetView(), rmtree(), scram_exchange(), sendDir(), sepgsql_avc_compute(), sepgsql_compute_create(), sepgsql_get_label(), sepgsql_mcstrans_in(), sepgsql_mcstrans_out(), sepgsql_set_client_label(), set_relation_column_names(), set_stream_options(), shell_archive_file(), shell_get_sink(), show_sort_group_keys(), ShowGUCOption(), slotsync_reread_config(), SPI_fname(), SPI_getrelname(), SPI_gettype(), SplitDirectoriesString(), splitTzLine(), StartupRereadConfig(), stringToQualifiedNameList(), strip_trailing_ws(), substitute_path_macro(), SysLoggerMain(), test_rls_hooks_permissive(), test_rls_hooks_restrictive(), testprs_lextype(), textToQualifiedNameList(), thesaurus_init(), throw_tcl_error(), ThrowErrorData(), tidout(), time_out(), timestamp_out(), timestamptz_out(), timetz_out(), tokenize_auth_file(), tokenize_expand_file(), transformFkeyGetPrimaryKey(), transformIndexConstraint(), transformJsonArrayQueryConstructor(), transformJsonTableColumn(), transformJsonTableColumns(), transformRangeTableFunc(), transformRowExpr(), transformSetOperationStmt(), transformTableLikeClause(), tsearch_readline(), typeTypeName(), unknownin(), unknownout(), utf_e2u(), utf_u2e(), validate_token(), verify_plain_backup_directory(), void_out(), wait_result_to_str(), worker_spi_main(), X509_NAME_to_cstring(), and xpstrdup().

◆ PublishMemoryContext()

static void PublishMemoryContext ( MemoryStatsEntry memcxt_info,
int  curr_id,
MemoryContext  context,
List path,
MemoryContextCounters  stat,
int  num_contexts,
dsa_area area,
int  max_levels 
)
static

Definition at line 1793 of file mcxt.c.

1797{
1798 const char *ident = context->ident;
1799 const char *name = context->name;
1800 int *path_list;
1801
1802 /*
1803 * To be consistent with logging output, we label dynahash contexts with
1804 * just the hash table name as with MemoryContextStatsPrint().
1805 */
1806 if (context->ident && strncmp(context->name, "dynahash", 8) == 0)
1807 {
1808 name = context->ident;
1809 ident = NULL;
1810 }
1811
1812 if (name != NULL)
1813 {
1814 int namelen = strlen(name);
1815 char *nameptr;
1816
1818 namelen = pg_mbcliplen(name, namelen,
1820
1821 memcxt_info[curr_id].name = dsa_allocate(area, namelen + 1);
1822 nameptr = (char *) dsa_get_address(area, memcxt_info[curr_id].name);
1823 strlcpy(nameptr, name, namelen + 1);
1824 }
1825 else
1826 memcxt_info[curr_id].name = InvalidDsaPointer;
1827
1828 /* Trim and copy the identifier if it is not set to NULL */
1829 if (ident != NULL)
1830 {
1831 int idlen = strlen(context->ident);
1832 char *identptr;
1833
1834 /*
1835 * Some identifiers such as SQL query string can be very long,
1836 * truncate oversize identifiers.
1837 */
1839 idlen = pg_mbcliplen(ident, idlen,
1841
1842 memcxt_info[curr_id].ident = dsa_allocate(area, idlen + 1);
1843 identptr = (char *) dsa_get_address(area, memcxt_info[curr_id].ident);
1844 strlcpy(identptr, ident, idlen + 1);
1845 }
1846 else
1847 memcxt_info[curr_id].ident = InvalidDsaPointer;
1848
1849 /* Allocate DSA memory for storing path information */
1850 if (path == NIL)
1851 memcxt_info[curr_id].path = InvalidDsaPointer;
1852 else
1853 {
1854 int levels = Min(list_length(path), max_levels);
1855
1856 memcxt_info[curr_id].path_length = levels;
1857 memcxt_info[curr_id].path = dsa_allocate0(area, levels * sizeof(int));
1858 memcxt_info[curr_id].levels = list_length(path);
1859 path_list = (int *) dsa_get_address(area, memcxt_info[curr_id].path);
1860
1861 foreach_int(i, path)
1862 {
1863 path_list[foreach_current_index(i)] = i;
1864 if (--levels == 0)
1865 break;
1866 }
1867 }
1868 memcxt_info[curr_id].type = context->type;
1869 memcxt_info[curr_id].totalspace = stat.totalspace;
1870 memcxt_info[curr_id].nblocks = stat.nblocks;
1871 memcxt_info[curr_id].freespace = stat.freespace;
1872 memcxt_info[curr_id].freechunks = stat.freechunks;
1873 memcxt_info[curr_id].num_agg_stats = num_contexts;
1874}
#define MEMORY_CONTEXT_IDENT_SHMEM_SIZE
Definition: memutils.h:59
static int list_length(const List *l)
Definition: pg_list.h:152
#define foreach_current_index(var_or_cell)
Definition: pg_list.h:403
#define foreach_int(var, lst)
Definition: pg_list.h:470
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45

References dsa_allocate, dsa_allocate0, dsa_get_address(), foreach_current_index, foreach_int, MemoryStatsEntry::freechunks, MemoryStatsEntry::freespace, i, MemoryContextData::ident, MemoryStatsEntry::ident, ident, InvalidDsaPointer, MemoryStatsEntry::levels, list_length(), MEMORY_CONTEXT_IDENT_SHMEM_SIZE, Min, name, MemoryContextData::name, MemoryStatsEntry::name, MemoryStatsEntry::nblocks, NIL, MemoryStatsEntry::num_agg_stats, MemoryStatsEntry::path, MemoryStatsEntry::path_length, pg_mbcliplen(), strlcpy(), MemoryStatsEntry::totalspace, and MemoryStatsEntry::type.

Referenced by ProcessGetMemoryContextInterrupt().

◆ repalloc()

void * repalloc ( void *  pointer,
Size  size 
)

Definition at line 2170 of file mcxt.c.

2171{
2172#ifdef USE_VALGRIND
2174#endif
2175#if defined(USE_ASSERT_CHECKING) || defined(USE_VALGRIND)
2176 MemoryContext context = GetMemoryChunkContext(pointer);
2177#endif
2178 void *ret;
2179
2181
2182 /* isReset must be false already */
2183 Assert(!context->isReset);
2184
2185 /*
2186 * For efficiency reasons, we purposefully offload the handling of
2187 * allocation failures to the MemoryContextMethods implementation as this
2188 * allows these checks to be performed only when an actual malloc needs to
2189 * be done to request more memory from the OS. Additionally, not having
2190 * to execute any instructions after this call allows the compiler to use
2191 * the sibling call optimization. If you're considering adding code after
2192 * this call, consider making it the responsibility of the 'realloc'
2193 * function instead.
2194 */
2195 ret = MCXT_METHOD(pointer, realloc) (pointer, size, 0);
2196
2197#ifdef USE_VALGRIND
2198 if (method != MCTX_ALIGNED_REDIRECT_ID)
2199 VALGRIND_MEMPOOL_CHANGE(context, pointer, ret, size);
2200#endif
2201
2202 return ret;
2203}
#define realloc(a, b)
Definition: header.h:60
#define VALGRIND_MEMPOOL_CHANGE(context, optr, nptr, size)
Definition: memdebug.h:31

References Assert(), AssertNotInCriticalSection, GetMemoryChunkContext(), GetMemoryChunkMethodID(), MemoryContextData::isReset, MCTX_ALIGNED_REDIRECT_ID, MCXT_METHOD, realloc, and VALGRIND_MEMPOOL_CHANGE.

Referenced by _bt_deadblocks(), _bt_pendingfsm_add(), _bt_preprocess_keys(), _fdvec_resize(), accumArrayResult(), accumArrayResultArr(), add_column_to_pathtarget(), add_exact_object_address(), add_exact_object_address_extra(), add_gin_entry(), add_object_address(), add_reloption(), addCompiledLexeme(), addCompoundAffixFlagValue(), AddInvalidationMessage(), addlit(), addlitchar(), AddStem(), addToArray(), addWrd(), AfterTriggerBeginSubXact(), AfterTriggerEnlargeQueryState(), appendElement(), appendKey(), apply_spooled_messages(), array_agg_array_combine(), array_agg_combine(), array_set_element_expanded(), AtSubCommit_childXids(), BlockRefTableEntryMarkBlockModified(), bms_add_member(), bms_add_range(), bms_replace_members(), brin_copy_tuple(), BufferSync(), BufFileAppend(), BufFileOpenFileSet(), checkcondition_str(), checkSharedDependencies(), compileTheLexeme(), compileTheSubstitute(), CopyReadAttributesCSV(), CopyReadAttributesText(), core_yyrealloc(), count_usable_fds(), cube_inter(), do_set_block_offsets(), dsnowball_lexize(), dsynonym_init(), dxsyn_lexize(), enlarge_list(), enlargeStringInfo(), enum_range_internal(), ExecIndexBuildScanKeys(), ExecInitPartitionDispatchInfo(), ExecInitRoutingInfo(), ExprEvalPushStep(), extendBufFile(), find_inheritance_children_extended(), find_plan(), findDependentObjects(), generate_dependencies_recurse(), generateHeadline(), get_docrep(), GetComboCommandId(), GetConfFilesInDir(), GetExplainExtensionId(), GetLockStatusData(), GetSingleProcBlockerStatusData(), gettoken_tsvector(), GinBufferStoreTuple(), ginFillScanEntry(), GinFormTuple(), ginPostingListDecodeAllSegments(), gistAddLoadedBuffer(), gistBuffersReleaseBlock(), gistGetNodeBuffer(), gistjoinvector(), gtsvector_compress(), hladdword(), hlfinditem(), icu_language_tag(), int2vectorin(), jsonpath_yyrealloc(), load_domaintype_info(), load_enum_cache_data(), load_relcache_init_file(), LockAcquireExtended(), lookup_type_cache(), ltsGetPreallocBlock(), ltsReleaseBlock(), mark_hl_fragments(), MergeAffix(), multirange_in(), newLexeme(), NIAddAffix(), NIAddSpell(), NISortAffixes(), oidvectorin(), oidvectortypes(), okeys_object_field_start(), parse_hstore(), parsetext(), perform_default_encoding_conversion(), pg_do_encoding_conversion(), pg_import_system_collations(), pgfnames(), pgss_shmem_startup(), plainnode(), plpgsql_adddatum(), prepare_room(), PrescanPreparedTransactions(), prs_setup_firstcall(), pushval_asis(), pushValue(), QTNTernary(), read_dictionary(), readstoplist(), record_corrupt_item(), RecordConstLocation(), RegisterExtensionExplainOption(), RelationBuildDesc(), RelationBuildRuleLock(), RelationBuildTriggers(), RememberToFreeTupleDescAtEOX(), ReorderBufferAddInvalidations(), ReorderBufferSerializeReserve(), repalloc0(), RequestNamedLWLockTranche(), resize_intArrayType(), resizeString(), rmtree(), SetConstraintStateAddItem(), setup_regexp_matches(), setup_test_matches(), smgrDoPendingDeletes(), smgrDoPendingSyncs(), SnapBuildAddCommittedTxn(), socket_putmessage_noblock(), SPI_connect_ext(), SPI_repalloc(), statext_dependencies_build(), statext_dependencies_deserialize(), statext_mcv_deserialize(), str_casefold(), str_initcap(), str_tolower(), str_toupper(), str_udeescape(), subxact_info_add(), TidListEval(), tsqueryrecv(), tsvectorin(), tsvectorrecv(), tuplestore_alloc_read_pointer(), uniqueentry(), uniqueWORD(), varstr_abbrev_convert(), varstrfastcmp_locale(), XLogEnsureRecordSpace(), and yyrealloc().

◆ repalloc0()

void * repalloc0 ( void *  pointer,
Size  oldsize,
Size  size 
)

Definition at line 2248 of file mcxt.c.

2249{
2250 void *ret;
2251
2252 /* catch wrong argument order */
2253 if (unlikely(oldsize > size))
2254 elog(ERROR, "invalid repalloc0 call: oldsize %zu, new size %zu",
2255 oldsize, size);
2256
2257 ret = repalloc(pointer, size);
2258 memset((char *) ret + oldsize, 0, (size - oldsize));
2259 return ret;
2260}
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:2170

References elog, ERROR, repalloc(), and unlikely.

Referenced by SetExplainExtensionState().

◆ repalloc_extended()

void * repalloc_extended ( void *  pointer,
Size  size,
int  flags 
)

Definition at line 2211 of file mcxt.c.

2212{
2213#if defined(USE_ASSERT_CHECKING) || defined(USE_VALGRIND)
2214 MemoryContext context = GetMemoryChunkContext(pointer);
2215#endif
2216 void *ret;
2217
2219
2220 /* isReset must be false already */
2221 Assert(!context->isReset);
2222
2223 /*
2224 * For efficiency reasons, we purposefully offload the handling of
2225 * allocation failures to the MemoryContextMethods implementation as this
2226 * allows these checks to be performed only when an actual malloc needs to
2227 * be done to request more memory from the OS. Additionally, not having
2228 * to execute any instructions after this call allows the compiler to use
2229 * the sibling call optimization. If you're considering adding code after
2230 * this call, consider making it the responsibility of the 'realloc'
2231 * function instead.
2232 */
2233 ret = MCXT_METHOD(pointer, realloc) (pointer, size, flags);
2234 if (unlikely(ret == NULL))
2235 return NULL;
2236
2237 VALGRIND_MEMPOOL_CHANGE(context, pointer, ret, size);
2238
2239 return ret;
2240}

References Assert(), AssertNotInCriticalSection, GetMemoryChunkContext(), MemoryContextData::isReset, MCXT_METHOD, realloc, unlikely, and VALGRIND_MEMPOOL_CHANGE.

Referenced by guc_realloc(), and repalloc_huge().

◆ repalloc_huge()

void * repalloc_huge ( void *  pointer,
Size  size 
)

Definition at line 2301 of file mcxt.c.

2302{
2303 /* this one seems not worth its own implementation */
2304 return repalloc_extended(pointer, size, MCXT_ALLOC_HUGE);
2305}
void * repalloc_extended(void *pointer, Size size, int flags)
Definition: mcxt.c:2211

References MCXT_ALLOC_HUGE, and repalloc_extended().

Referenced by ginCombineData(), grow_memtuples(), and spi_printtup().

Variable Documentation

◆ CacheMemoryContext

MemoryContext CacheMemoryContext = NULL

Definition at line 168 of file mcxt.c.

Referenced by _SPI_save_plan(), AllocateRelationDesc(), assign_record_type_typmod(), AttrDefaultFetch(), BuildEventTriggerCache(), BuildHardcodedDescriptor(), CatalogCacheCreateEntry(), CatalogCacheInitializeCache(), CheckNNConstraintFetch(), CreateCacheMemoryContext(), ensure_record_cache_typmod_slot_exists(), FetchTableStates(), generate_partition_qual(), get_attribute_options(), get_tablespace(), GetCachedExpression(), GetCachedPlan(), GetFdwRoutineForRelation(), init_ts_config_cache(), InitCatCache(), InitializeAttoptCache(), InitializeRelfilenumberMap(), InitializeTableSpaceCache(), load_domaintype_info(), load_enum_cache_data(), load_rangetype_info(), load_relcache_init_file(), logicalrep_partmap_init(), logicalrep_relmap_init(), lookup_ts_config_cache(), lookup_ts_dictionary_cache(), lookup_ts_parser_cache(), lookup_type_cache(), LookupOpclassInfo(), pgoutput_startup(), register_on_commit_action(), RehashCatCache(), RehashCatCacheLists(), RelationBuildLocalRelation(), RelationBuildPartitionDesc(), RelationBuildPartitionKey(), RelationBuildPublicationDesc(), RelationBuildRowSecurity(), RelationBuildRuleLock(), RelationBuildTriggers(), RelationBuildTupleDesc(), RelationCacheInitialize(), RelationCacheInitializePhase2(), RelationCacheInitializePhase3(), RelationGetFKeyList(), RelationGetIdentityKeyBitmap(), RelationGetIndexAttrBitmap(), RelationGetIndexList(), RelationGetStatExtList(), RelationInitIndexAccessInfo(), RelationParseRelOptions(), RememberToFreeTupleDescAtEOX(), SaveCachedPlan(), SearchCatCacheList(), set_schema_sent_in_streamed_txn(), SPI_keepplan(), sql_compile_callback(), and UploadManifest().

◆ CurrentMemoryContext

MemoryContext CurrentMemoryContext = NULL

Definition at line 159 of file mcxt.c.

Referenced by _brin_parallel_merge(), _bt_load(), _bt_preprocess_array_keys(), _gin_parallel_build_main(), _hash_finish_split(), _SPI_commit(), _SPI_rollback(), _SPI_save_plan(), advance_windowaggregate(), advance_windowaggregate_base(), afterTriggerInvokeEvents(), AllocateSnapshotBuilder(), array_agg_array_deserialize(), array_agg_array_finalfn(), array_agg_deserialize(), array_agg_finalfn(), array_positions(), array_sort_internal(), array_to_datum_internal(), AtStart_Memory(), AtSubStart_Memory(), AttachPartitionEnsureIndexes(), autovacuum_do_vac_analyze(), be_lo_export(), be_lo_from_bytea(), be_lo_put(), begin_heap_rewrite(), BeginCopyFrom(), BeginCopyTo(), blbuild(), blinsert(), brin_build_desc(), brin_minmax_multi_summary_out(), brin_minmax_multi_union(), brin_new_memtuple(), bringetbitmap(), brininsert(), bt_check_every_level(), btree_xlog_startup(), btvacuumscan(), build_colinfo_names_hash(), build_join_rel_hash(), BuildCachedPlan(), BuildParamLogString(), BuildRelationExtStatistics(), CheckForSessionAndXactLocks(), CloneRowTriggersToPartition(), CompactCheckpointerRequestQueue(), compactify_ranges(), CompleteCachedPlan(), compute_array_stats(), compute_expr_stats(), compute_scalar_stats(), compute_tsvector_stats(), ComputeExtStatisticsRows(), CopyCachedPlan(), CopyErrorData(), CopyFrom(), CopyFromTextLikeOneRow(), create_toast_table(), CreateCachedPlan(), CreateEmptyBlockRefTable(), CreateExecutorState(), CreateOneShotCachedPlan(), CreatePartitionPruneState(), CreateStandaloneExprContext(), createTempGistContext(), createTrgmNFA(), CreateTriggerFiringOn(), daitch_mokotoff(), daitch_mokotoff_coding(), DatumGetExpandedArray(), DatumGetExpandedArrayX(), DatumGetExpandedRecord(), datumTransfer(), dblink_get_connections(), DiscreteKnapsack(), do_analyze_rel(), do_start_worker(), DoCopyTo(), domain_check_internal(), dsnowball_init(), each_worker(), each_worker_jsonb(), elements_worker(), elements_worker_jsonb(), ensure_free_space_in_buffer(), errsave_start(), EventTriggerInvoke(), examine_expression(), exec_replication_command(), exec_stmt_block(), ExecAggCopyTransValue(), ExecEvalHashedScalarArrayOp(), ExecHashTableCreate(), ExecInitCoerceToDomain(), ExecInitFunctionScan(), ExecInitGatherMerge(), ExecInitIndexScan(), ExecInitMemoize(), ExecInitMergeAppend(), ExecInitModifyTable(), ExecInitProjectSet(), ExecInitRecursiveUnion(), ExecInitSetOp(), ExecInitSubPlan(), ExecInitTableFuncScan(), ExecInitWindowAgg(), ExecMakeTableFunctionResult(), ExecScanSubPlan(), ExecSetParamPlan(), ExecSetupPartitionTupleRouting(), execute_sql_string(), ExecuteTruncateGuts(), ExplainExecuteQuery(), fetch_array_arg_replace_nulls(), file_acquire_sample_rows(), fileIterateForeignScan(), fill_hba_view(), fill_ident_view(), find_all_inheritors(), find_or_create_child_node(), find_partition_scheme(), fmgr_info(), fmgr_info_other_lang(), geqo_eval(), get_actual_variable_range(), get_database_list(), get_json_object_as_hash(), get_subscription_list(), GetCachedExpression(), GetConnection(), GetErrorContextStack(), GetWALRecordsInfo(), GetXLogSummaryStats(), gin_check_parent_keys_consistency(), gin_check_posting_tree_parent_keys_consistency(), gin_extract_query_trgm(), gin_xlog_startup(), ginbeginscan(), GinBufferInit(), ginbuild(), ginbulkdelete(), gininsert(), ginInsertCleanup(), ginPlaceToPage(), gistbuild(), gistInitBuildBuffers(), gistInitParentMap(), gistvacuumscan(), IdentifySystem(), index_form_tuple(), initBloomState(), initGinState(), initGISTstate(), initialize_brin_buildstate(), initialize_peragg(), InitPartitionPruneContext(), initTrie(), inline_function(), inline_set_returning_function(), intset_create(), json_unique_builder_init(), json_unique_check_init(), JsonTableInitOpaque(), libpqrcv_processTuples(), lo_get_fragment_internal(), lo_import_internal(), load_domaintype_info(), load_tzoffsets(), load_validator_library(), LogicalParallelApplyLoop(), makeIndexInfo(), makeNumericAggStateCurrentContext(), MakeTupleTableSlot(), MemoryContextDeleteOnly(), MemoryContextInit(), MemoryContextSwitchTo(), MJExamineQuals(), multi_sort_add_dimension(), NextCopyFrom(), open_auth_file(), optionListToArray(), palloc(), palloc0(), palloc_aligned(), palloc_extended(), ParallelWorkerMain(), parse_ident(), perform_default_encoding_conversion(), perform_work_item(), pg_buffercache_numa_pages(), pg_buffercache_pages(), pg_do_encoding_conversion(), pg_get_backend_memory_contexts(), pg_get_logical_snapshot_info(), pg_get_logical_snapshot_meta(), pg_get_process_memory_contexts(), pg_get_statisticsobjdef_expressions(), pg_get_wal_block_info(), pg_stats_ext_mcvlist_items(), plan_cluster_use_sort(), plan_create_index_workers(), plperl_array_to_datum(), plperl_inline_handler(), plperl_return_next(), plperl_return_next_internal(), plperl_spi_commit(), plperl_spi_exec(), plperl_spi_exec_prepared(), plperl_spi_fetchrow(), plperl_spi_prepare(), plperl_spi_query(), plperl_spi_query_prepared(), plperl_spi_rollback(), plperl_util_elog(), plpgsql_compile_inline(), plpgsql_estate_setup(), plpgsql_inline_handler(), plpgsql_validator(), plpython3_inline_handler(), pltcl_commit(), pltcl_elog(), pltcl_returnnext(), pltcl_rollback(), pltcl_SPI_execute(), pltcl_SPI_execute_plan(), pltcl_SPI_prepare(), pltcl_subtransaction(), PLy_commit(), PLy_cursor_fetch(), PLy_cursor_iternext(), PLy_cursor_plan(), PLy_cursor_query(), PLy_output(), PLy_rollback(), PLy_spi_execute_fetch_result(), PLy_spi_execute_plan(), PLy_spi_execute_query(), PLy_spi_prepare(), PLy_subtransaction_enter(), PLySequence_ToArray(), PLySequence_ToArray_recurse(), populate_array(), populate_recordset_object_start(), PortalRun(), PortalRunMulti(), postgresAcquireSampleRowsFunc(), postquel_start(), pq_parse_errornotice(), preparePresortedCols(), printtup_startup(), ProcessConfigFile(), ProcessGetMemoryContextInterrupt(), prune_append_rel_partitions(), pstrdup(), publicationListToArray(), pull_up_simple_subquery(), RE_compile_and_cache(), regexp_split_to_array(), RelationBuildDesc(), RelationBuildRowSecurity(), ReorderBufferAllocate(), ReorderBufferProcessTXN(), ResetUnloggedRelations(), ResetUnloggedRelationsInDbspaceDir(), RevalidateCachedQuery(), ScanKeyEntryInitializeWithInfo(), serialize_expr_stats(), serializeAnalyzeStartup(), SerializePendingSyncs(), set_relation_partition_info(), set_rtable_names(), shdepReassignOwned(), shm_mq_attach(), smgr_bulk_start_smgr(), spg_xlog_startup(), spgbeginscan(), spgbuild(), spginsert(), spi_dest_startup(), split_text_accum_result(), sql_compile_callback(), standard_ExplainOneQuery(), startScanKey(), StartupDecodingContext(), statext_dependencies_build(), statext_mcv_serialize(), strlist_to_textarray(), sts_attach(), sts_initialize(), subquery_planner(), tbm_create(), test_basic(), test_empty(), test_enc_conversion(), test_pattern(), test_random(), text_to_array(), TidStoreCreateLocal(), tokenize_auth_file(), transformGraph(), transformRelOptions(), tsquery_rewrite_query(), tuple_data_split_internal(), tuplesort_begin_cluster(), tuplesort_begin_common(), tuplesort_begin_datum(), tuplesort_begin_heap(), tuplesort_begin_index_btree(), tuplesort_begin_index_gin(), tuplesort_begin_index_gist(), tuplestore_begin_common(), union_tuples(), UploadManifest(), validateForeignKeyConstraint(), write_console(), and xpath().

◆ CurTransactionContext

◆ ErrorContext

◆ mcxt_methods

const MemoryContextMethods mcxt_methods[]
static

Definition at line 51 of file mcxt.c.

Referenced by MemoryContextCreate().

◆ MemoryStatsDsaArea

dsa_area* MemoryStatsDsaArea = NULL

◆ MessageContext

◆ PortalContext

◆ PostmasterContext

◆ TopMemoryContext

MemoryContext TopMemoryContext = NULL

Definition at line 165 of file mcxt.c.

Referenced by _PG_init(), AbortOutOfAnyTransaction(), add_reloption(), allocate_reloption(), AllocateAttribute(), AllocSetContextCreateInternal(), ApplyLauncherMain(), AtAbort_Memory(), AtStart_Memory(), AttachSession(), AutoVacLauncherMain(), BackendInitialize(), BackendMain(), BackgroundWorkerMain(), BackgroundWriterMain(), BaseBackupAddTarget(), be_tls_open_server(), build_guc_variables(), BumpContextCreate(), cache_single_string(), cached_function_compile(), cfunc_hashtable_insert(), check_foreign_key(), check_primary_key(), CheckpointerMain(), ClientAuthentication(), compile_plperl_function(), compile_pltcl_function(), CreateCacheMemoryContext(), CreateWaitEventSet(), dblink_connect(), dblink_init(), DCH_cache_getnew(), do_autovacuum(), dsm_create_descriptor(), dsm_impl_sysv(), EnablePortalManager(), EventTriggerBeginCompleteQuery(), Exec_ListenCommit(), exec_replication_command(), executeDateTimeMethod(), find_plan(), finish_xact_command(), GenerationContextCreate(), GetExplainExtensionId(), GetLocalBufferStorage(), GetLockConflicts(), getmissingattr(), GetNamedDSMSegment(), GetSessionDsmHandle(), hash_create(), init_database_collation(), init_missing_cache(), init_string_reloption(), InitDeadLockChecking(), initialize_reloptions(), initialize_target_list(), InitializeClientEncoding(), InitializeLogRepWorker(), InitializeParallelDSM(), InitializeSearchPath(), InitializeSession(), InitializeSystemUser(), InitSync(), InitWalSender(), InitXLogInsert(), injection_points_attach(), injection_points_detach(), llvm_compile_module(), llvm_create_context(), llvm_session_initialize(), LockAcquireExtended(), logicalrep_launcher_attach_dshmem(), LogicalRepApplyLoop(), LWLockRegisterTranche(), mdinit(), MemoryContextAllocationFailure(), MemoryContextDeleteOnly(), MemoryContextInit(), mxid_to_string(), newLOfd(), NUM_cache_getnew(), on_dsm_detach(), PageSetChecksumCopy(), ParallelWorkerMain(), PerformAuthentication(), pg_backup_start(), pg_get_backend_memory_contexts(), pg_get_process_memory_contexts(), pg_newlocale_from_collation(), PgArchiverMain(), pgstat_attach_shmem(), pgstat_init_snapshot_fixed(), pgstat_prep_pending_entry(), pgstat_prep_snapshot(), pgstat_register_kind(), pgstat_setup_backend_status_context(), pgstat_setup_memcxt(), plperl_spi_prepare(), plpgsql_compile_callback(), plpython3_inline_handler(), plsample_func_handler(), pltcl_SPI_prepare(), PLy_cursor_plan(), PLy_cursor_query(), PLy_procedure_create(), PLy_spi_execute_fetch_result(), PLy_spi_prepare(), populate_typ_list(), PostgresMain(), postmaster_child_launch(), PostmasterMain(), pq_init(), PrepareClientEncoding(), ProcessGetMemoryContextInterrupt(), ProcessLogMemoryContextInterrupt(), ProcessParallelApplyMessages(), ProcessParallelMessages(), ProcessStartupPacket(), px_find_cipher(), px_find_digest(), RE_compile_and_cache(), recomputeNamespacePath(), register_label_provider(), RegisterExtensionExplainOption(), RegisterResourceReleaseCallback(), RegisterSubXactCallback(), RegisterXactCallback(), RelationCreateStorage(), RelationDropStorage(), RequestNamedLWLockTranche(), ResourceOwnerCreate(), ResourceOwnerEnlarge(), RestoreClientConnectionInfo(), RestoreReindexState(), ri_HashCompareOp(), roles_is_member_of(), secure_open_gssapi(), sepgsql_avc_init(), sepgsql_xact_callback(), set_authn_id(), SetDatabasePath(), SharedRecordTypmodRegistryAttach(), SharedRecordTypmodRegistryInit(), SlabContextCreate(), spcache_init(), SPI_connect_ext(), test_create(), WalSummarizerMain(), WalWriterMain(), and XLOGShmemInit().

◆ TopTransactionContext