PostgreSQL Source Code git master
Loading...
Searching...
No Matches
mcxt.c File Reference
#include "postgres.h"
#include "common/int.h"
#include "mb/pg_wchar.h"
#include "miscadmin.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
 

Functions

static void BogusFree (void *pointer)
 
static voidBogusRealloc (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, bool print_to_stderr)
 
static void MemoryContextStatsPrint (MemoryContext context, void *passthru, const char *stats_string, bool print_to_stderr)
 
static pg_noreturn pg_noinline void add_size_error (Size s1, Size s2)
 
static pg_noreturn pg_noinline void mul_size_error (Size s1, Size s2)
 
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 MemoryContextUnregisterResetCallback (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)
 
voidMemoryContextAllocationFailure (MemoryContext context, Size size, int flags)
 
void MemoryContextSizeFailure (MemoryContext context, Size size, int flags)
 
voidMemoryContextAlloc (MemoryContext context, Size size)
 
voidMemoryContextAllocZero (MemoryContext context, Size size)
 
voidMemoryContextAllocExtended (MemoryContext context, Size size, int flags)
 
void HandleLogMemoryContextInterrupt (void)
 
void ProcessLogMemoryContextInterrupt (void)
 
voidpalloc (Size size)
 
voidpalloc0 (Size size)
 
voidpalloc_extended (Size size, int flags)
 
voidMemoryContextAllocAligned (MemoryContext context, Size size, Size alignto, int flags)
 
voidpalloc_aligned (Size size, Size alignto, int flags)
 
void pfree (void *pointer)
 
voidrepalloc (void *pointer, Size size)
 
voidrepalloc_extended (void *pointer, Size size, int flags)
 
voidrepalloc0 (void *pointer, Size oldsize, Size size)
 
Size add_size (Size s1, Size s2)
 
Size mul_size (Size s1, Size s2)
 
voidpalloc_mul (Size s1, Size s2)
 
voidpalloc0_mul (Size s1, Size s2)
 
voidpalloc_mul_extended (Size s1, Size s2, int flags)
 
voidrepalloc_mul (void *p, Size s1, Size s2)
 
voidrepalloc_mul_extended (void *p, Size s1, Size s2, int flags)
 
voidMemoryContextAllocHuge (MemoryContext context, Size size)
 
voidrepalloc_huge (void *pointer, Size size)
 
charMemoryContextStrdup (MemoryContext context, const char *string)
 
charpstrdup (const char *in)
 
charpnstrdup (const char *in, Size len)
 
charpchomp (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
 
static bool LogMemoryContextInProgress = false
 

Macro Definition Documentation

◆ AssertNotInCriticalSection

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

Definition at line 198 of file mcxt.c.

214{
215 uint64 header;
216
217 /*
218 * Try to detect bogus pointers handed to us, poorly though we can.
219 * Presumably, a pointer that isn't MAXALIGNED isn't pointing at an
220 * allocated chunk.
221 */
222 Assert(pointer == (const void *) MAXALIGN(pointer));
223
224 /* Allow access to the uint64 header */
225 VALGRIND_MAKE_MEM_DEFINED((char *) pointer - sizeof(uint64), sizeof(uint64));
226
227 header = *((const uint64 *) ((const char *) pointer - sizeof(uint64)));
228
229 /* Disallow access to the uint64 header */
230 VALGRIND_MAKE_MEM_NOACCESS((char *) pointer - sizeof(uint64), sizeof(uint64));
231
233}
234
235/*
236 * GetMemoryChunkHeader
237 * Return the uint64 chunk header which directly precedes 'pointer'.
238 *
239 * This is only used after GetMemoryChunkMethodID, so no need for error checks.
240 */
241static inline uint64
242GetMemoryChunkHeader(const void *pointer)
243{
244 uint64 header;
245
246 /* Allow access to the uint64 header */
247 VALGRIND_MAKE_MEM_DEFINED((char *) pointer - sizeof(uint64), sizeof(uint64));
248
249 header = *((const uint64 *) ((const char *) pointer - sizeof(uint64)));
250
251 /* Disallow access to the uint64 header */
252 VALGRIND_MAKE_MEM_NOACCESS((char *) pointer - sizeof(uint64), sizeof(uint64));
253
254 return header;
255}
256
257/*
258 * MemoryContextTraverseNext
259 * Helper function to traverse all descendants of a memory context
260 * without recursion.
261 *
262 * Recursion could lead to out-of-stack errors with deep context hierarchies,
263 * which would be unpleasant in error cleanup code paths.
264 *
265 * To process 'context' and all its descendants, use a loop like this:
266 *
267 * <process 'context'>
268 * for (MemoryContext curr = context->firstchild;
269 * curr != NULL;
270 * curr = MemoryContextTraverseNext(curr, context))
271 * {
272 * <process 'curr'>
273 * }
274 *
275 * This visits all the contexts in pre-order, that is a node is visited
276 * before its children.
277 */
278static MemoryContext
280{
281 /* After processing a node, traverse to its first child if any */
282 if (curr->firstchild != NULL)
283 return curr->firstchild;
284
285 /*
286 * After processing a childless node, traverse to its next sibling if
287 * there is one. If there isn't, traverse back up to the parent (which
288 * has already been visited, and now so have all its descendants). We're
289 * done if that is "top", otherwise traverse to its next sibling if any,
290 * otherwise repeat moving up.
291 */
292 while (curr->nextchild == NULL)
293 {
294 curr = curr->parent;
295 if (curr == top)
296 return NULL;
297 }
298 return curr->nextchild;
299}
300
301/*
302 * Support routines to trap use of invalid memory context method IDs
303 * (from calling pfree or the like on a bogus pointer). As a possible
304 * aid in debugging, we report the header word along with the pointer
305 * address (if we got here, there must be an accessible header word).
306 */
307static void
308BogusFree(void *pointer)
309{
310 elog(ERROR, "pfree called with invalid pointer %p (header 0x%016" PRIx64 ")",
311 pointer, GetMemoryChunkHeader(pointer));
312}
313
314static void *
315BogusRealloc(void *pointer, Size size, int flags)
316{
317 elog(ERROR, "repalloc called with invalid pointer %p (header 0x%016" PRIx64 ")",
318 pointer, GetMemoryChunkHeader(pointer));
319 return NULL; /* keep compiler quiet */
320}
321
322static MemoryContext
323BogusGetChunkContext(void *pointer)
324{
325 elog(ERROR, "GetMemoryChunkContext called with invalid pointer %p (header 0x%016" PRIx64 ")",
326 pointer, GetMemoryChunkHeader(pointer));
327 return NULL; /* keep compiler quiet */
328}
329
330static Size
331BogusGetChunkSpace(void *pointer)
332{
333 elog(ERROR, "GetMemoryChunkSpace called with invalid pointer %p (header 0x%016" PRIx64 ")",
334 pointer, GetMemoryChunkHeader(pointer));
335 return 0; /* keep compiler quiet */
336}
337
338
339/*****************************************************************************
340 * EXPORTED ROUTINES *
341 *****************************************************************************/
342
343
344/*
345 * MemoryContextInit
346 * Start up the memory-context subsystem.
347 *
348 * This must be called before creating contexts or allocating memory in
349 * contexts. TopMemoryContext and ErrorContext are initialized here;
350 * other contexts must be created afterwards.
351 *
352 * In normal multi-backend operation, this is called once during
353 * postmaster startup, and not at all by individual backend startup
354 * (since the backends inherit an already-initialized context subsystem
355 * by virtue of being forked off the postmaster). But in an EXEC_BACKEND
356 * build, each process must do this for itself.
357 *
358 * In a standalone backend this must be called during backend startup.
359 */
360void
362{
364
365 /*
366 * First, initialize TopMemoryContext, which is the parent of all others.
367 */
369 "TopMemoryContext",
371
372 /*
373 * Not having any other place to point CurrentMemoryContext, make it point
374 * to TopMemoryContext. Caller should change this soon!
375 */
377
378 /*
379 * Initialize ErrorContext as an AllocSetContext with slow growth rate ---
380 * we don't really expect much to be allocated in it. More to the point,
381 * require it to contain at least 8K at all times. This is the only case
382 * where retained memory in a context is *essential* --- we want to be
383 * sure ErrorContext still has some memory even if we've run out
384 * elsewhere! Also, allow allocations in ErrorContext within a critical
385 * section. Otherwise a PANIC will cause an assertion failure in the error
386 * reporting code, before printing out the real cause of the failure.
387 *
388 * This should be the last step in this function, as elog.c assumes memory
389 * management works once ErrorContext is non-null.
390 */
392 "ErrorContext",
393 8 * 1024,
394 8 * 1024,
395 8 * 1024);
397}
398
399/*
400 * MemoryContextReset
401 * Release all space allocated within a context and delete all its
402 * descendant contexts (but not the named context itself).
403 */
404void
406{
408
409 /* save a function call in common case where there are no children */
410 if (context->firstchild != NULL)
412
413 /* save a function call if no pallocs since startup or last reset */
414 if (!context->isReset)
415 MemoryContextResetOnly(context);
416}
417
418/*
419 * MemoryContextResetOnly
420 * Release all space allocated within a context.
421 * Nothing is done to the context's descendant contexts.
422 */
423void
425{
427
428 /* Nothing to do if no pallocs since startup or last reset */
429 if (!context->isReset)
430 {
432
433 /*
434 * If context->ident points into the context's memory, it will become
435 * a dangling pointer. We could prevent that by setting it to NULL
436 * here, but that would break valid coding patterns that keep the
437 * ident elsewhere, e.g. in a parent context. So for now we assume
438 * the programmer got it right.
439 */
440
441 context->methods->reset(context);
442 context->isReset = true;
443 }
444}
445
446/*
447 * MemoryContextResetChildren
448 * Release all space allocated within a context's descendants,
449 * but don't delete the contexts themselves. The named context
450 * itself is not touched.
451 */
452void
454{
456
457 for (MemoryContext curr = context->firstchild;
458 curr != NULL;
460 {
462 }
463}
464
465/*
466 * MemoryContextDelete
467 * Delete a context and its descendants, and release all space
468 * allocated therein.
469 *
470 * The type-specific delete routine removes all storage for the context,
471 * but we have to deal with descendant nodes here.
472 */
473void
475{
477
479
480 /*
481 * Delete subcontexts from the bottom up.
482 *
483 * Note: Do not use recursion here. A "stack depth limit exceeded" error
484 * would be unpleasant if we're already in the process of cleaning up from
485 * transaction abort. We also cannot use MemoryContextTraverseNext() here
486 * because we modify the tree as we go.
487 */
488 curr = context;
489 for (;;)
490 {
491 MemoryContext parent;
492
493 /* Descend down until we find a leaf context with no children */
494 while (curr->firstchild != NULL)
496
497 /*
498 * We're now at a leaf with no children. Free it and continue from the
499 * parent. Or if this was the original node, we're all done.
500 */
501 parent = curr->parent;
503
504 if (curr == context)
505 break;
506 curr = parent;
507 }
508}
509
510/*
511 * Subroutine of MemoryContextDelete,
512 * to delete a context that has no children.
513 * We must also delink the context from its parent, if it has one.
514 */
515static void
517{
519 /* We had better not be deleting TopMemoryContext ... */
520 Assert(context != TopMemoryContext);
521 /* And not CurrentMemoryContext, either */
522 Assert(context != CurrentMemoryContext);
523 /* All the children should've been deleted already */
524 Assert(context->firstchild == NULL);
525
526 /*
527 * It's not entirely clear whether 'tis better to do this before or after
528 * delinking the context; but an error in a callback will likely result in
529 * leaking the whole context (if it's not a root context) if we do it
530 * after, so let's do it before.
531 */
533
534 /*
535 * We delink the context from its parent before deleting it, so that if
536 * there's an error we won't have deleted/busted contexts still attached
537 * to the context tree. Better a leak than a crash.
538 */
540
541 /*
542 * Also reset the context's ident pointer, in case it points into the
543 * context. This would only matter if someone tries to get stats on the
544 * (already unlinked) context, which is unlikely, but let's be safe.
545 */
546 context->ident = NULL;
547
548 context->methods->delete_context(context);
549}
550
551/*
552 * MemoryContextDeleteChildren
553 * Delete all the descendants of the named context and release all
554 * space allocated therein. The named context itself is not touched.
555 */
556void
558{
560
561 /*
562 * MemoryContextDelete will delink the child from me, so just iterate as
563 * long as there is a child.
564 */
565 while (context->firstchild != NULL)
567}
568
569/*
570 * MemoryContextRegisterResetCallback
571 * Register a function to be called before next context reset/delete.
572 * Such callbacks will be called in reverse order of registration.
573 *
574 * The caller is responsible for allocating a MemoryContextCallback struct
575 * to hold the info about this callback request, and for filling in the
576 * "func" and "arg" fields in the struct to show what function to call with
577 * what argument. Typically the callback struct should be allocated within
578 * the specified context, since that means it will automatically be freed
579 * when no longer needed.
580 *
581 * Note that callers can assume this cannot fail.
582 */
583void
586{
588
589 /* Push onto head so this will be called before older registrants. */
590 cb->next = context->reset_cbs;
591 context->reset_cbs = cb;
592 /* Mark the context as non-reset (it probably is already). */
593 context->isReset = false;
594}
595
596/*
597 * MemoryContextUnregisterResetCallback
598 * Undo the effects of MemoryContextRegisterResetCallback.
599 *
600 * This can be used if a callback's effects are no longer required
601 * at some point before the context has been reset/deleted. It is the
602 * caller's responsibility to pfree the callback struct (if needed).
603 *
604 * An assertion failure occurs if the callback was not registered.
605 * We could alternatively define that case as a no-op, but that seems too
606 * likely to mask programming errors such as passing the wrong context.
607 */
608void
611{
613 *cur;
614
616
617 for (prev = NULL, cur = context->reset_cbs; cur != NULL;
618 prev = cur, cur = cur->next)
619 {
620 if (cur != cb)
621 continue;
622 if (prev)
623 prev->next = cur->next;
624 else
625 context->reset_cbs = cur->next;
626 return;
627 }
628 Assert(false);
629}
630
631/*
632 * MemoryContextCallResetCallbacks
633 * Internal function to call all registered callbacks for context.
634 */
635static void
637{
639
640 /*
641 * We pop each callback from the list before calling. That way, if an
642 * error occurs inside the callback, we won't try to call it a second time
643 * in the likely event that we reset or delete the context later.
644 */
645 while ((cb = context->reset_cbs) != NULL)
646 {
647 context->reset_cbs = cb->next;
648 cb->func(cb->arg);
649 }
650}
651
652/*
653 * MemoryContextSetIdentifier
654 * Set the identifier string for a memory context.
655 *
656 * An identifier can be provided to help distinguish among different contexts
657 * of the same kind in memory context stats dumps. The identifier string
658 * must live at least as long as the context it is for; typically it is
659 * allocated inside that context, so that it automatically goes away on
660 * context deletion. Pass id = NULL to forget any old identifier.
661 */
662void
663MemoryContextSetIdentifier(MemoryContext context, const char *id)
664{
666 context->ident = id;
667}
668
669/*
670 * MemoryContextSetParent
671 * Change a context to belong to a new parent (or no parent).
672 *
673 * We provide this as an API function because it is sometimes useful to
674 * change a context's lifespan after creation. For example, a context
675 * might be created underneath a transient context, filled with data,
676 * and then reparented underneath CacheMemoryContext to make it long-lived.
677 * In this way no special effort is needed to get rid of the context in case
678 * a failure occurs before its contents are completely set up.
679 *
680 * Callers often assume that this function cannot fail, so don't put any
681 * elog(ERROR) calls in it.
682 *
683 * A possible caller error is to reparent a context under itself, creating
684 * a loop in the context graph. We assert here that context != new_parent,
685 * but checking for multi-level loops seems more trouble than it's worth.
686 */
687void
689{
691 Assert(context != new_parent);
692
693 /* Fast path if it's got correct parent already */
694 if (new_parent == context->parent)
695 return;
696
697 /* Delink from existing parent, if any */
698 if (context->parent)
699 {
700 MemoryContext parent = context->parent;
701
702 if (context->prevchild != NULL)
703 context->prevchild->nextchild = context->nextchild;
704 else
705 {
706 Assert(parent->firstchild == context);
707 parent->firstchild = context->nextchild;
708 }
709
710 if (context->nextchild != NULL)
711 context->nextchild->prevchild = context->prevchild;
712 }
713
714 /* And relink */
715 if (new_parent)
716 {
718 context->parent = new_parent;
719 context->prevchild = NULL;
720 context->nextchild = new_parent->firstchild;
721 if (new_parent->firstchild != NULL)
722 new_parent->firstchild->prevchild = context;
723 new_parent->firstchild = context;
724 }
725 else
726 {
727 context->parent = NULL;
728 context->prevchild = NULL;
729 context->nextchild = NULL;
730 }
731}
732
733/*
734 * MemoryContextAllowInCriticalSection
735 * Allow/disallow allocations in this memory context within a critical
736 * section.
737 *
738 * Normally, memory allocations are not allowed within a critical section,
739 * because a failure would lead to PANIC. There are a few exceptions to
740 * that, like allocations related to debugging code that is not supposed to
741 * be enabled in production. This function can be used to exempt specific
742 * memory contexts from the assertion in palloc().
743 */
744void
746{
748
749 context->allowInCritSection = allow;
750}
751
752/*
753 * GetMemoryChunkContext
754 * Given a currently-allocated chunk, determine the MemoryContext that
755 * the chunk belongs to.
756 */
758GetMemoryChunkContext(void *pointer)
759{
760 return MCXT_METHOD(pointer, get_chunk_context) (pointer);
761}
762
763/*
764 * GetMemoryChunkSpace
765 * Given a currently-allocated chunk, determine the total space
766 * it occupies (including all memory-allocation overhead).
767 *
768 * This is useful for measuring the total space occupied by a set of
769 * allocated chunks.
770 */
771Size
772GetMemoryChunkSpace(void *pointer)
773{
774 return MCXT_METHOD(pointer, get_chunk_space) (pointer);
775}
776
777/*
778 * MemoryContextGetParent
779 * Get the parent context (if any) of the specified context
780 */
783{
785
786 return context->parent;
787}
788
789/*
790 * MemoryContextIsEmpty
791 * Is a memory context empty of any allocated space?
792 */
793bool
795{
797
798 /*
799 * For now, we consider a memory context nonempty if it has any children;
800 * perhaps this should be changed later.
801 */
802 if (context->firstchild != NULL)
803 return false;
804 /* Otherwise use the type-specific inquiry */
805 return context->methods->is_empty(context);
806}
807
808/*
809 * Find the memory allocated to blocks for this memory context. If recurse is
810 * true, also include children.
811 */
812Size
813MemoryContextMemAllocated(MemoryContext context, bool recurse)
814{
815 Size total = context->mem_allocated;
816
818
819 if (recurse)
820 {
821 for (MemoryContext curr = context->firstchild;
822 curr != NULL;
824 {
825 total += curr->mem_allocated;
826 }
827 }
828
829 return total;
830}
831
832/*
833 * Return the memory consumption statistics about the given context and its
834 * children.
835 */
836void
839{
841
842 memset(consumed, 0, sizeof(*consumed));
843
844 /* Examine the context itself */
845 context->methods->stats(context, NULL, NULL, consumed, false);
846
847 /* Examine children, using iteration not recursion */
848 for (MemoryContext curr = context->firstchild;
849 curr != NULL;
851 {
852 curr->methods->stats(curr, NULL, NULL, consumed, false);
853 }
854}
855
856/*
857 * MemoryContextStats
858 * Print statistics about the named context and all its descendants.
859 *
860 * This is just a debugging utility, so it's not very fancy. However, we do
861 * make some effort to summarize when the output would otherwise be very long.
862 * The statistics are sent to stderr.
863 */
864void
866{
867 /* Hard-wired limits are usually good enough */
868 MemoryContextStatsDetail(context, 100, 100, true);
869}
870
871/*
872 * MemoryContextStatsDetail
873 *
874 * Entry point for use if you want to vary the number of child contexts shown.
875 *
876 * If print_to_stderr is true, print statistics about the memory contexts
877 * with fprintf(stderr), otherwise use ereport().
878 */
879void
881 int max_level, int max_children,
882 bool print_to_stderr)
883{
885
886 memset(&grand_totals, 0, sizeof(grand_totals));
887
890
891 if (print_to_stderr)
893 "Grand total: %zu bytes in %zu blocks; %zu free (%zu chunks); %zu used\n",
894 grand_totals.totalspace, grand_totals.nblocks,
895 grand_totals.freespace, grand_totals.freechunks,
896 grand_totals.totalspace - grand_totals.freespace);
897 else
898 {
899 /*
900 * Use LOG_SERVER_ONLY to prevent the memory contexts from being sent
901 * to the connected client.
902 *
903 * We don't buffer the information about all memory contexts in a
904 * backend into StringInfo and log it as one message. That would
905 * require the buffer to be enlarged, risking an OOM as there could be
906 * a large number of memory contexts in a backend. Instead, we log
907 * one message per memory context.
908 */
910 (errhidestmt(true),
911 errhidecontext(true),
912 errmsg_internal("Grand total: %zu bytes in %zu blocks; %zu free (%zu chunks); %zu used",
913 grand_totals.totalspace, grand_totals.nblocks,
914 grand_totals.freespace, grand_totals.freechunks,
915 grand_totals.totalspace - grand_totals.freespace)));
916 }
917}
918
919/*
920 * MemoryContextStatsInternal
921 * One recursion level for MemoryContextStats
922 *
923 * Print stats for this context if possible, but in any case accumulate counts
924 * into *totals (if not NULL).
925 */
926static void
928 int max_level, int max_children,
930 bool print_to_stderr)
931{
932 MemoryContext child;
933 int ichild;
934
936
937 /* Examine the context itself */
938 context->methods->stats(context,
940 &level,
942
943 /*
944 * Examine children.
945 *
946 * If we are past the recursion depth limit or already running low on
947 * stack, do not print them explicitly but just summarize them. Similarly,
948 * if there are more than max_children of them, we do not print the rest
949 * explicitly, but just summarize them.
950 */
951 child = context->firstchild;
952 ichild = 0;
953 if (level <= max_level && !stack_is_too_deep())
954 {
955 for (; child != NULL && ichild < max_children;
956 child = child->nextchild, ichild++)
957 {
958 MemoryContextStatsInternal(child, level + 1,
960 totals,
962 }
963 }
964
965 if (child != NULL)
966 {
967 /* Summarize the rest of the children, avoiding recursion. */
969
970 memset(&local_totals, 0, sizeof(local_totals));
971
972 ichild = 0;
973 while (child != NULL)
974 {
975 child->methods->stats(child, NULL, NULL, &local_totals, false);
976 ichild++;
977 child = MemoryContextTraverseNext(child, context);
978 }
979
980 if (print_to_stderr)
981 {
982 for (int i = 0; i < level; i++)
983 fprintf(stderr, " ");
985 "%d more child contexts containing %zu total in %zu blocks; %zu free (%zu chunks); %zu used\n",
986 ichild,
987 local_totals.totalspace,
988 local_totals.nblocks,
989 local_totals.freespace,
990 local_totals.freechunks,
991 local_totals.totalspace - local_totals.freespace);
992 }
993 else
995 (errhidestmt(true),
996 errhidecontext(true),
997 errmsg_internal("level: %d; %d more child contexts containing %zu total in %zu blocks; %zu free (%zu chunks); %zu used",
998 level,
999 ichild,
1000 local_totals.totalspace,
1001 local_totals.nblocks,
1002 local_totals.freespace,
1003 local_totals.freechunks,
1004 local_totals.totalspace - local_totals.freespace)));
1005
1006 if (totals)
1007 {
1008 totals->nblocks += local_totals.nblocks;
1009 totals->freechunks += local_totals.freechunks;
1010 totals->totalspace += local_totals.totalspace;
1011 totals->freespace += local_totals.freespace;
1012 }
1013 }
1014}
1015
1016/*
1017 * MemoryContextStatsPrint
1018 * Print callback used by MemoryContextStatsInternal
1019 *
1020 * For now, the passthru pointer just points to "int level"; later we might
1021 * make that more complicated.
1022 */
1023static void
1025 const char *stats_string,
1026 bool print_to_stderr)
1027{
1028 int level = *(int *) passthru;
1029 const char *name = context->name;
1030 const char *ident = context->ident;
1031 char truncated_ident[110];
1032 int i;
1033
1034 /*
1035 * It seems preferable to label dynahash contexts with just the hash table
1036 * name. Those are already unique enough, so the "dynahash" part isn't
1037 * very helpful, and this way is more consistent with pre-v11 practice.
1038 */
1039 if (ident && strcmp(name, "dynahash") == 0)
1040 {
1041 name = ident;
1042 ident = NULL;
1043 }
1044
1045 truncated_ident[0] = '\0';
1046
1047 if (ident)
1048 {
1049 /*
1050 * Some contexts may have very long identifiers (e.g., SQL queries).
1051 * Arbitrarily truncate at 100 bytes, but be careful not to break
1052 * multibyte characters. Also, replace ASCII control characters, such
1053 * as newlines, with spaces.
1054 */
1055 int idlen = strlen(ident);
1056 bool truncated = false;
1057
1058 strcpy(truncated_ident, ": ");
1060
1061 if (idlen > 100)
1062 {
1063 idlen = pg_mbcliplen(ident, idlen, 100);
1064 truncated = true;
1065 }
1066
1067 while (idlen-- > 0)
1068 {
1069 unsigned char c = *ident++;
1070
1071 if (c < ' ')
1072 c = ' ';
1073 truncated_ident[i++] = c;
1074 }
1075 truncated_ident[i] = '\0';
1076
1077 if (truncated)
1078 strcat(truncated_ident, "...");
1079 }
1080
1081 if (print_to_stderr)
1082 {
1083 for (i = 1; i < level; i++)
1084 fprintf(stderr, " ");
1086 }
1087 else
1089 (errhidestmt(true),
1090 errhidecontext(true),
1091 errmsg_internal("level: %d; %s: %s%s",
1092 level, name, stats_string, truncated_ident)));
1093}
1094
1095/*
1096 * MemoryContextCheck
1097 * Check all chunks in the named context and its children.
1098 *
1099 * This is just a debugging utility, so it's not fancy.
1100 */
1101#ifdef MEMORY_CONTEXT_CHECKING
1102void
1104{
1105 Assert(MemoryContextIsValid(context));
1106 context->methods->check(context);
1107
1108 for (MemoryContext curr = context->firstchild;
1109 curr != NULL;
1111 {
1113 curr->methods->check(curr);
1114 }
1115}
1116#endif
1117
1118/*
1119 * MemoryContextCreate
1120 * Context-type-independent part of context creation.
1121 *
1122 * This is only intended to be called by context-type-specific
1123 * context creation routines, not by the unwashed masses.
1124 *
1125 * The memory context creation procedure goes like this:
1126 * 1. Context-type-specific routine makes some initial space allocation,
1127 * including enough space for the context header. If it fails,
1128 * it can ereport() with no damage done.
1129 * 2. Context-type-specific routine sets up all type-specific fields of
1130 * the header (those beyond MemoryContextData proper), as well as any
1131 * other management fields it needs to have a fully valid context.
1132 * Usually, failure in this step is impossible, but if it's possible
1133 * the initial space allocation should be freed before ereport'ing.
1134 * 3. Context-type-specific routine calls MemoryContextCreate() to fill in
1135 * the generic header fields and link the context into the context tree.
1136 * 4. We return to the context-type-specific routine, which finishes
1137 * up type-specific initialization. This routine can now do things
1138 * that might fail (like allocate more memory), so long as it's
1139 * sure the node is left in a state that delete will handle.
1140 *
1141 * node: the as-yet-uninitialized common part of the context header node.
1142 * tag: NodeTag code identifying the memory context type.
1143 * method_id: MemoryContextMethodID of the context-type being created.
1144 * parent: parent context, or NULL if this will be a top-level context.
1145 * name: name of context (must be statically allocated).
1146 *
1147 * Context routines generally assume that MemoryContextCreate can't fail,
1148 * so this can contain Assert but not elog/ereport.
1149 */
1150void
1152 NodeTag tag,
1154 MemoryContext parent,
1155 const char *name)
1156{
1157 /* Creating new memory contexts is not allowed in a critical section */
1159
1160 /* Validate parent, to help prevent crazy context linkages */
1161 Assert(parent == NULL || MemoryContextIsValid(parent));
1162 Assert(node != parent);
1163
1164 /* Initialize all standard fields of memory context header */
1165 node->type = tag;
1166 node->isReset = true;
1167 node->methods = &mcxt_methods[method_id];
1168 node->parent = parent;
1169 node->firstchild = NULL;
1170 node->mem_allocated = 0;
1171 node->prevchild = NULL;
1172 node->name = name;
1173 node->ident = NULL;
1174 node->reset_cbs = NULL;
1175
1176 /* OK to link node into context tree */
1177 if (parent)
1178 {
1179 node->nextchild = parent->firstchild;
1180 if (parent->firstchild != NULL)
1181 parent->firstchild->prevchild = node;
1182 parent->firstchild = node;
1183 /* inherit allowInCritSection flag from parent */
1184 node->allowInCritSection = parent->allowInCritSection;
1185 }
1186 else
1187 {
1188 node->nextchild = NULL;
1189 node->allowInCritSection = false;
1190 }
1191}
1192
1193/*
1194 * MemoryContextAllocationFailure
1195 * For use by MemoryContextMethods implementations to handle when malloc
1196 * returns NULL. The behavior is specific to whether MCXT_ALLOC_NO_OOM
1197 * is in 'flags'.
1198 */
1199void *
1200MemoryContextAllocationFailure(MemoryContext context, Size size, int flags)
1201{
1202 if ((flags & MCXT_ALLOC_NO_OOM) == 0)
1203 {
1204 if (TopMemoryContext)
1206 ereport(ERROR,
1208 errmsg("out of memory"),
1209 errdetail("Failed on request of size %zu in memory context \"%s\".",
1210 size, context->name)));
1211 }
1212 return NULL;
1213}
1214
1215/*
1216 * MemoryContextSizeFailure
1217 * For use by MemoryContextMethods implementations to handle invalid
1218 * memory allocation request sizes.
1219 */
1220void
1221MemoryContextSizeFailure(MemoryContext context, Size size, int flags)
1222{
1223 elog(ERROR, "invalid memory alloc request size %zu", size);
1224}
1225
1226/*
1227 * MemoryContextAlloc
1228 * Allocate space within the specified context.
1229 *
1230 * This could be turned into a macro, but we'd have to import
1231 * nodes/memnodes.h into postgres.h which seems a bad idea.
1232 */
1233void *
1235{
1236 void *ret;
1237
1238 Assert(MemoryContextIsValid(context));
1240
1241 context->isReset = false;
1242
1243 /*
1244 * For efficiency reasons, we purposefully offload the handling of
1245 * allocation failures to the MemoryContextMethods implementation as this
1246 * allows these checks to be performed only when an actual malloc needs to
1247 * be done to request more memory from the OS. Additionally, not having
1248 * to execute any instructions after this call allows the compiler to use
1249 * the sibling call optimization. If you're considering adding code after
1250 * this call, consider making it the responsibility of the 'alloc'
1251 * function instead.
1252 */
1253 ret = context->methods->alloc(context, size, 0);
1254
1255 VALGRIND_MEMPOOL_ALLOC(context, ret, size);
1256
1257 return ret;
1258}
1259
1260/*
1261 * MemoryContextAllocZero
1262 * Like MemoryContextAlloc, but clears allocated memory
1263 *
1264 * We could just call MemoryContextAlloc then clear the memory, but this
1265 * is a very common combination, so we provide the combined operation.
1266 */
1267void *
1269{
1270 void *ret;
1271
1272 Assert(MemoryContextIsValid(context));
1274
1275 context->isReset = false;
1276
1277 ret = context->methods->alloc(context, size, 0);
1278
1279 VALGRIND_MEMPOOL_ALLOC(context, ret, size);
1280
1281 MemSetAligned(ret, 0, size);
1282
1283 return ret;
1284}
1285
1286/*
1287 * MemoryContextAllocExtended
1288 * Allocate space within the specified context using the given flags.
1289 */
1290void *
1291MemoryContextAllocExtended(MemoryContext context, Size size, int flags)
1292{
1293 void *ret;
1294
1295 Assert(MemoryContextIsValid(context));
1297
1298 if (!((flags & MCXT_ALLOC_HUGE) != 0 ? AllocHugeSizeIsValid(size) :
1299 AllocSizeIsValid(size)))
1300 elog(ERROR, "invalid memory alloc request size %zu", size);
1301
1302 context->isReset = false;
1303
1304 ret = context->methods->alloc(context, size, flags);
1305 if (unlikely(ret == NULL))
1306 return NULL;
1307
1308 VALGRIND_MEMPOOL_ALLOC(context, ret, size);
1309
1310 if ((flags & MCXT_ALLOC_ZERO) != 0)
1311 MemSetAligned(ret, 0, size);
1312
1313 return ret;
1314}
1315
1316/*
1317 * HandleLogMemoryContextInterrupt
1318 * Handle receipt of an interrupt indicating logging of memory
1319 * contexts.
1320 *
1321 * All the actual work is deferred to ProcessLogMemoryContextInterrupt(),
1322 * because we cannot safely emit a log message inside the signal handler.
1323 */
1324void
1326{
1327 InterruptPending = true;
1329 /* latch will be set by procsignal_sigusr1_handler */
1330}
1331
1332/*
1333 * ProcessLogMemoryContextInterrupt
1334 * Perform logging of memory contexts of this backend process.
1335 *
1336 * Any backend that participates in ProcSignal signaling must arrange
1337 * to call this function if we see LogMemoryContextPending set.
1338 * It is called from CHECK_FOR_INTERRUPTS(), which is enough because
1339 * the target process for logging of memory contexts is a backend.
1340 */
1341void
1343{
1345
1346 /*
1347 * Exit immediately if memory context logging is already in progress. This
1348 * prevents recursive calls, which could occur if logging is requested
1349 * repeatedly and rapidly, potentially leading to infinite recursion and a
1350 * crash.
1351 */
1353 return;
1355
1356 PG_TRY();
1357 {
1358 /*
1359 * Use LOG_SERVER_ONLY to prevent this message from being sent to the
1360 * connected client.
1361 */
1363 (errhidestmt(true),
1364 errhidecontext(true),
1365 errmsg("logging memory contexts of PID %d", MyProcPid)));
1366
1367 /*
1368 * When a backend process is consuming huge memory, logging all its
1369 * memory contexts might overrun available disk space. To prevent
1370 * this, we limit the depth of the hierarchy, as well as the number of
1371 * child contexts to log per parent to 100.
1372 *
1373 * As with MemoryContextStats(), we suppose that practical cases where
1374 * the dump gets long will typically be huge numbers of siblings under
1375 * the same parent context; while the additional debugging value from
1376 * seeing details about individual siblings beyond 100 will not be
1377 * large.
1378 */
1380 }
1381 PG_FINALLY();
1382 {
1384 }
1385 PG_END_TRY();
1386}
1387
1388void *
1389palloc(Size size)
1390{
1391 /* duplicates MemoryContextAlloc to avoid increased overhead */
1392 void *ret;
1394
1395 Assert(MemoryContextIsValid(context));
1397
1398 context->isReset = false;
1399
1400 /*
1401 * For efficiency reasons, we purposefully offload the handling of
1402 * allocation failures to the MemoryContextMethods implementation as this
1403 * allows these checks to be performed only when an actual malloc needs to
1404 * be done to request more memory from the OS. Additionally, not having
1405 * to execute any instructions after this call allows the compiler to use
1406 * the sibling call optimization. If you're considering adding code after
1407 * this call, consider making it the responsibility of the 'alloc'
1408 * function instead.
1409 */
1410 ret = context->methods->alloc(context, size, 0);
1411 /* We expect OOM to be handled by the alloc function */
1412 Assert(ret != NULL);
1413 VALGRIND_MEMPOOL_ALLOC(context, ret, size);
1414
1415 return ret;
1416}
1417
1418void *
1419palloc0(Size size)
1420{
1421 /* duplicates MemoryContextAllocZero to avoid increased overhead */
1422 void *ret;
1424
1425 Assert(MemoryContextIsValid(context));
1427
1428 context->isReset = false;
1429
1430 ret = context->methods->alloc(context, size, 0);
1431 /* We expect OOM to be handled by the alloc function */
1432 Assert(ret != NULL);
1433 VALGRIND_MEMPOOL_ALLOC(context, ret, size);
1434
1435 MemSetAligned(ret, 0, size);
1436
1437 return ret;
1438}
1439
1440void *
1441palloc_extended(Size size, int flags)
1442{
1443 /* duplicates MemoryContextAllocExtended to avoid increased overhead */
1444 void *ret;
1446
1447 Assert(MemoryContextIsValid(context));
1449
1450 context->isReset = false;
1451
1452 ret = context->methods->alloc(context, size, flags);
1453 if (unlikely(ret == NULL))
1454 {
1455 /* NULL can be returned only when using MCXT_ALLOC_NO_OOM */
1456 Assert(flags & MCXT_ALLOC_NO_OOM);
1457 return NULL;
1458 }
1459
1460 VALGRIND_MEMPOOL_ALLOC(context, ret, size);
1461
1462 if ((flags & MCXT_ALLOC_ZERO) != 0)
1463 MemSetAligned(ret, 0, size);
1464
1465 return ret;
1466}
1467
1468/*
1469 * MemoryContextAllocAligned
1470 * Allocate 'size' bytes of memory in 'context' aligned to 'alignto'
1471 * bytes.
1472 *
1473 * Currently, we align addresses by requesting additional bytes from the
1474 * MemoryContext's standard allocator function and then aligning the returned
1475 * address by the required alignment. This means that the given MemoryContext
1476 * must support providing us with a chunk of memory that's larger than 'size'.
1477 * For allocators such as Slab, that's not going to work, as slab only allows
1478 * chunks of the size that's specified when the context is created.
1479 *
1480 * 'alignto' must be a power of 2.
1481 * 'flags' may be 0 or set the same as MemoryContextAllocExtended().
1482 */
1483void *
1485 Size size, Size alignto, int flags)
1486{
1489 void *unaligned;
1490 void *aligned;
1491
1492 /*
1493 * Restrict alignto to ensure that it can fit into the "value" field of
1494 * the redirection MemoryChunk, and that the distance back to the start of
1495 * the unaligned chunk will fit into the space available for that. This
1496 * isn't a limitation in practice, since it wouldn't make much sense to
1497 * waste that much space.
1498 */
1499 Assert(alignto < (128 * 1024 * 1024));
1500
1501 /* ensure alignto is a power of 2 */
1502 Assert((alignto & (alignto - 1)) == 0);
1503
1504 /*
1505 * If the alignment requirements are less than what we already guarantee
1506 * then just use the standard allocation function.
1507 */
1509 return MemoryContextAllocExtended(context, size, flags);
1510
1511 /*
1512 * We implement aligned pointers by simply allocating enough memory for
1513 * the requested size plus the alignment and an additional "redirection"
1514 * MemoryChunk. This additional MemoryChunk is required for operations
1515 * such as pfree when used on the pointer returned by this function. We
1516 * use this redirection MemoryChunk in order to find the pointer to the
1517 * memory that was returned by the MemoryContextAllocExtended call below.
1518 * We do that by "borrowing" the block offset field and instead of using
1519 * that to find the offset into the owning block, we use it to find the
1520 * original allocated address.
1521 *
1522 * Here we must allocate enough extra memory so that we can still align
1523 * the pointer returned by MemoryContextAllocExtended and also have enough
1524 * space for the redirection MemoryChunk. Since allocations will already
1525 * be at least aligned by MAXIMUM_ALIGNOF, we can subtract that amount
1526 * from the allocation size to save a little memory.
1527 */
1529
1530#ifdef MEMORY_CONTEXT_CHECKING
1531 /* ensure there's space for a sentinel byte */
1532 alloc_size += 1;
1533#endif
1534
1535 /*
1536 * Perform the actual allocation, but do not pass down MCXT_ALLOC_ZERO.
1537 * This ensures that wasted bytes beyond the aligned chunk do not become
1538 * DEFINED.
1539 */
1541 flags & ~MCXT_ALLOC_ZERO);
1542
1543 /* compute the aligned pointer */
1544 aligned = (void *) TYPEALIGN(alignto, (char *) unaligned +
1545 sizeof(MemoryChunk));
1546
1548
1549 /*
1550 * We set the redirect MemoryChunk so that the block offset calculation is
1551 * used to point back to the 'unaligned' allocated chunk. This allows us
1552 * to use MemoryChunkGetBlock() to find the unaligned chunk when we need
1553 * to perform operations such as pfree() and repalloc().
1554 *
1555 * We store 'alignto' in the MemoryChunk's 'value' so that we know what
1556 * the alignment was set to should we ever be asked to realloc this
1557 * pointer.
1558 */
1561
1562 /* double check we produced a correctly aligned pointer */
1563 Assert((void *) TYPEALIGN(alignto, aligned) == aligned);
1564
1565#ifdef MEMORY_CONTEXT_CHECKING
1566 alignedchunk->requested_size = size;
1567 /* set mark to catch clobber of "unused" space */
1568 set_sentinel(aligned, size);
1569#endif
1570
1571 /*
1572 * MemoryContextAllocExtended marked the whole unaligned chunk as a
1573 * vchunk. Undo that, instead making just the aligned chunk be a vchunk.
1574 * This prevents Valgrind from complaining that the vchunk is possibly
1575 * leaked, since only pointers to the aligned chunk will exist.
1576 *
1577 * After these calls, the aligned chunk will be marked UNDEFINED, and all
1578 * the rest of the unaligned chunk (the redirection chunk header, the
1579 * padding bytes before it, and any wasted trailing bytes) will be marked
1580 * NOACCESS, which is what we want.
1581 */
1583 VALGRIND_MEMPOOL_ALLOC(context, aligned, size);
1584
1585 /* Now zero (and make DEFINED) just the aligned chunk, if requested */
1586 if ((flags & MCXT_ALLOC_ZERO) != 0)
1587 MemSetAligned(aligned, 0, size);
1588
1589 return aligned;
1590}
1591
1592/*
1593 * palloc_aligned
1594 * Allocate 'size' bytes returning a pointer that's aligned to the
1595 * 'alignto' boundary.
1596 *
1597 * Currently, we align addresses by requesting additional bytes from the
1598 * MemoryContext's standard allocator function and then aligning the returned
1599 * address by the required alignment. This means that the given MemoryContext
1600 * must support providing us with a chunk of memory that's larger than 'size'.
1601 * For allocators such as Slab, that's not going to work, as slab only allows
1602 * chunks of the size that's specified when the context is created.
1603 *
1604 * 'alignto' must be a power of 2.
1605 * 'flags' may be 0 or set the same as MemoryContextAllocExtended().
1606 */
1607void *
1608palloc_aligned(Size size, Size alignto, int flags)
1609{
1611}
1612
1613/*
1614 * pfree
1615 * Release an allocated chunk.
1616 */
1617void
1618pfree(void *pointer)
1619{
1620#ifdef USE_VALGRIND
1621 MemoryContext context = GetMemoryChunkContext(pointer);
1622#endif
1623
1624 MCXT_METHOD(pointer, free_p) (pointer);
1625
1626 VALGRIND_MEMPOOL_FREE(context, pointer);
1627}
1628
1629/*
1630 * repalloc
1631 * Adjust the size of a previously allocated chunk.
1632 */
1633void *
1634repalloc(void *pointer, Size size)
1635{
1636#if defined(USE_ASSERT_CHECKING) || defined(USE_VALGRIND)
1637 MemoryContext context = GetMemoryChunkContext(pointer);
1638#endif
1639 void *ret;
1640
1642
1643 /* isReset must be false already */
1644 Assert(!context->isReset);
1645
1646 /*
1647 * For efficiency reasons, we purposefully offload the handling of
1648 * allocation failures to the MemoryContextMethods implementation as this
1649 * allows these checks to be performed only when an actual malloc needs to
1650 * be done to request more memory from the OS. Additionally, not having
1651 * to execute any instructions after this call allows the compiler to use
1652 * the sibling call optimization. If you're considering adding code after
1653 * this call, consider making it the responsibility of the 'realloc'
1654 * function instead.
1655 */
1656 ret = MCXT_METHOD(pointer, realloc) (pointer, size, 0);
1657
1658 VALGRIND_MEMPOOL_CHANGE(context, pointer, ret, size);
1659
1660 return ret;
1661}
1662
1663/*
1664 * repalloc_extended
1665 * Adjust the size of a previously allocated chunk,
1666 * with HUGE and NO_OOM options.
1667 */
1668void *
1669repalloc_extended(void *pointer, Size size, int flags)
1670{
1671#if defined(USE_ASSERT_CHECKING) || defined(USE_VALGRIND)
1672 MemoryContext context = GetMemoryChunkContext(pointer);
1673#endif
1674 void *ret;
1675
1677
1678 /* isReset must be false already */
1679 Assert(!context->isReset);
1680
1681 /*
1682 * For efficiency reasons, we purposefully offload the handling of
1683 * allocation failures to the MemoryContextMethods implementation as this
1684 * allows these checks to be performed only when an actual malloc needs to
1685 * be done to request more memory from the OS. Additionally, not having
1686 * to execute any instructions after this call allows the compiler to use
1687 * the sibling call optimization. If you're considering adding code after
1688 * this call, consider making it the responsibility of the 'realloc'
1689 * function instead.
1690 */
1691 ret = MCXT_METHOD(pointer, realloc) (pointer, size, flags);
1692 if (unlikely(ret == NULL))
1693 return NULL;
1694
1695 VALGRIND_MEMPOOL_CHANGE(context, pointer, ret, size);
1696
1697 return ret;
1698}
1699
1700/*
1701 * repalloc0
1702 * Adjust the size of a previously allocated chunk and zero out the added
1703 * space.
1704 */
1705void *
1706repalloc0(void *pointer, Size oldsize, Size size)
1707{
1708 void *ret;
1709
1710 /* catch wrong argument order */
1711 if (unlikely(oldsize > size))
1712 elog(ERROR, "invalid repalloc0 call: oldsize %zu, new size %zu",
1713 oldsize, size);
1714
1715 ret = repalloc(pointer, size);
1716 memset((char *) ret + oldsize, 0, (size - oldsize));
1717 return ret;
1718}
1719
1720/*
1721 * Support for safe calculation of memory request sizes
1722 *
1723 * These functions perform the requested calculation, but throw error if the
1724 * result overflows.
1725 *
1726 * An important property of these functions is that if an argument was a
1727 * negative signed int before promotion (implying overflow in calculating it)
1728 * we will detect that as an error. That happens because we reject results
1729 * larger than SIZE_MAX / 2 later on, in the actual allocation step.
1730 */
1731Size
1733{
1734 Size result;
1735
1738 return result;
1739}
1740
1741pg_noreturn static pg_noinline void
1743{
1744 ereport(ERROR,
1746 errmsg("invalid memory allocation request size %zu + %zu",
1747 s1, s2)));
1748}
1749
1750Size
1752{
1753 Size result;
1754
1757 return result;
1758}
1759
1760pg_noreturn static pg_noinline void
1762{
1763 ereport(ERROR,
1765 errmsg("invalid memory allocation request size %zu * %zu",
1766 s1, s2)));
1767}
1768
1769/*
1770 * palloc_mul
1771 * Equivalent to palloc(mul_size(s1, s2)).
1772 */
1773void *
1775{
1776 /* inline mul_size() for efficiency */
1777 Size req;
1778
1781 return palloc(req);
1782}
1783
1784/*
1785 * palloc0_mul
1786 * Equivalent to palloc0(mul_size(s1, s2)).
1787 *
1788 * This is comparable to standard calloc's behavior.
1789 */
1790void *
1792{
1793 /* inline mul_size() for efficiency */
1794 Size req;
1795
1798 return palloc0(req);
1799}
1800
1801/*
1802 * palloc_mul_extended
1803 * Equivalent to palloc_extended(mul_size(s1, s2), flags).
1804 */
1805void *
1806palloc_mul_extended(Size s1, Size s2, int flags)
1807{
1808 /* inline mul_size() for efficiency */
1809 Size req;
1810
1813 return palloc_extended(req, flags);
1814}
1815
1816/*
1817 * repalloc_mul
1818 * Equivalent to repalloc(p, mul_size(s1, s2)).
1819 */
1820void *
1821repalloc_mul(void *p, Size s1, Size s2)
1822{
1823 /* inline mul_size() for efficiency */
1824 Size req;
1825
1828 return repalloc(p, req);
1829}
1830
1831/*
1832 * repalloc_mul_extended
1833 * Equivalent to repalloc_extended(p, mul_size(s1, s2), flags).
1834 */
1835void *
1836repalloc_mul_extended(void *p, Size s1, Size s2, int flags)
1837{
1838 /* inline mul_size() for efficiency */
1839 Size req;
1840
1843 return repalloc_extended(p, req, flags);
1844}
1845
1846/*
1847 * MemoryContextAllocHuge
1848 * Allocate (possibly-expansive) space within the specified context.
1849 *
1850 * See considerations in comment at MaxAllocHugeSize.
1851 */
1852void *
1854{
1855 void *ret;
1856
1857 Assert(MemoryContextIsValid(context));
1859
1860 context->isReset = false;
1861
1862 /*
1863 * For efficiency reasons, we purposefully offload the handling of
1864 * allocation failures to the MemoryContextMethods implementation as this
1865 * allows these checks to be performed only when an actual malloc needs to
1866 * be done to request more memory from the OS. Additionally, not having
1867 * to execute any instructions after this call allows the compiler to use
1868 * the sibling call optimization. If you're considering adding code after
1869 * this call, consider making it the responsibility of the 'alloc'
1870 * function instead.
1871 */
1872 ret = context->methods->alloc(context, size, MCXT_ALLOC_HUGE);
1873
1874 VALGRIND_MEMPOOL_ALLOC(context, ret, size);
1875
1876 return ret;
1877}
1878
1879/*
1880 * repalloc_huge
1881 * Adjust the size of a previously allocated chunk, permitting a large
1882 * value. The previous allocation need not have been "huge".
1883 */
1884void *
1885repalloc_huge(void *pointer, Size size)
1886{
1887 /* this one seems not worth its own implementation */
1888 return repalloc_extended(pointer, size, MCXT_ALLOC_HUGE);
1889}
1890
1891/*
1892 * MemoryContextStrdup
1893 * Like strdup(), but allocate from the specified context
1894 */
1895char *
1896MemoryContextStrdup(MemoryContext context, const char *string)
1897{
1898 char *nstr;
1899 Size len = strlen(string) + 1;
1900
1901 nstr = (char *) MemoryContextAlloc(context, len);
1902
1903 memcpy(nstr, string, len);
1904
1905 return nstr;
1906}
1907
1908char *
1909pstrdup(const char *in)
1910{
1912}
1913
1914/*
1915 * pnstrdup
1916 * Like pstrdup(), but append null byte to a
1917 * not-necessarily-null-terminated input string.
1918 */
1919char *
1920pnstrdup(const char *in, Size len)
1921{
1922 char *out;
1923
1924 len = strnlen(in, len);
1925
1926 out = palloc(len + 1);
1927 memcpy(out, in, len);
1928 out[len] = '\0';
1929
1930 return out;
1931}
1932
1933/*
1934 * Make copy of string with all trailing newline characters removed.
1935 */
1936char *
1937pchomp(const char *in)
1938{
1939 size_t n;
1940
1941 n = strlen(in);
1942 while (n > 0 && in[n - 1] == '\n')
1943 n--;
1944 return pnstrdup(in, n);
1945}
#define pg_noinline
Definition c.h:321
#define MAXALIGN(LEN)
Definition c.h:896
#define TYPEALIGN(ALIGNVAL, LEN)
Definition c.h:889
#define pg_noreturn
Definition c.h:190
#define Assert(condition)
Definition c.h:943
#define MemSetAligned(start, val, len)
Definition c.h:1137
uint64_t uint64
Definition c.h:625
#define unlikely(x)
Definition c.h:438
size_t Size
Definition c.h:689
uint32 result
memcpy(sums, checksumBaseOffsets, sizeof(checksumBaseOffsets))
#define fprintf(file, fmt, msg)
Definition cubescan.l:21
struct cursor * cur
Definition ecpg.c:29
int errcode(int sqlerrcode)
Definition elog.c:875
int int errhidestmt(bool hide_stmt)
int errdetail(const char *fmt,...) pg_attribute_printf(1
#define LOG_SERVER_ONLY
Definition elog.h:33
int int errmsg_internal(const char *fmt,...) pg_attribute_printf(1
#define PG_TRY(...)
Definition elog.h:374
#define PG_END_TRY(...)
Definition elog.h:399
#define ERROR
Definition elog.h:40
int errhidecontext(bool hide_ctx)
#define elog(elevel,...)
Definition elog.h:228
#define PG_FINALLY(...)
Definition elog.h:391
#define ereport(elevel,...)
Definition elog.h:152
#define MCXT_ALLOC_ZERO
Definition fe_memutils.h:30
#define MCXT_ALLOC_HUGE
Definition fe_memutils.h:28
#define MCXT_ALLOC_NO_OOM
Definition fe_memutils.h:29
volatile sig_atomic_t LogMemoryContextPending
Definition globals.c:41
volatile sig_atomic_t InterruptPending
Definition globals.c:32
int MyProcPid
Definition globals.c:49
volatile uint32 CritSectionCount
Definition globals.c:45
#define ident
static bool pg_mul_size_overflow(size_t a, size_t b, size_t *result)
Definition int.h:642
static bool pg_add_size_overflow(size_t a, size_t b, size_t *result)
Definition int.h:608
int i
Definition isn.c:77
int pg_mbcliplen(const char *mbstr, int len, int limit)
Definition mbutils.c:1212
static void MemoryContextStatsInternal(MemoryContext context, int level, int max_level, int max_children, MemoryContextCounters *totals, bool print_to_stderr)
Definition mcxt.c:928
void MemoryContextUnregisterResetCallback(MemoryContext context, MemoryContextCallback *cb)
Definition mcxt.c:610
void * repalloc0(void *pointer, Size oldsize, Size size)
Definition mcxt.c:1707
static void MemoryContextCallResetCallbacks(MemoryContext context)
Definition mcxt.c:637
char * MemoryContextStrdup(MemoryContext context, const char *string)
Definition mcxt.c:1897
void * palloc_mul_extended(Size s1, Size s2, int flags)
Definition mcxt.c:1807
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition mcxt.c:1235
bool MemoryContextIsEmpty(MemoryContext context)
Definition mcxt.c:795
void MemoryContextMemConsumed(MemoryContext context, MemoryContextCounters *consumed)
Definition mcxt.c:838
void MemoryContextReset(MemoryContext context)
Definition mcxt.c:406
void MemoryContextCreate(MemoryContext node, NodeTag tag, MemoryContextMethodID method_id, MemoryContext parent, const char *name)
Definition mcxt.c:1152
void * MemoryContextAllocZero(MemoryContext context, Size size)
Definition mcxt.c:1269
Size add_size(Size s1, Size s2)
Definition mcxt.c:1733
char * pstrdup(const char *in)
Definition mcxt.c:1910
void HandleLogMemoryContextInterrupt(void)
Definition mcxt.c:1326
void MemoryContextRegisterResetCallback(MemoryContext context, MemoryContextCallback *cb)
Definition mcxt.c:585
void MemoryContextSetParent(MemoryContext context, MemoryContext new_parent)
Definition mcxt.c:689
static void * BogusRealloc(void *pointer, Size size, int flags)
Definition mcxt.c:316
void * repalloc(void *pointer, Size size)
Definition mcxt.c:1635
void pfree(void *pointer)
Definition mcxt.c:1619
Size GetMemoryChunkSpace(void *pointer)
Definition mcxt.c:773
void * palloc0(Size size)
Definition mcxt.c:1420
static Size BogusGetChunkSpace(void *pointer)
Definition mcxt.c:332
void * MemoryContextAllocAligned(MemoryContext context, Size size, Size alignto, int flags)
Definition mcxt.c:1485
void MemoryContextDeleteChildren(MemoryContext context)
Definition mcxt.c:558
MemoryContext TopMemoryContext
Definition mcxt.c:167
char * pchomp(const char *in)
Definition mcxt.c:1938
#define AssertNotInCriticalSection(context)
Definition mcxt.c:198
Size mul_size(Size s1, Size s2)
Definition mcxt.c:1752
static pg_noreturn pg_noinline void mul_size_error(Size s1, Size s2)
Definition mcxt.c:1762
void * palloc(Size size)
Definition mcxt.c:1390
MemoryContext CurrentMemoryContext
Definition mcxt.c:161
static MemoryContext MemoryContextTraverseNext(MemoryContext curr, MemoryContext top)
Definition mcxt.c:280
static bool LogMemoryContextInProgress
Definition mcxt.c:179
MemoryContext GetMemoryChunkContext(void *pointer)
Definition mcxt.c:759
void * MemoryContextAllocExtended(MemoryContext context, Size size, int flags)
Definition mcxt.c:1292
void MemoryContextStatsDetail(MemoryContext context, int max_level, int max_children, bool print_to_stderr)
Definition mcxt.c:881
Size MemoryContextMemAllocated(MemoryContext context, bool recurse)
Definition mcxt.c:814
void * palloc0_mul(Size s1, Size s2)
Definition mcxt.c:1792
char * pnstrdup(const char *in, Size len)
Definition mcxt.c:1921
void MemoryContextStats(MemoryContext context)
Definition mcxt.c:866
void MemoryContextInit(void)
Definition mcxt.c:362
static void BogusFree(void *pointer)
Definition mcxt.c:309
void * palloc_extended(Size size, int flags)
Definition mcxt.c:1442
void * repalloc_mul_extended(void *p, Size s1, Size s2, int flags)
Definition mcxt.c:1837
void * MemoryContextAllocationFailure(MemoryContext context, Size size, int flags)
Definition mcxt.c:1201
void * palloc_mul(Size s1, Size s2)
Definition mcxt.c:1775
static const MemoryContextMethods mcxt_methods[]
Definition mcxt.c:64
void * repalloc_extended(void *pointer, Size size, int flags)
Definition mcxt.c:1670
MemoryContext MemoryContextGetParent(MemoryContext context)
Definition mcxt.c:783
void ProcessLogMemoryContextInterrupt(void)
Definition mcxt.c:1343
MemoryContext ErrorContext
Definition mcxt.c:168
static MemoryContext BogusGetChunkContext(void *pointer)
Definition mcxt.c:324
void * repalloc_mul(void *p, Size s1, Size s2)
Definition mcxt.c:1822
void MemoryContextSizeFailure(MemoryContext context, Size size, int flags)
Definition mcxt.c:1222
void * MemoryContextAllocHuge(MemoryContext context, Size size)
Definition mcxt.c:1854
void MemoryContextDelete(MemoryContext context)
Definition mcxt.c:475
static pg_noreturn pg_noinline void add_size_error(Size s1, Size s2)
Definition mcxt.c:1743
void MemoryContextAllowInCriticalSection(MemoryContext context, bool allow)
Definition mcxt.c:746
static void MemoryContextDeleteOnly(MemoryContext context)
Definition mcxt.c:517
void MemoryContextResetChildren(MemoryContext context)
Definition mcxt.c:454
static void MemoryContextStatsPrint(MemoryContext context, void *passthru, const char *stats_string, bool print_to_stderr)
Definition mcxt.c:1025
void * repalloc_huge(void *pointer, Size size)
Definition mcxt.c:1886
void MemoryContextSetIdentifier(MemoryContext context, const char *id)
Definition mcxt.c:664
void MemoryContextResetOnly(MemoryContext context)
Definition mcxt.c:425
static uint64 GetMemoryChunkHeader(const void *pointer)
Definition mcxt.c:243
void * palloc_aligned(Size size, Size alignto, int flags)
Definition mcxt.c:1609
#define MCXT_METHOD(pointer, method)
Definition mcxt.c:205
#define VALGRIND_MAKE_MEM_DEFINED(addr, size)
Definition memdebug.h:26
#define VALGRIND_MEMPOOL_CHANGE(context, optr, nptr, size)
Definition memdebug.h:31
#define VALGRIND_MEMPOOL_ALLOC(context, addr, size)
Definition memdebug.h:29
#define VALGRIND_MEMPOOL_FREE(context, addr)
Definition memdebug.h:30
#define VALGRIND_MAKE_MEM_NOACCESS(addr, size)
Definition memdebug.h:27
#define MemoryContextIsValid(context)
Definition memnodes.h:145
#define AllocSetContextCreate
Definition memutils.h:129
#define ALLOCSET_DEFAULT_SIZES
Definition memutils.h:160
#define AllocHugeSizeIsValid(size)
Definition memutils.h:49
#define AllocSizeIsValid(size)
Definition memutils.h:42
#define MEMORY_CONTEXT_METHODID_MASK
#define PallocAlignedExtraBytes(alignto)
MemoryContextMethodID
@ MCTX_ALIGNED_REDIRECT_ID
#define PointerGetMemoryChunk(p)
static void MemoryChunkSetHdrMask(MemoryChunk *chunk, void *block, Size value, MemoryContextMethodID methodid)
NodeTag
Definition nodes.h:27
static char * errmsg
const void size_t len
char * c
static int fb(int x)
char * s1
char * s2
#define realloc(a, b)
bool stack_is_too_deep(void)
struct MemoryContextCallback * next
Definition palloc.h:51
MemoryContextCallbackFunction func
Definition palloc.h:49
MemoryContext prevchild
Definition memnodes.h:129
MemoryContext firstchild
Definition memnodes.h:128
bool allowInCritSection
Definition memnodes.h:124
const char * ident
Definition memnodes.h:132
MemoryContext parent
Definition memnodes.h:127
MemoryContextCallback * reset_cbs
Definition memnodes.h:133
const MemoryContextMethods * methods
Definition memnodes.h:126
MemoryContext nextchild
Definition memnodes.h:130
const char * name
Definition memnodes.h:131
void(* delete_context)(MemoryContext context)
Definition memnodes.h:86
void(* stats)(MemoryContext context, MemoryStatsPrintFunc printfunc, void *passthru, MemoryContextCounters *totals, bool print_to_stderr)
Definition memnodes.h:102
bool(* is_empty)(MemoryContext context)
Definition memnodes.h:101
void *(* alloc)(MemoryContext context, Size size, int flags)
Definition memnodes.h:66
void(* reset)(MemoryContext context)
Definition memnodes.h:83
struct cursor * next
Definition type.h:149
const char * name

◆ BOGUS_MCTX

#define BOGUS_MCTX (   id)
Value:
[id].free_p = BogusFree, \
[id].realloc = BogusRealloc, \
[id].get_chunk_context = BogusGetChunkContext, \
[id].get_chunk_space = BogusGetChunkSpace

Definition at line 58 of file mcxt.c.

◆ MCXT_METHOD

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

Definition at line 205 of file mcxt.c.

Function Documentation

◆ add_size()

Size add_size ( Size  s1,
Size  s2 
)

Definition at line 1733 of file mcxt.c.

1734{
1735 Size result;
1736
1739 return result;
1740}

References add_size_error(), pg_add_size_overflow(), result, s1, s2, and unlikely.

Referenced by _brin_parallel_estimate_shared(), _bt_parallel_estimate_shared(), _gin_parallel_estimate_shared(), ApplyLauncherShmemRequest(), AsyncShmemRequest(), AutoVacuumShmemRequest(), BackgroundWorkerShmemRequest(), btestimateparallelscan(), BTreeShmemRequest(), CalculateFastPathLockShmemSize(), CalculateShmemSize(), CheckpointerShmemRequest(), CreateAnonymousSegment(), estimate_variable_size(), EstimateClientConnectionInfoSpace(), EstimateComboCIDStateSpace(), EstimateGUCStateSpace(), EstimateLibraryStateSpace(), EstimateParamExecSpace(), EstimateParamListSpace(), EstimateSnapshotSpace(), EstimateTransactionStateSpace(), ExecAggEstimate(), ExecAppendEstimate(), ExecBitmapHeapInstrumentEstimate(), ExecBitmapHeapInstrumentInitDSM(), ExecHashEstimate(), ExecIncrementalSortEstimate(), ExecIndexOnlyScanInstrumentEstimate(), ExecIndexOnlyScanInstrumentInitDSM(), ExecIndexScanInstrumentEstimate(), ExecIndexScanInstrumentInitDSM(), ExecMemoizeEstimate(), ExecSeqScanInstrumentEstimate(), ExecSeqScanInstrumentInitDSM(), ExecSortEstimate(), ExecTidRangeScanInstrumentEstimate(), ExecTidRangeScanInstrumentInitDSM(), expand_planner_arrays(), hash_estimate_size(), index_parallelscan_estimate(), index_parallelscan_initialize(), InitializeShmemGUCs(), MultiXactShmemRequest(), PMSignalShmemRequest(), PredicateLockShmemRequest(), ProcArrayShmemRequest(), ProcGlobalShmemRequest(), ProcSignalShmemRequest(), ReplicationOriginShmemRequest(), ReplicationSlotsShmemRequest(), RequestAddinShmemSpace(), SerializeTransactionState(), SharedInvalShmemRequest(), shm_toc_estimate(), ShmemGetRequestedSize(), StatsShmemSize(), table_parallelscan_estimate(), tuplesort_estimate_shared(), TwoPhaseShmemRequest(), WaitLSNShmemRequest(), WalSndShmemRequest(), and XLOGShmemRequest().

◆ add_size_error()

static pg_noreturn pg_noinline void add_size_error ( Size  s1,
Size  s2 
)
static

Definition at line 1743 of file mcxt.c.

1744{
1745 ereport(ERROR,
1747 errmsg("invalid memory allocation request size %zu + %zu",
1748 s1, s2)));
1749}

References ereport, errcode(), errmsg, ERROR, fb(), s1, and s2.

Referenced by add_size().

◆ BogusFree()

static void BogusFree ( void pointer)
static

Definition at line 309 of file mcxt.c.

310{
311 elog(ERROR, "pfree called with invalid pointer %p (header 0x%016" PRIx64 ")",
312 pointer, GetMemoryChunkHeader(pointer));
313}

References elog, ERROR, fb(), and GetMemoryChunkHeader().

◆ BogusGetChunkContext()

static MemoryContext BogusGetChunkContext ( void pointer)
static

Definition at line 324 of file mcxt.c.

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

References elog, ERROR, fb(), and GetMemoryChunkHeader().

◆ BogusGetChunkSpace()

static Size BogusGetChunkSpace ( void pointer)
static

Definition at line 332 of file mcxt.c.

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

References elog, ERROR, fb(), and GetMemoryChunkHeader().

◆ BogusRealloc()

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

Definition at line 316 of file mcxt.c.

317{
318 elog(ERROR, "repalloc called with invalid pointer %p (header 0x%016" PRIx64 ")",
319 pointer, GetMemoryChunkHeader(pointer));
320 return NULL; /* keep compiler quiet */
321}

References elog, ERROR, fb(), and GetMemoryChunkHeader().

◆ GetMemoryChunkContext()

◆ GetMemoryChunkHeader()

static uint64 GetMemoryChunkHeader ( const void pointer)
inlinestatic

Definition at line 243 of file mcxt.c.

244{
245 uint64 header;
246
247 /* Allow access to the uint64 header */
248 VALGRIND_MAKE_MEM_DEFINED((char *) pointer - sizeof(uint64), sizeof(uint64));
249
250 header = *((const uint64 *) ((const char *) pointer - sizeof(uint64)));
251
252 /* Disallow access to the uint64 header */
253 VALGRIND_MAKE_MEM_NOACCESS((char *) pointer - sizeof(uint64), sizeof(uint64));
254
255 return header;
256}

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 214 of file mcxt.c.

215{
216 uint64 header;
217
218 /*
219 * Try to detect bogus pointers handed to us, poorly though we can.
220 * Presumably, a pointer that isn't MAXALIGNED isn't pointing at an
221 * allocated chunk.
222 */
223 Assert(pointer == (const void *) MAXALIGN(pointer));
224
225 /* Allow access to the uint64 header */
226 VALGRIND_MAKE_MEM_DEFINED((char *) pointer - sizeof(uint64), sizeof(uint64));
227
228 header = *((const uint64 *) ((const char *) pointer - sizeof(uint64)));
229
230 /* Disallow access to the uint64 header */
231 VALGRIND_MAKE_MEM_NOACCESS((char *) pointer - sizeof(uint64), sizeof(uint64));
232
234}

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

◆ GetMemoryChunkSpace()

◆ HandleLogMemoryContextInterrupt()

void HandleLogMemoryContextInterrupt ( void  )

Definition at line 1326 of file mcxt.c.

1327{
1328 InterruptPending = true;
1330 /* latch will be set by procsignal_sigusr1_handler */
1331}

References InterruptPending, and LogMemoryContextPending.

Referenced by procsignal_sigusr1_handler().

◆ MemoryContextAlloc()

void * MemoryContextAlloc ( MemoryContext  context,
Size  size 
)

Definition at line 1235 of file mcxt.c.

1236{
1237 void *ret;
1238
1239 Assert(MemoryContextIsValid(context));
1241
1242 context->isReset = false;
1243
1244 /*
1245 * For efficiency reasons, we purposefully offload the handling of
1246 * allocation failures to the MemoryContextMethods implementation as this
1247 * allows these checks to be performed only when an actual malloc needs to
1248 * be done to request more memory from the OS. Additionally, not having
1249 * to execute any instructions after this call allows the compiler to use
1250 * the sibling call optimization. If you're considering adding code after
1251 * this call, consider making it the responsibility of the 'alloc'
1252 * function instead.
1253 */
1254 ret = context->methods->alloc(context, size, 0);
1255
1256 VALGRIND_MEMPOOL_ALLOC(context, ret, size);
1257
1258 return ret;
1259}

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(), CatalogCacheCreateEntry(), check_foreign_key(), check_primary_key(), compute_array_stats(), copy_byval_expanded_array(), copyScalarSubstructure(), CopySnapshot(), create_drop_transactional_internal(), 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(), GetLockConflicts(), GetPlannerExtensionId(), 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(), InitPgFdwOptions(), InitXLogInsert(), insertStatEntry(), intset_new_internal_node(), intset_new_leaf_node(), inv_open(), libpqsrv_PGresultSetParent(), 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(), PreCommit_Notify(), PrepareClientEncoding(), PrepareSortSupportComparisonShim(), PrepareTempTablespaces(), PushActiveSnapshotWithLevel(), pushJsonbValueScalar(), pushState(), 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(), RestoreSnapshot(), RT_ALLOC_LEAF(), RT_ALLOC_NODE(), setup_background_workers(), shm_mq_receive(), ShmemRequestHashWithOpts(), ShmemRequestStructWithOpts(), SimpleLruRequestWithOpts(), 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 1485 of file mcxt.c.

1487{
1490 void *unaligned;
1491 void *aligned;
1492
1493 /*
1494 * Restrict alignto to ensure that it can fit into the "value" field of
1495 * the redirection MemoryChunk, and that the distance back to the start of
1496 * the unaligned chunk will fit into the space available for that. This
1497 * isn't a limitation in practice, since it wouldn't make much sense to
1498 * waste that much space.
1499 */
1500 Assert(alignto < (128 * 1024 * 1024));
1501
1502 /* ensure alignto is a power of 2 */
1503 Assert((alignto & (alignto - 1)) == 0);
1504
1505 /*
1506 * If the alignment requirements are less than what we already guarantee
1507 * then just use the standard allocation function.
1508 */
1510 return MemoryContextAllocExtended(context, size, flags);
1511
1512 /*
1513 * We implement aligned pointers by simply allocating enough memory for
1514 * the requested size plus the alignment and an additional "redirection"
1515 * MemoryChunk. This additional MemoryChunk is required for operations
1516 * such as pfree when used on the pointer returned by this function. We
1517 * use this redirection MemoryChunk in order to find the pointer to the
1518 * memory that was returned by the MemoryContextAllocExtended call below.
1519 * We do that by "borrowing" the block offset field and instead of using
1520 * that to find the offset into the owning block, we use it to find the
1521 * original allocated address.
1522 *
1523 * Here we must allocate enough extra memory so that we can still align
1524 * the pointer returned by MemoryContextAllocExtended and also have enough
1525 * space for the redirection MemoryChunk. Since allocations will already
1526 * be at least aligned by MAXIMUM_ALIGNOF, we can subtract that amount
1527 * from the allocation size to save a little memory.
1528 */
1530
1531#ifdef MEMORY_CONTEXT_CHECKING
1532 /* ensure there's space for a sentinel byte */
1533 alloc_size += 1;
1534#endif
1535
1536 /*
1537 * Perform the actual allocation, but do not pass down MCXT_ALLOC_ZERO.
1538 * This ensures that wasted bytes beyond the aligned chunk do not become
1539 * DEFINED.
1540 */
1542 flags & ~MCXT_ALLOC_ZERO);
1543
1544 /* compute the aligned pointer */
1545 aligned = (void *) TYPEALIGN(alignto, (char *) unaligned +
1546 sizeof(MemoryChunk));
1547
1549
1550 /*
1551 * We set the redirect MemoryChunk so that the block offset calculation is
1552 * used to point back to the 'unaligned' allocated chunk. This allows us
1553 * to use MemoryChunkGetBlock() to find the unaligned chunk when we need
1554 * to perform operations such as pfree() and repalloc().
1555 *
1556 * We store 'alignto' in the MemoryChunk's 'value' so that we know what
1557 * the alignment was set to should we ever be asked to realloc this
1558 * pointer.
1559 */
1562
1563 /* double check we produced a correctly aligned pointer */
1564 Assert((void *) TYPEALIGN(alignto, aligned) == aligned);
1565
1566#ifdef MEMORY_CONTEXT_CHECKING
1567 alignedchunk->requested_size = size;
1568 /* set mark to catch clobber of "unused" space */
1569 set_sentinel(aligned, size);
1570#endif
1571
1572 /*
1573 * MemoryContextAllocExtended marked the whole unaligned chunk as a
1574 * vchunk. Undo that, instead making just the aligned chunk be a vchunk.
1575 * This prevents Valgrind from complaining that the vchunk is possibly
1576 * leaked, since only pointers to the aligned chunk will exist.
1577 *
1578 * After these calls, the aligned chunk will be marked UNDEFINED, and all
1579 * the rest of the unaligned chunk (the redirection chunk header, the
1580 * padding bytes before it, and any wasted trailing bytes) will be marked
1581 * NOACCESS, which is what we want.
1582 */
1584 VALGRIND_MEMPOOL_ALLOC(context, aligned, size);
1585
1586 /* Now zero (and make DEFINED) just the aligned chunk, if requested */
1587 if ((flags & MCXT_ALLOC_ZERO) != 0)
1588 MemSetAligned(aligned, 0, size);
1589
1590 return aligned;
1591}

References Assert, fb(), MCTX_ALIGNED_REDIRECT_ID, MCXT_ALLOC_ZERO, MemoryChunkSetHdrMask(), MemoryContextAllocExtended(), MemSetAligned, PallocAlignedExtraBytes, PointerGetMemoryChunk, TYPEALIGN, unlikely, VALGRIND_MEMPOOL_ALLOC, and VALGRIND_MEMPOOL_FREE.

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

◆ MemoryContextAllocationFailure()

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

Definition at line 1201 of file mcxt.c.

1202{
1203 if ((flags & MCXT_ALLOC_NO_OOM) == 0)
1204 {
1205 if (TopMemoryContext)
1207 ereport(ERROR,
1209 errmsg("out of memory"),
1210 errdetail("Failed on request of size %zu in memory context \"%s\".",
1211 size, context->name)));
1212 }
1213 return NULL;
1214}

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

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

◆ MemoryContextAllocExtended()

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

Definition at line 1292 of file mcxt.c.

1293{
1294 void *ret;
1295
1296 Assert(MemoryContextIsValid(context));
1298
1299 if (!((flags & MCXT_ALLOC_HUGE) != 0 ? AllocHugeSizeIsValid(size) :
1300 AllocSizeIsValid(size)))
1301 elog(ERROR, "invalid memory alloc request size %zu", size);
1302
1303 context->isReset = false;
1304
1305 ret = context->methods->alloc(context, size, flags);
1306 if (unlikely(ret == NULL))
1307 return NULL;
1308
1309 VALGRIND_MEMPOOL_ALLOC(context, ret, size);
1310
1311 if ((flags & MCXT_ALLOC_ZERO) != 0)
1312 MemSetAligned(ret, 0, size);
1313
1314 return ret;
1315}

References MemoryContextMethods::alloc, AllocHugeSizeIsValid, AllocSizeIsValid, Assert, AssertNotInCriticalSection, elog, ERROR, fb(), 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(), libpqsrv_PQwrap(), MemoryContextAllocAligned(), pagetable_allocate(), and RegisterBackgroundWorker().

◆ MemoryContextAllocHuge()

void * MemoryContextAllocHuge ( MemoryContext  context,
Size  size 
)

Definition at line 1854 of file mcxt.c.

1855{
1856 void *ret;
1857
1858 Assert(MemoryContextIsValid(context));
1860
1861 context->isReset = false;
1862
1863 /*
1864 * For efficiency reasons, we purposefully offload the handling of
1865 * allocation failures to the MemoryContextMethods implementation as this
1866 * allows these checks to be performed only when an actual malloc needs to
1867 * be done to request more memory from the OS. Additionally, not having
1868 * to execute any instructions after this call allows the compiler to use
1869 * the sibling call optimization. If you're considering adding code after
1870 * this call, consider making it the responsibility of the 'alloc'
1871 * function instead.
1872 */
1873 ret = context->methods->alloc(context, size, MCXT_ALLOC_HUGE);
1874
1875 VALGRIND_MEMPOOL_ALLOC(context, ret, size);
1876
1877 return ret;
1878}

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_os_pages_internal(), pg_do_encoding_conversion(), and pgstat_read_current_status().

◆ MemoryContextAllocZero()

void * MemoryContextAllocZero ( MemoryContext  context,
Size  size 
)

Definition at line 1269 of file mcxt.c.

1270{
1271 void *ret;
1272
1273 Assert(MemoryContextIsValid(context));
1275
1276 context->isReset = false;
1277
1278 ret = context->methods->alloc(context, size, 0);
1279
1280 VALGRIND_MEMPOOL_ALLOC(context, ret, size);
1281
1282 MemSetAligned(ret, 0, size);
1283
1284 return ret;
1285}

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(), get_function_sibling_type(), gistAllocateNewPageBuffer(), index_form_tuple_context(), init_MultiFuncCall(), init_sql_fcache(), initArrayResultArr(), InitializeSession(), InitWalSender(), InitXLogInsert(), json_populate_type(), jsonb_agg_transfn_worker(), jsonb_object_agg_transfn_worker(), llvm_create_context(), load_relcache_init_file(), LookupOpclassInfo(), 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(), SetPlannerGlobalExtensionState(), SetPlannerInfoExtensionState(), SetRelOptInfoExtensionState(), SnapBuildBuildSnapshot(), SnapBuildRestoreSnapshot(), spgGetCache(), sts_puttuple(), ts_accum(), ts_stat_sql(), and WinGetPartitionLocalMemory().

◆ MemoryContextAllowInCriticalSection()

void MemoryContextAllowInCriticalSection ( MemoryContext  context,
bool  allow 
)

Definition at line 746 of file mcxt.c.

747{
749
750 context->allowInCritSection = allow;
751}

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

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

◆ MemoryContextCallResetCallbacks()

static void MemoryContextCallResetCallbacks ( MemoryContext  context)
static

Definition at line 637 of file mcxt.c.

638{
640
641 /*
642 * We pop each callback from the list before calling. That way, if an
643 * error occurs inside the callback, we won't try to call it a second time
644 * in the likely event that we reset or delete the context later.
645 */
646 while ((cb = context->reset_cbs) != NULL)
647 {
648 context->reset_cbs = cb->next;
649 cb->func(cb->arg);
650 }
651}

References MemoryContextCallback::arg, fb(), 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 1152 of file mcxt.c.

1157{
1158 /* Creating new memory contexts is not allowed in a critical section */
1160
1161 /* Validate parent, to help prevent crazy context linkages */
1162 Assert(parent == NULL || MemoryContextIsValid(parent));
1163 Assert(node != parent);
1164
1165 /* Initialize all standard fields of memory context header */
1166 node->type = tag;
1167 node->isReset = true;
1168 node->methods = &mcxt_methods[method_id];
1169 node->parent = parent;
1170 node->firstchild = NULL;
1171 node->mem_allocated = 0;
1172 node->prevchild = NULL;
1173 node->name = name;
1174 node->ident = NULL;
1175 node->reset_cbs = NULL;
1176
1177 /* OK to link node into context tree */
1178 if (parent)
1179 {
1180 node->nextchild = parent->firstchild;
1181 if (parent->firstchild != NULL)
1182 parent->firstchild->prevchild = node;
1183 parent->firstchild = node;
1184 /* inherit allowInCritSection flag from parent */
1185 node->allowInCritSection = parent->allowInCritSection;
1186 }
1187 else
1188 {
1189 node->nextchild = NULL;
1190 node->allowInCritSection = false;
1191 }
1192}

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

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

◆ MemoryContextDelete()

void MemoryContextDelete ( MemoryContext  context)

Definition at line 475 of file mcxt.c.

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

References Assert, fb(), 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(), be_tls_init(), blbuild(), blinsert(), brin_free_desc(), brin_minmax_multi_union(), bringetbitmap(), brininsert(), bt_check_every_level(), btendscan(), btree_xlog_cleanup(), btvacuumscan(), BuildParamLogString(), BuildRelationExtStatistics(), CloneRowTriggersToPartition(), 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(), ExecRepack(), 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_function_in_from(), libpqrcv_processTuples(), load_hba(), load_ident(), load_tzoffsets(), makeArrayResultArr(), makeMdArrayResult(), materializeQueryResult(), maybe_reread_subscription(), MemoryContextDeleteChildren(), NIFinishBuild(), pg_backup_stop(), pg_decode_shutdown(), pg_get_wal_block_info(), pg_plan_advice_advice_check_hook(), pgsa_read_from_disk(), pgsa_write_to_disk(), 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(), ReplSlotSyncWorkerMain(), ResetUnloggedRelations(), RevalidateCachedQuery(), ri_FastPathTeardown(), 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(), SyncReplicationSlots(), SysLoggerMain(), test_pattern(), TidStoreDestroy(), tokenize_auth_file(), tuplesort_end(), tuplestore_end(), union_tuples(), UploadManifest(), and validateForeignKeyConstraint().

◆ MemoryContextDeleteChildren()

void MemoryContextDeleteChildren ( MemoryContext  context)

Definition at line 558 of file mcxt.c.

559{
561
562 /*
563 * MemoryContextDelete will delink the child from me, so just iterate as
564 * long as there is a child.
565 */
566 while (context->firstchild != NULL)
568}

References Assert, fb(), 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 517 of file mcxt.c.

518{
520 /* We had better not be deleting TopMemoryContext ... */
521 Assert(context != TopMemoryContext);
522 /* And not CurrentMemoryContext, either */
523 Assert(context != CurrentMemoryContext);
524 /* All the children should've been deleted already */
525 Assert(context->firstchild == NULL);
526
527 /*
528 * It's not entirely clear whether 'tis better to do this before or after
529 * delinking the context; but an error in a callback will likely result in
530 * leaking the whole context (if it's not a root context) if we do it
531 * after, so let's do it before.
532 */
534
535 /*
536 * We delink the context from its parent before deleting it, so that if
537 * there's an error we won't have deleted/busted contexts still attached
538 * to the context tree. Better a leak than a crash.
539 */
541
542 /*
543 * Also reset the context's ident pointer, in case it points into the
544 * context. This would only matter if someone tries to get stats on the
545 * (already unlinked) context, which is unlikely, but let's be safe.
546 */
547 context->ident = NULL;
548
549 context->methods->delete_context(context);
550}

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

Referenced by MemoryContextDelete().

◆ MemoryContextGetParent()

MemoryContext MemoryContextGetParent ( MemoryContext  context)

◆ MemoryContextInit()

void MemoryContextInit ( void  )

Definition at line 362 of file mcxt.c.

363{
365
366 /*
367 * First, initialize TopMemoryContext, which is the parent of all others.
368 */
370 "TopMemoryContext",
372
373 /*
374 * Not having any other place to point CurrentMemoryContext, make it point
375 * to TopMemoryContext. Caller should change this soon!
376 */
378
379 /*
380 * Initialize ErrorContext as an AllocSetContext with slow growth rate ---
381 * we don't really expect much to be allocated in it. More to the point,
382 * require it to contain at least 8K at all times. This is the only case
383 * where retained memory in a context is *essential* --- we want to be
384 * sure ErrorContext still has some memory even if we've run out
385 * elsewhere! Also, allow allocations in ErrorContext within a critical
386 * section. Otherwise a PANIC will cause an assertion failure in the error
387 * reporting code, before printing out the real cause of the failure.
388 *
389 * This should be the last step in this function, as elog.c assumes memory
390 * management works once ErrorContext is non-null.
391 */
393 "ErrorContext",
394 8 * 1024,
395 8 * 1024,
396 8 * 1024);
398}

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

Referenced by main().

◆ MemoryContextIsEmpty()

bool MemoryContextIsEmpty ( MemoryContext  context)

Definition at line 795 of file mcxt.c.

796{
798
799 /*
800 * For now, we consider a memory context nonempty if it has any children;
801 * perhaps this should be changed later.
802 */
803 if (context->firstchild != NULL)
804 return false;
805 /* Otherwise use the type-specific inquiry */
806 return context->methods->is_empty(context);
807}

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

Referenced by AtSubCommit_Memory().

◆ MemoryContextMemAllocated()

Size MemoryContextMemAllocated ( MemoryContext  context,
bool  recurse 
)

Definition at line 814 of file mcxt.c.

815{
816 Size total = context->mem_allocated;
817
819
820 if (recurse)
821 {
822 for (MemoryContext curr = context->firstchild;
823 curr != NULL;
825 {
826 total += curr->mem_allocated;
827 }
828 }
829
830 return total;
831}

References Assert, fb(), 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 838 of file mcxt.c.

840{
842
843 memset(consumed, 0, sizeof(*consumed));
844
845 /* Examine the context itself */
846 context->methods->stats(context, NULL, NULL, consumed, false);
847
848 /* Examine children, using iteration not recursion */
849 for (MemoryContext curr = context->firstchild;
850 curr != NULL;
852 {
853 curr->methods->stats(curr, NULL, NULL, consumed, false);
854 }
855}

References Assert, fb(), 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 585 of file mcxt.c.

587{
589
590 /* Push onto head so this will be called before older registrants. */
591 cb->next = context->reset_cbs;
592 context->reset_cbs = cb;
593 /* Mark the context as non-reset (it probably is already). */
594 context->isReset = false;
595}

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

Referenced by be_tls_init(), expanded_record_fetch_tupdesc(), init_sql_fcache(), InitDomainConstraintRef(), libpqsrv_PGresultSetParent(), libpqsrv_PQwrap(), load_validator_library(), make_expanded_record_from_exprecord(), make_expanded_record_from_tupdesc(), make_expanded_record_from_typeid(), pgoutput_startup(), and PLy_exec_function().

◆ MemoryContextReset()

void MemoryContextReset ( MemoryContext  context)

Definition at line 406 of file mcxt.c.

407{
409
410 /* save a function call in common case where there are no children */
411 if (context->firstchild != NULL)
413
414 /* save a function call if no pallocs since startup or last reset */
415 if (!context->isReset)
416 MemoryContextResetOnly(context);
417}

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

Referenced by _brin_parallel_merge(), _bt_preprocess_array_keys(), _gin_parallel_merge(), _SPI_end_call(), AfterTriggerExecute(), 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(), 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(), errfinish(), 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(), 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(), ProcessRepackMessages(), release_partition(), repack_store_change(), ReScanExprContext(), resetSpGistScanOpaque(), ResetTupleHashTable(), ri_FastPathBatchFlush(), RT_FREE(), scanPendingInsert(), sepgsql_avc_reset(), serializeAnalyzeReceive(), spcache_init(), spg_redo(), spginsert(), spgistBuildCallback(), spgWalk(), startScanKey(), statext_dependencies_build(), storeRow(), stream_stop_internal(), SyncReplicationSlots(), tfuncFetchRows(), tfuncLoadRows(), tuplesort_free(), tuplestore_clear(), validateForeignKeyConstraint(), WalSummarizerMain(), and WalWriterMain().

◆ MemoryContextResetChildren()

void MemoryContextResetChildren ( MemoryContext  context)

Definition at line 454 of file mcxt.c.

455{
457
458 for (MemoryContext curr = context->firstchild;
459 curr != NULL;
461 {
463 }
464}

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

◆ MemoryContextResetOnly()

void MemoryContextResetOnly ( MemoryContext  context)

Definition at line 425 of file mcxt.c.

426{
428
429 /* Nothing to do if no pallocs since startup or last reset */
430 if (!context->isReset)
431 {
433
434 /*
435 * If context->ident points into the context's memory, it will become
436 * a dangling pointer. We could prevent that by setting it to NULL
437 * here, but that would break valid coding patterns that keep the
438 * ident elsewhere, e.g. in a parent context. So for now we assume
439 * the programmer got it right.
440 */
441
442 context->methods->reset(context);
443 context->isReset = true;
444 }
445}

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

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

◆ MemoryContextSetIdentifier()

◆ MemoryContextSetParent()

void MemoryContextSetParent ( MemoryContext  context,
MemoryContext  new_parent 
)

Definition at line 689 of file mcxt.c.

690{
692 Assert(context != new_parent);
693
694 /* Fast path if it's got correct parent already */
695 if (new_parent == context->parent)
696 return;
697
698 /* Delink from existing parent, if any */
699 if (context->parent)
700 {
701 MemoryContext parent = context->parent;
702
703 if (context->prevchild != NULL)
704 context->prevchild->nextchild = context->nextchild;
705 else
706 {
707 Assert(parent->firstchild == context);
708 parent->firstchild = context->nextchild;
709 }
710
711 if (context->nextchild != NULL)
712 context->nextchild->prevchild = context->prevchild;
713 }
714
715 /* And relink */
716 if (new_parent)
717 {
719 context->parent = new_parent;
720 context->prevchild = NULL;
721 context->nextchild = new_parent->firstchild;
722 if (new_parent->firstchild != NULL)
723 new_parent->firstchild->prevchild = context;
724 new_parent->firstchild = context;
725 }
726 else
727 {
728 context->parent = NULL;
729 context->prevchild = NULL;
730 context->nextchild = NULL;
731 }
732}

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

Referenced by _SPI_save_plan(), CachedPlanSetParentContext(), CompleteCachedPlan(), exec_parse_message(), GetCachedExpression(), GetCachedPlan(), InitializeLogRepWorker(), load_domaintype_info(), maybe_reread_subscription(), MemoryContextDeleteOnly(), plpgsql_compile_callback(), 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 1222 of file mcxt.c.

1223{
1224 elog(ERROR, "invalid memory alloc request size %zu", size);
1225}

References elog, and ERROR.

Referenced by MemoryContextCheckSize().

◆ MemoryContextStats()

void MemoryContextStats ( MemoryContext  context)

Definition at line 866 of file mcxt.c.

867{
868 /* Hard-wired limits are usually good enough */
869 MemoryContextStatsDetail(context, 100, 100, true);
870}

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 881 of file mcxt.c.

884{
886
887 memset(&grand_totals, 0, sizeof(grand_totals));
888
891
892 if (print_to_stderr)
894 "Grand total: %zu bytes in %zu blocks; %zu free (%zu chunks); %zu used\n",
895 grand_totals.totalspace, grand_totals.nblocks,
896 grand_totals.freespace, grand_totals.freechunks,
897 grand_totals.totalspace - grand_totals.freespace);
898 else
899 {
900 /*
901 * Use LOG_SERVER_ONLY to prevent the memory contexts from being sent
902 * to the connected client.
903 *
904 * We don't buffer the information about all memory contexts in a
905 * backend into StringInfo and log it as one message. That would
906 * require the buffer to be enlarged, risking an OOM as there could be
907 * a large number of memory contexts in a backend. Instead, we log
908 * one message per memory context.
909 */
911 (errhidestmt(true),
912 errhidecontext(true),
913 errmsg_internal("Grand total: %zu bytes in %zu blocks; %zu free (%zu chunks); %zu used",
914 grand_totals.totalspace, grand_totals.nblocks,
915 grand_totals.freespace, grand_totals.freechunks,
916 grand_totals.totalspace - grand_totals.freespace)));
917 }
918}

References ereport, errhidecontext(), errhidestmt(), errmsg_internal(), fb(), fprintf, LOG_SERVER_ONLY, and MemoryContextStatsInternal().

Referenced by MemoryContextStats(), and ProcessLogMemoryContextInterrupt().

◆ MemoryContextStatsInternal()

static void MemoryContextStatsInternal ( MemoryContext  context,
int  level,
int  max_level,
int  max_children,
MemoryContextCounters totals,
bool  print_to_stderr 
)
static

Definition at line 928 of file mcxt.c.

932{
933 MemoryContext child;
934 int ichild;
935
937
938 /* Examine the context itself */
939 context->methods->stats(context,
941 &level,
943
944 /*
945 * Examine children.
946 *
947 * If we are past the recursion depth limit or already running low on
948 * stack, do not print them explicitly but just summarize them. Similarly,
949 * if there are more than max_children of them, we do not print the rest
950 * explicitly, but just summarize them.
951 */
952 child = context->firstchild;
953 ichild = 0;
954 if (level <= max_level && !stack_is_too_deep())
955 {
956 for (; child != NULL && ichild < max_children;
957 child = child->nextchild, ichild++)
958 {
959 MemoryContextStatsInternal(child, level + 1,
961 totals,
963 }
964 }
965
966 if (child != NULL)
967 {
968 /* Summarize the rest of the children, avoiding recursion. */
970
971 memset(&local_totals, 0, sizeof(local_totals));
972
973 ichild = 0;
974 while (child != NULL)
975 {
976 child->methods->stats(child, NULL, NULL, &local_totals, false);
977 ichild++;
978 child = MemoryContextTraverseNext(child, context);
979 }
980
981 if (print_to_stderr)
982 {
983 for (int i = 0; i < level; i++)
984 fprintf(stderr, " ");
986 "%d more child contexts containing %zu total in %zu blocks; %zu free (%zu chunks); %zu used\n",
987 ichild,
988 local_totals.totalspace,
989 local_totals.nblocks,
990 local_totals.freespace,
991 local_totals.freechunks,
992 local_totals.totalspace - local_totals.freespace);
993 }
994 else
996 (errhidestmt(true),
997 errhidecontext(true),
998 errmsg_internal("level: %d; %d more child contexts containing %zu total in %zu blocks; %zu free (%zu chunks); %zu used",
999 level,
1000 ichild,
1001 local_totals.totalspace,
1002 local_totals.nblocks,
1003 local_totals.freespace,
1004 local_totals.freechunks,
1005 local_totals.totalspace - local_totals.freespace)));
1006
1007 if (totals)
1008 {
1009 totals->nblocks += local_totals.nblocks;
1010 totals->freechunks += local_totals.freechunks;
1011 totals->totalspace += local_totals.totalspace;
1012 totals->freespace += local_totals.freespace;
1013 }
1014 }
1015}

References Assert, ereport, errhidecontext(), errhidestmt(), errmsg_internal(), fb(), MemoryContextData::firstchild, fprintf, i, LOG_SERVER_ONLY, MemoryContextIsValid, MemoryContextStatsInternal(), MemoryContextStatsPrint(), MemoryContextTraverseNext(), MemoryContextData::methods, MemoryContextData::nextchild, stack_is_too_deep(), and MemoryContextMethods::stats.

Referenced by MemoryContextStatsDetail(), and MemoryContextStatsInternal().

◆ MemoryContextStatsPrint()

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

Definition at line 1025 of file mcxt.c.

1028{
1029 int level = *(int *) passthru;
1030 const char *name = context->name;
1031 const char *ident = context->ident;
1032 char truncated_ident[110];
1033 int i;
1034
1035 /*
1036 * It seems preferable to label dynahash contexts with just the hash table
1037 * name. Those are already unique enough, so the "dynahash" part isn't
1038 * very helpful, and this way is more consistent with pre-v11 practice.
1039 */
1040 if (ident && strcmp(name, "dynahash") == 0)
1041 {
1042 name = ident;
1043 ident = NULL;
1044 }
1045
1046 truncated_ident[0] = '\0';
1047
1048 if (ident)
1049 {
1050 /*
1051 * Some contexts may have very long identifiers (e.g., SQL queries).
1052 * Arbitrarily truncate at 100 bytes, but be careful not to break
1053 * multibyte characters. Also, replace ASCII control characters, such
1054 * as newlines, with spaces.
1055 */
1056 int idlen = strlen(ident);
1057 bool truncated = false;
1058
1059 strcpy(truncated_ident, ": ");
1061
1062 if (idlen > 100)
1063 {
1064 idlen = pg_mbcliplen(ident, idlen, 100);
1065 truncated = true;
1066 }
1067
1068 while (idlen-- > 0)
1069 {
1070 unsigned char c = *ident++;
1071
1072 if (c < ' ')
1073 c = ' ';
1074 truncated_ident[i++] = c;
1075 }
1076 truncated_ident[i] = '\0';
1077
1078 if (truncated)
1079 strcat(truncated_ident, "...");
1080 }
1081
1082 if (print_to_stderr)
1083 {
1084 for (i = 1; i < level; i++)
1085 fprintf(stderr, " ");
1087 }
1088 else
1090 (errhidestmt(true),
1091 errhidecontext(true),
1092 errmsg_internal("level: %d; %s: %s%s",
1093 level, name, stats_string, truncated_ident)));
1094}

References ereport, errhidecontext(), errhidestmt(), errmsg_internal(), fb(), 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 280 of file mcxt.c.

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

References fb(), MemoryContextData::firstchild, MemoryContextData::nextchild, and MemoryContextData::parent.

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

◆ MemoryContextUnregisterResetCallback()

void MemoryContextUnregisterResetCallback ( MemoryContext  context,
MemoryContextCallback cb 
)

Definition at line 610 of file mcxt.c.

612{
614 *cur;
615
617
618 for (prev = NULL, cur = context->reset_cbs; cur != NULL;
619 prev = cur, cur = cur->next)
620 {
621 if (cur != cb)
622 continue;
623 if (prev)
624 prev->next = cur->next;
625 else
626 context->reset_cbs = cur->next;
627 return;
628 }
629 Assert(false);
630}

References Assert, cur, fb(), MemoryContextIsValid, MemoryContextCallback::next, cursor::next, and MemoryContextData::reset_cbs.

Referenced by libpqsrv_PGresultSetParent(), and libpqsrv_PQclear().

◆ mul_size()

Size mul_size ( Size  s1,
Size  s2 
)

Definition at line 1752 of file mcxt.c.

1753{
1754 Size result;
1755
1758 return result;
1759}

References mul_size_error(), pg_mul_size_overflow(), result, s1, s2, and unlikely.

Referenced by _brin_begin_parallel(), _bt_begin_parallel(), _gin_begin_parallel(), AioBackendShmemSize(), AioHandleDataShmemSize(), AioHandleIOVShmemSize(), AioHandleShmemSize(), ApplyLauncherShmemRequest(), AsyncShmemRequest(), AutoVacuumShmemRequest(), BackendStatusShmemAttach(), BackendStatusShmemRequest(), BackgroundWorkerShmemRequest(), BTreeShmemRequest(), CalculateFastPathLockShmemSize(), CheckpointerShmemRequest(), datetime_to_char_body(), EstimateComboCIDStateSpace(), EstimatePendingSyncsSpace(), EstimateReindexStateSpace(), EstimateSnapshotSpace(), EstimateTransactionStateSpace(), ExecAggEstimate(), ExecBitmapHeapInstrumentEstimate(), ExecBitmapHeapInstrumentInitDSM(), ExecHashEstimate(), ExecIncrementalSortEstimate(), ExecIndexOnlyScanInstrumentEstimate(), ExecIndexOnlyScanInstrumentInitDSM(), ExecIndexScanInstrumentEstimate(), ExecIndexScanInstrumentInitDSM(), ExecInitParallelPlan(), ExecMemoizeEstimate(), ExecParallelRetrieveInstrumentation(), ExecParallelRetrieveJitInstrumentation(), ExecParallelSetupTupleQueues(), ExecSeqScanInstrumentEstimate(), ExecSeqScanInstrumentInitDSM(), ExecSortEstimate(), ExecTidRangeScanInstrumentEstimate(), ExecTidRangeScanInstrumentInitDSM(), hash_estimate_size(), InitializeParallelDSM(), MultiXactShmemRequest(), parallel_vacuum_init(), PGSemaphoreShmemRequest(), PMSignalShmemRequest(), PredicateLockShmemRequest(), ProcArrayShmemRequest(), ProcGlobalShmemRequest(), ProcSignalShmemRequest(), ReplicationOriginShmemRequest(), ReplicationSlotsShmemRequest(), SharedInvalShmemRequest(), shm_toc_estimate(), tuplesort_estimate_shared(), TwoPhaseShmemRequest(), WaitLSNShmemRequest(), WalSndShmemRequest(), and XLOGShmemRequest().

◆ mul_size_error()

static pg_noreturn pg_noinline void mul_size_error ( Size  s1,
Size  s2 
)
static

Definition at line 1762 of file mcxt.c.

1763{
1764 ereport(ERROR,
1766 errmsg("invalid memory allocation request size %zu * %zu",
1767 s1, s2)));
1768}

References ereport, errcode(), errmsg, ERROR, fb(), s1, and s2.

Referenced by mul_size(), palloc0_mul(), palloc_mul(), palloc_mul_extended(), repalloc_mul(), and repalloc_mul_extended().

◆ palloc()

void * palloc ( Size  size)

Definition at line 1390 of file mcxt.c.

1391{
1392 /* duplicates MemoryContextAlloc to avoid increased overhead */
1393 void *ret;
1395
1396 Assert(MemoryContextIsValid(context));
1398
1399 context->isReset = false;
1400
1401 /*
1402 * For efficiency reasons, we purposefully offload the handling of
1403 * allocation failures to the MemoryContextMethods implementation as this
1404 * allows these checks to be performed only when an actual malloc needs to
1405 * be done to request more memory from the OS. Additionally, not having
1406 * to execute any instructions after this call allows the compiler to use
1407 * the sibling call optimization. If you're considering adding code after
1408 * this call, consider making it the responsibility of the 'alloc'
1409 * function instead.
1410 */
1411 ret = context->methods->alloc(context, size, 0);
1412 /* We expect OOM to be handled by the alloc function */
1413 Assert(ret != NULL);
1414 VALGRIND_MEMPOOL_ALLOC(context, ret, size);
1415
1416 return ret;
1417}

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

Referenced by _bt_bottomupdel_pass(), _bt_dedup_pass(), _bt_delitems_delete_check(), _bt_delitems_update(), _bt_load(), _bt_mkscankey(), _bt_newlevel(), _bt_preprocess_array_keys(), _bt_simpledel_pass(), _bt_unmark_keys(), _intbig_alloc(), _ltree_picksplit(), _metaphone(), AbsorbSyncRequests(), accum_sum_copy(), accumArrayResultArr(), aclitemout(), aclmembers(), acquire_inherited_sample_rows(), add_exact_object_address_extra(), add_reloption(), addWrd(), adjust_appendrel_attrs_mutator(), allocate_recordbuf(), allocate_reloption(), AllocateRelationDesc(), AlterSubscription_refresh(), anybit_typmodout(), anychar_typmodout(), appendJSONKeyValueFmt(), AppendStringCommandOption(), apply_spooled_messages(), array_agg_array_combine(), array_agg_array_deserialize(), array_create_iterator(), array_map(), array_out(), array_recv(), array_replace_internal(), array_set_element(), ArrayGetIntegerTypmods(), Async_Notify(), autoinc(), bbsink_copystream_begin_backup(), be_loread(), be_tls_get_certificate_hash(), 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(), bms_copy(), boolout(), bottomup_sort_and_shrink(), box_poly(), bpchar(), bpchar_input(), bqarr_in(), brin_build_desc(), brin_copy_tuple(), brin_minmax_multi_distance_inet(), brin_page_items(), brin_range_deserialize(), brin_revmap_data(), bringetbitmap(), bt_normalize_tuple(), bt_page_items_internal(), bt_page_print_tuples(), btbeginscan(), btree_xlog_dedup(), btree_xlog_updates(), btreevacuumposting(), btrescan(), BufferSync(), build_column_frequencies(), build_distinct_groups(), build_function_result_tupdesc_d(), build_mvndistinct(), build_pertrans_for_aggref(), build_server_final_message(), build_server_first_message(), build_tlist_index(), build_tlist_index_other_vars(), build_tuplestore_recursively(), BuildTupleFromCStrings(), bytea_catenate(), bytea_reverse(), bytea_string_agg_finalfn(), byteain(), byteaout(), bytearecv(), catenate_stringinfo_string(), char_bpchar(), char_text(), charout(), check_foreign_key(), check_ident_usermap(), check_primary_key(), check_temp_tablespaces(), checkSharedDependencies(), chr(), cidout(), cleanup_tsquery_stopwords(), collect_corrupt_items(), collectPartitionIndexExtDeps(), collectTSQueryValues(), compute_array_stats(), compute_distinct_stats(), compute_expr_stats(), compute_index_stats(), compute_range_stats(), compute_scalar_stats(), compute_tsvector_stats(), computeLeafRecompressWALData(), concat_text(), consider_groupingsets_paths(), construct_connection_params(), convert_prep_stmt_params(), convert_requires_to_datum(), convert_string_datum(), copy_file(), copy_pathtarget(), copy_plpgsql_datums(), CopyFromTextLikeStart(), CopyIndexTuple(), CopyLimitPrintoutLength(), copytext(), CopyTriggerDesc(), core_yyalloc(), core_yyrealloc(), count_usable_fds(), create_hash_bounds(), create_limit_plan(), create_list_bounds(), create_memoize_plan(), create_mergejoin_plan(), create_range_bounds(), create_secmsg(), CreateConstraintEntry(), CreateFunction(), CreatePartitionPruneState(), createPostingTree(), CreateTemplateTupleDesc(), CreateTriggerFiringOn(), CreateTupleDescCopyConstr(), cstring_to_text_with_len(), cube_recv(), current_database(), current_schemas(), dataBeginPlaceToPageLeaf(), datetime_to_char_body(), datumCopy(), datumRestore(), datumSerialize(), debackslash(), decodePageSplitRecord(), DeescapeQuotedString(), deparse_lquery(), deparse_ltree(), deserialize_deflist(), detoast_attr(), detoast_attr_slice(), detoast_external_attr(), disassembleLeaf(), DiscreteKnapsack(), div_var(), do_analyze_rel(), dobyteatrim(), DoCopyTo(), doPickSplit(), dotrim(), double_to_shortest_decimal(), downcase_convert(), downcase_identifier(), DropRelationsAllBuffers(), duplicate_numeric(), encrypt_password(), entry_dealloc(), enum_range_internal(), ExecAggRetrieveInstrumentation(), ExecBitmapHeapRetrieveInstrumentation(), ExecBitmapIndexScanRetrieveInstrumentation(), ExecEvalArrayExpr(), ExecGather(), ExecGatherMerge(), ExecGetJsonValueItemString(), ExecHashJoinGetSavedTuple(), ExecHashRetrieveInstrumentation(), ExecIncrementalSortRetrieveInstrumentation(), ExecIndexBuildScanKeys(), ExecIndexOnlyScanRetrieveInstrumentation(), ExecIndexScanRetrieveInstrumentation(), ExecInitAgg(), ExecInitAppend(), ExecInitExprRec(), ExecInitIndexScan(), ExecInitJunkFilter(), ExecInitMemoize(), ExecInitPartitionDispatchInfo(), ExecInitSubPlan(), ExecInitValuesScan(), ExecMakeTableFunctionResult(), ExecMemoizeRetrieveInstrumentation(), ExecParallelCreateReaders(), ExecParallelRetrieveInstrumentation(), ExecParallelSetupTupleQueues(), ExecSeqScanRetrieveInstrumentation(), ExecSortRetrieveInstrumentation(), ExecTidRangeScanRetrieveInstrumentation(), execTuplesHashPrepare(), execTuplesMatchPrepare(), ExecuteTruncateGuts(), ExplainCreateWorkersState(), export_initial_snapshot(), extract_rollup_sets(), fallbackSplit(), file_acquire_sample_rows(), find_hash_columns(), find_in_path(), find_inheritance_children_extended(), FinishWalRecovery(), float4_to_char(), float4out(), float8_to_char(), float8out_internal(), float_to_shortest_decimal(), format_operator_extended(), format_procedure_extended(), formTextDatum(), formTextDatum(), FuncnameGetCandidates(), g_cube_picksplit(), g_int_picksplit(), 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_union(), gbt_int2_union(), gbt_int4_union(), gbt_int8_union(), gbt_intv_compress(), gbt_intv_union(), gbt_num_picksplit(), gbt_oid_union(), gbt_time_union(), gbt_ts_union(), gbt_uuid_compress(), gbt_uuid_union(), gbt_var_key_from_datum(), gbt_var_picksplit(), gen_random_uuid(), generate_normalized_query(), generate_restrict_key(), generate_trgm_only(), generate_uuidv7(), generate_wildcard_trgm(), generateHeadline(), genericPickSplit(), get_attribute_options(), get_environ(), get_extension_aux_control_filename(), get_extension_control_directories(), get_extension_script_filename(), get_func_arg_info(), get_func_input_arg_names(), get_func_signature(), get_func_trftypes(), get_initial_snapshot(), get_name_for_var_field(), get_page_from_raw(), get_permutation(), get_raw_page_internal(), get_str_from_var(), get_str_from_var_sci(), get_tsearch_config_filename(), get_val(), GetMultiXactIdMembers(), GetPermutation(), GetRunningTransactionLocks(), GetWALBlockInfo(), ghstore_alloc(), ghstore_picksplit(), gin_extract_hstore(), gin_extract_hstore_query(), gin_leafpage_items(), GinBufferStoreTuple(), ginCompressPostingList(), GinDataLeafPageGetItems(), GinFormInteriorTuple(), ginHeapTupleFastInsert(), ginMergeItemPointers(), ginNewScanKey(), ginPostingListDecodeAllSegments(), ginReadTuple(), ginReadTupleWithoutState(), ginRedoRecompress(), ginVacuumPostingTreeLeaf(), gist_box_picksplit(), gist_indexsortbuild(), gist_indexsortbuild_levelstate_flush(), gist_page_items_bytea(), gistbeginscan(), gistfillitupvec(), gistGetItupFromPage(), gistgettuple(), gistMakeUnionItVec(), gistrescan(), gistScanPage(), gistSplitByKey(), gistSplitHalf(), gseg_picksplit(), gtrgm_alloc(), gtrgm_consistent(), gtrgm_picksplit(), gtsquery_picksplit(), gtsvector_alloc(), gtsvector_penalty(), gtsvector_picksplit(), hash_object_field_end(), hashagg_batch_read(), hashbpchar(), hashbpcharextended(), hashtext(), hashtextextended(), heap_copy_minimal_tuple(), heap_copy_tuple_as_datum(), heap_copytuple(), heap_copytuple_with_tuple(), heap_multi_insert(), heap_page_items(), heap_tuple_from_minimal_tuple(), 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(), ImportSnapshot(), inet_gist_picksplit(), inet_set_masklen(), init_sexpr(), init_slab_allocator(), init_trgm_array(), init_tsvector_parser(), InitDeadLockChecking(), initialize_change_context(), InitJumble(), InitPostmasterChildSlots(), initStringInfoInternal(), InitWalRecovery(), inplaceGetInvalidationMessages(), int2out(), int2vectorout(), int44in(), int44out(), int4_to_char(), int4out(), int8_to_char(), int8out(), int_custom_out(), int_to_roman(), interpret_AS_clause(), interpret_function_parameter_list(), intervaltypmodout(), irbt_alloc(), json_manifest_finalize_file(), jsonb_object_keys(), JsonbValueToJsonb(), JsonEncodeDateTime(), jsonpath_yyalloc(), jsonpath_yyrealloc(), JsonValueListAppend(), leafRepackItems(), libpqrcv_readtimelinehistoryfile(), like_fixed_prefix(), like_fixed_prefix_ci(), litbufdup(), llvm_compile_expr(), lo_get_fragment_internal(), load_domaintype_info(), load_enum_cache_data(), load_relcache_init_file(), logfile_getname(), logical_heap_rewrite_flush_mappings(), logicalrep_read_tuple(), LogicalRepSyncTableStart(), LogicalTapeFreeze(), LogicalTapeSetCreate(), LogicalTapeWrite(), lookup_var_attr_stats(), lpad(), lrq_alloc(), ltree2text(), ltree_gist_alloc(), ltree_label_match(), ltree_picksplit(), ltsInitReadBuffer(), lz4_compress_datum(), lz4_decompress_datum(), lz4_decompress_datum_slice(), macaddr8_out(), macaddr_out(), make_build_data(), make_colname_unique(), make_greater_string(), make_jsp_entry_node(), make_jsp_expr_node(), make_partitionedrel_pruneinfo(), make_pathtarget_from_tlist(), make_result_safe(), make_sort_from_groupcols(), make_sort_from_sortclauses(), make_text_key(), make_tuple_from_result_row(), make_tuple_indirect(), makeitem(), makeObjectName(), makeParamList(), mark_hl_fragments(), MatchNamedCall(), MatchText(), mbuf_create(), minimal_tuple_from_heap_tuple(), mock_scram_secret(), moveLeafs(), mul_var(), mXactCacheGetById(), new_list(), newLexeme(), nodeRead(), numeric_sortsupport(), numeric_to_char(), numeric_to_number(), numerictypmodout(), oid8out(), oidout(), oidvectorout(), oidvectortypes(), OpernameGetCandidates(), optionListToArray(), order_qual_clauses(), ordered_set_startup(), pad_eme_pkcs1_v15(), PageGetTempPage(), PageGetTempPageCopy(), PageGetTempPageCopySpecial(), palloc_btree_page(), palloc_mul(), parse_compress_specification(), parse_fcall_arguments(), parse_one_reloption(), parse_scram_secret(), parse_tsquery(), ParseLongOption(), parseRelOptions(), partition_bounds_copy(), path_add(), path_in(), path_poly(), path_recv(), percentile_cont_multi_final_common(), percentile_disc_multi_final(), pg_armor(), pg_blocking_pids(), 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_constraintdef_worker(), pg_get_logical_snapshot_info(), pg_get_userbyid(), pg_hmac(), pg_import_system_collations(), pg_listening_channels(), pg_random_bytes(), pg_safe_snapshot_blocking_pids(), pg_snapshot_recv(), pglz_compress_datum(), pglz_decompress_datum(), pglz_decompress_datum_slice(), pgp_extract_armor_headers(), pgp_key_id_w(), pgp_mpi_alloc(), pgpa_make_scan(), pgrowlocks(), pgsa_read_from_disk(), pgss_shmem_init(), pgstat_fetch_entry(), pgstat_get_transactional_drops(), placeChar(), plaintree(), plperl_spi_exec_prepared(), plperl_spi_prepare(), plperl_spi_query_prepared(), plpgsql_ns_additem(), pltcl_quote(), pltcl_SPI_execute_plan(), pltcl_SPI_prepare(), PLy_cursor_plan(), PLy_procedure_munge_source(), PLy_spi_execute_plan(), PLyObject_ToBytea(), pnstrdup(), policy_role_list_to_array(), poly_path(), populate_record(), populate_recordset_object_field_end(), populate_scalar(), PostmasterMain(), pq_getmsgtext(), prepare_sort_from_pathkeys(), prepare_sql_fn_parse_info(), preparePresortedCols(), preprocess_grouping_sets(), PrescanPreparedTransactions(), ProcessStartupPacket(), prs_setup_firstcall(), psprintf(), pullf_create(), pushf_create(), px_find_hmac(), QTNCopy(), queryin(), queue_listen(), quote_identifier(), quote_literal(), quote_literal_cstr(), range_gist_picksplit(), RE_compile(), RE_compile_and_cache(), read_binary_file(), read_client_final_message(), read_stream_begin_impl(), read_whole_file(), readDatum(), readtup_heap(), ReadTwoPhaseFile(), rebuild_database_list(), record_cmp(), record_eq(), record_image_cmp(), record_image_eq(), record_in(), record_recv(), regclassout(), regcollationout(), regcomp_auth_token(), regconfigout(), regdatabaseout(), regdictionaryout(), regexec_auth_token(), regexp_fixed_prefix(), RegisterAfterTriggerBatchCallback(), regnamespaceout(), regoperout(), regprocout(), regroleout(), regtypeout(), rel_is_distinct_for(), RelationBuildPartitionDesc(), RelationBuildTriggers(), RememberToFreeTupleDescAtEOX(), remove_dbtablespaces(), remove_useless_groupby_columns(), ReorderBufferQueueMessage(), repeat(), replace_text_regexp(), report_json_context(), resizeString(), restore_tuple(), rot13_passphrase(), rpad(), save_state_data(), scanner_init(), scram_build_secret(), scram_verify_plain_password(), SearchCatCacheList(), secure_open_server(), seg_out(), select_outer_pathkeys_for_merge(), sepgsql_fmgr_hook(), seq_redo(), serialize_expr_stats(), SerializeTransactionState(), set_relation_column_names(), set_rtable_names(), set_var_from_str(), setup_firstcall(), setup_pct_info(), setup_regexp_matches(), setup_test_matches(), ShmemRequestInternal(), show_trgm(), similar_escape_internal(), spg_text_inner_consistent(), spg_text_leaf_consistent(), spgAllocSearchItem(), spgist_name_inner_consistent(), spgNewHeapItem(), SplitToVariants(), StartPrepare(), startScanKey(), statext_mcv_build(), statext_mcv_deserialize(), statext_ndistinct_build(), statext_ndistinct_deserialize(), statext_ndistinct_serialize(), StoreRelCheck(), str_casefold(), str_initcap(), str_tolower(), str_toupper(), str_udeescape(), string_to_bytea_const(), strlower_libc_mb(), strncoll_libc(), strnxfrm_libc(), strtitle_libc_mb(), strupper_libc_mb(), sync_queue_init(), test_custom_stats_var_from_serialized_data(), test_enc_conversion(), test_pattern(), test_pglz_compress(), test_pglz_decompress(), test_random(), test_re_compile(), test_resowner_many(), test_resowner_priorities(), test_saslprep(), test_saslprep_ranges(), test_text_to_wchars(), test_wchars_to_text(), testdelete(), text_catenate(), text_reverse(), text_substring(), text_to_bits(), text_to_cstring(), TidListEval(), toast_fetch_datum(), toast_fetch_datum_slice(), toast_save_datum(), transformRelOptions(), translate(), TS_phrase_output(), ts_process_call(), tsqueryout(), tsqueryrecv(), tsquerytree(), tsvector_setweight(), tsvector_setweight_by_filter(), tsvector_to_array(), tsvector_unnest(), tsvectorout(), tuple_data_split_internal(), tuplesort_begin_batch(), tuplesort_putbrintuple(), tuplesort_putgintuple(), tuplestore_begin_common(), unicode_normalize_func(), update_attstats(), uuid_decrement(), uuid_increment(), uuid_out(), uuid_recv(), uuid_skipsupport(), vac_open_indexes(), varbit(), varbit_out(), varbit_recv(), varstr_levenshtein(), varstr_sortsupport(), xid8out(), xidout(), XLogInsertRecord(), XLogReadRecordAlloc(), xml_recv(), xpath_string(), xpath_table(), yyalloc(), and yyrealloc().

◆ palloc0()

void * palloc0 ( Size  size)

Definition at line 1420 of file mcxt.c.

1421{
1422 /* duplicates MemoryContextAllocZero to avoid increased overhead */
1423 void *ret;
1425
1426 Assert(MemoryContextIsValid(context));
1428
1429 context->isReset = false;
1430
1431 ret = context->methods->alloc(context, size, 0);
1432 /* We expect OOM to be handled by the alloc function */
1433 Assert(ret != NULL);
1434 VALGRIND_MEMPOOL_ALLOC(context, ret, size);
1435
1436 MemSetAligned(ret, 0, size);
1437
1438 return ret;
1439}

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

Referenced by _bt_form_posting(), _bt_truncate(), _bt_unmark_keys(), _bt_update_posting(), _gin_build_tuple(), _ltq_extract_regex(), _ltree_extract_isparent(), _ltree_extract_risparent(), _ltxtq_extract_exec(), accum_sum_rescale(), add_column_to_pathtarget(), add_sp_item_to_pathtarget(), allocacl(), allocateReloptStruct(), AlterObjectNamespace_internal(), AlterObjectOwner_internal(), AlterObjectRename_internal(), appendSCRAMKeysInfo(), array_cat(), array_get_slice(), array_in(), array_map(), array_recv(), array_replace_internal(), array_set_element(), array_set_slice(), array_to_tsvector(), be_tls_init(), BeginCopyFrom(), BeginCopyTo(), bernoulli_initsamplescan(), BipartiteMatch(), bit(), bit_in(), BlockRefTableEntryMarkBlockModified(), bloom_create(), bloom_init(), BloomFormTuple(), 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(), bt_page_print_tuples(), build_expanded_ranges(), build_expr_data(), build_mvdependencies(), build_sorted_items(), BuildDatabaseList(), buildint2vector(), buildNSItemFromLists(), buildNSItemFromTupleDesc(), buildoidvector(), circle_poly_internal(), collect_visibility_data(), combo_init(), compact_palloc0(), compile_plperl_function(), compile_pltcl_function(), construct_connection_params(), construct_md_array(), copy_ltree(), create_array_envelope(), create_groupingsets_plan(), 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(), cvt_text_name(), deparse_context_for_plan_tree(), dependencies_object_end(), do_analyze_rel(), dsm_impl_mmap(), EnumValuesCreate(), eqjoinsel(), ExecBuildGroupingEqual(), ExecBuildHash32Expr(), ExecBuildHash32FromAttrs(), ExecBuildParamSetEqual(), ExecEvalArrayExpr(), ExecEvalHashedScalarArrayOp(), ExecGrant_Relation(), ExecIndexBuildScanKeys(), ExecInitAppend(), ExecInitBitmapAnd(), ExecInitBitmapOr(), ExecInitExprRec(), ExecInitFunc(), ExecInitGenerated(), ExecInitIndexScan(), ExecInitJsonExpr(), ExecInitJunkFilterConversion(), ExecInitRangeTable(), ExecInitResultRelation(), ExecInitSetOp(), ExecInitSubscriptingRef(), ExecInitValuesScan(), expand_partitioned_rtentry(), expand_tuple(), expand_virtual_generated_columns(), ExplainCreateWorkersState(), extract_rollup_sets(), extract_variadic_args(), fetch_more_data(), fillFakeState(), 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(), get_crosstab_tuplestore(), get_matching_partitions(), get_relation_info(), GetAccessStrategyWithSize(), getColorInfo(), ginNewScanKey(), gist_indexsortbuild_levelstate_add(), grow_notnull_info(), heap_form_minimal_tuple(), heap_form_tuple(), heap_toast_insert_or_update(), heap_vacuum_rel(), hmac_init(), identify_join_columns(), init_returning_filter(), InitCatCache(), initHyperLogLog(), initSpGistState(), inittapes(), inline_function(), inner_subltree(), int2vectorin(), interpret_function_parameter_list(), jbv_string_get_cstr(), jsonb_exec_setup(), lca_inner(), leader_takeover_tapes(), leftmostvalue_name(), ltree_concat(), ltree_picksplit(), ltree_union(), make_auth_token(), make_inh_translation_list(), make_multirange(), make_partitionedrel_pruneinfo(), make_setop_translation_list(), make_sort_input_target(), make_tsvector(), make_tuple_from_result_row(), make_tuple_indirect(), makeArrayResultArr(), MakeTupleTableSlot(), 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_object_end(), new_intArrayType(), newNode(), newRegisNode(), oidvectorin(), palloc0_mul(), ParallelSlotsSetup(), parse_hosts_line(), parse_lquery(), parse_ltree(), parse_tsquery(), pg_crypt(), pgoutput_truncate(), pgp_init(), plperl_modify_tuple(), plsample_func_handler(), pltcl_build_tuple_result(), PLy_modify_tuple(), poly_in(), poly_recv(), prepare_query_params(), PrepareForIncrementalBackup(), preparePresortedCols(), printtup_prepare_info(), pull_up_constant_function(), pull_up_simple_subquery(), pull_up_simple_values(), px_crypt_shacrypt(), QTN2QT(), queryin(), range_agg_finalfn(), range_serialize(), read_buffers(), RelationBuildLocalRelation(), ReorderBufferToastReplace(), RequestNamedLWLockTranche(), reverse_name(), rewriteTargetListIU(), rewriteValuesRTE(), serialize_prepare_info(), set_append_rel_size(), set_deparse_for_query(), set_join_column_names(), set_plan_references(), set_simple_column_names(), set_subquery_pathlist(), SetExplainExtensionState(), SnapBuildSerialize(), spgFormInnerTuple(), spgFormLeafTuple(), spgFormNodeTuple(), spgist_name_leaf_consistent(), standard_join_search(), statext_dependencies_build(), statext_dependencies_deserialize(), statext_dependencies_serialize(), statext_mcv_build(), statext_mcv_deserialize(), statext_mcv_import(), statext_mcv_serialize(), statext_ndistinct_deserialize(), test_create(), test_saslprep(), testdelete(), text_name(), toast_flatten_tuple_to_datum(), transformFromClauseItem(), transformSetOperationStmt(), transformValuesClause(), transformWithClause(), tsqueryrecv(), tsvector_concat(), tsvector_delete_arr(), tsvector_delete_by_indices(), tsvector_filter(), tsvector_strip(), tsvectorin(), tsvectorrecv(), TupleDescGetAttInMetadata(), tuplesort_begin_cluster(), tuplesort_begin_heap(), tuplesort_begin_index_btree(), tuplesort_begin_index_gin(), tuplesort_begin_index_gist(), vacuum_all_databases(), and varbit_in().

◆ palloc0_mul()

void * palloc0_mul ( Size  s1,
Size  s2 
)

Definition at line 1792 of file mcxt.c.

1793{
1794 /* inline mul_size() for efficiency */
1795 Size req;
1796
1799 return palloc0(req);
1800}

References fb(), mul_size_error(), palloc0(), pg_mul_size_overflow(), s1, s2, and unlikely.

◆ palloc_aligned()

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

Definition at line 1609 of file mcxt.c.

1610{
1612}

References CurrentMemoryContext, fb(), and MemoryContextAllocAligned().

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

◆ palloc_extended()

void * palloc_extended ( Size  size,
int  flags 
)

Definition at line 1442 of file mcxt.c.

1443{
1444 /* duplicates MemoryContextAllocExtended to avoid increased overhead */
1445 void *ret;
1447
1448 Assert(MemoryContextIsValid(context));
1450
1451 context->isReset = false;
1452
1453 ret = context->methods->alloc(context, size, flags);
1454 if (unlikely(ret == NULL))
1455 {
1456 /* NULL can be returned only when using MCXT_ALLOC_NO_OOM */
1457 Assert(flags & MCXT_ALLOC_NO_OOM);
1458 return NULL;
1459 }
1460
1461 VALGRIND_MEMPOOL_ALLOC(context, ret, size);
1462
1463 if ((flags & MCXT_ALLOC_ZERO) != 0)
1464 MemSetAligned(ret, 0, size);
1465
1466 return ret;
1467}

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

Referenced by AllocDeadEndChild(), apw_dump_now(), palloc_mul_extended(), pg_clean_ascii(), pgsa_read_from_disk(), qtext_load_file(), and XLogReaderAllocate().

◆ palloc_mul()

void * palloc_mul ( Size  s1,
Size  s2 
)

Definition at line 1775 of file mcxt.c.

1776{
1777 /* inline mul_size() for efficiency */
1778 Size req;
1779
1782 return palloc(req);
1783}

References fb(), mul_size_error(), palloc(), pg_mul_size_overflow(), s1, s2, and unlikely.

◆ palloc_mul_extended()

void * palloc_mul_extended ( Size  s1,
Size  s2,
int  flags 
)

Definition at line 1807 of file mcxt.c.

1808{
1809 /* inline mul_size() for efficiency */
1810 Size req;
1811
1814 return palloc_extended(req, flags);
1815}

References fb(), mul_size_error(), palloc_extended(), pg_mul_size_overflow(), s1, s2, and unlikely.

◆ pchomp()

◆ pfree()

void pfree ( void pointer)

Definition at line 1619 of file mcxt.c.

1620{
1621#ifdef USE_VALGRIND
1622 MemoryContext context = GetMemoryChunkContext(pointer);
1623#endif
1624
1625 MCXT_METHOD(pointer, free_p) (pointer);
1626
1627 VALGRIND_MEMPOOL_FREE(context, pointer);
1628}

References GetMemoryChunkContext(), 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_unmark_keys(), _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(), append_guc_value(), appendJSONKeyValueFmt(), appendSCRAMKeysInfo(), AppendStringCommandOption(), appendStringInfoStringQuoted(), apply_scanjoin_target_to_paths(), apw_dump_now(), array_free_iterator(), array_in(), array_in_safe(), 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(), astreamer_waldump_content(), astreamer_waldump_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(), 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_child_join_sjinfo(), build_EvalXFuncInt(), build_index_paths(), build_local_reloptions(), build_mvdependencies(), build_mvndistinct(), build_pertrans_for_aggref(), build_reloptions(), build_sorted_items(), buildFreshLeafTuple(), BuildRestoreCommand(), BuildTupleFromCStrings(), bytea_abbrev_convert(), byteafastcmp(), cache_single_string(), cached_function_compile(), calc_arraycontsel(), calc_distr(), calc_rank_and(), calc_rank_cd(), calc_rank_or(), calc_word_similarity(), calculate_partition_bound_for_merge(), CallShmemCallbacksAfterStartup(), cancel_on_dsm_detach(), casefold(), cash_words(), CatalogCloseIndexes(), CatCacheFreeKeys(), CatCacheRemoveCList(), CatCacheRemoveCTup(), char2wchar(), check_all_expr_argnames_valid(), 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_foreign_key(), check_ident_usermap(), check_locale(), check_log_connections(), check_log_destination(), check_log_min_messages(), check_oauth_validator(), check_partitions_for_split(), check_primary_key(), check_publications(), check_publications_origin_sequences(), check_publications_origin_tables(), 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(), CheckSASLAuth(), checkSharedDependencies(), choose_plan_name(), 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(), collectPartitionIndexExtDeps(), 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_connection_params(), construct_empty_expanded_array(), convert_any_priv_string(), convert_charset(), convert_column_name(), convert_string_datum(), convert_to_scalar(), convertPgWchar(), copy_connection(), 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(), 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(), datumSerialize(), db_encoding_convert(), dbase_redo(), DCH_to_char(), deallocate_query(), DecodeTextArrayToBitmapset(), DeconstructFkConstraintRow(), DefineDomain(), DefineEnum(), DefineRange(), DefineType(), deleteSplitPartitionContext(), 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_init(), 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(), escape_json_text(), eval_windowaggregates(), EventTriggerAlterTableEnd(), EventTriggerSQLDropAddObject(), examine_attribute(), examine_attribute(), examine_expression(), exec_bind_message(), exec_command_conninfo(), exec_command_unrestrict(), exec_object_restorecon(), exec_stmt_foreach_a(), 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(), export_initial_snapshot(), extended_statistics_update(), extract_autovac_opts(), extract_rollup_sets(), fetch_finfo_record(), fetch_function_defaults(), fetch_relation_list(), fetch_remote_slots(), fetch_remote_table_info(), fetch_statentries_for_relation(), file_acquire_sample_rows(), filter_list_to_array(), finalize_aggregates(), FinalizeIncrementalManifest(), find_in_path(), find_in_paths(), 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_remattrmap(), free_sort_tuple(), FreeAccessStrategy(), freeAndGetParent(), FreeBulkInsertState(), FreeConfigVariable(), FreeDatabaseList(), FreeErrorData(), FreeErrorDataContents(), FreeExprContext(), FreeFakeRelcacheEntry(), freeGinBtreeStack(), freeHyperLogLog(), FreeOldMultiXactReader(), freePartitionIndexExtDeps(), FreeQueryDesc(), FreeSnapshot(), 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(), gc_qtexts(), gen_ossl_free(), generate_append_tlist(), generate_base_implied_equalities_no_const(), generate_combinations(), generate_dependencies(), generate_error_response(), generate_matching_part_pairs(), generate_normalized_query(), generate_trgm_only(), generate_wildcard_trgm(), generateClonedExtStatsStmt(), generateHeadline(), generator_free(), GenericXLogAbort(), GenericXLogFinish(), get_attstatsslot(), get_const_expr(), get_control_dbstate(), get_dbname_oid_list_from_mfile(), get_docrep(), get_extension_aux_control_filename(), get_extension_control_directories(), get_extension_script_filename(), get_flush_position(), get_from_clause(), get_initial_snapshot(), 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(), GetAggInitVal(), GetAggInitVal(), getColorInfo(), GetConfFilesInDir(), getFileContentType(), GetMultiXactIdHintBits(), getNextNearest(), getObjectDescription(), getObjectIdentityParts(), getPublicationSchemaInfo(), GetTempNamespaceProcNumber(), GetWALRecordsInfo(), GetWalStats(), 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(), ginFinishSplit(), ginFlushBuildState(), GinFormTuple(), ginFreeScanKeys(), ginNewScanKey(), 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(), host_cache_pointer(), hstoreUniquePairs(), hv_fetch_string(), hv_store_string(), icu_language_tag(), import_expressions(), import_pg_statistic(), index_compute_xid_horizon_for_tuples(), index_create_copy(), index_form_tuple_context(), index_truncate_tuple(), IndexScanEnd(), infix(), infix(), infix(), initcap(), InitExecPartitionPruneContexts(), initialize_reloptions(), InitializeSystemUser(), InitPostgres(), initTrie(), InitWalRecovery(), inner_int_inter(), insert_username(), InsertOneTuple(), InsertPgAttributeTuples(), internal_citext_pattern_cmp(), intorel_destroy(), intset_subtract(), inv_close(), inv_getsize(), inv_read(), inv_truncate(), inv_write(), InvalidateAttoptCacheCallback(), InvalidateConstraintCacheCallBack(), InvalidateTableSpaceCacheCallback(), IoWorkerMain(), irbt_free(), isAnyTempNamespace(), isolation_start_test(), iterate_jsonb_values(), iterate_word_similarity(), jbv_to_infunc_datum(), 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_send(), jsonb_set_element(), JsonbDeepContains(), JsonbValue_to_SV(), JsonItemFromDatum(), jsonpath_send(), jsonpath_yyfree(), JsonValueListClear(), 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_option_from_conninfo(), libpqrcv_startstreaming(), libpqsrv_PGresultSetParent(), libpqsrv_PQclear(), like_fixed_prefix(), like_fixed_prefix_ci(), 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(), LogicalRepSyncSequences(), 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_label_match(), ltree_picksplit(), ltree_recv(), ltree_send(), ltree_textadd(), ltxtq_recv(), ltxtq_send(), lz4_compress_datum(), main(), main(), make_greater_string(), make_partition_pruneinfo(), make_partitionedrel_pruneinfo(), make_propgraphdef_properties(), 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(), mq_putmessage(), 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_poly_stddev_internal(), numeric_to_number(), numericvar_to_double_no_overflow(), object_aclmask_ext(), overexplain_alias(), overexplain_bitmapset(), overexplain_bitmapset_list(), 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_ddl_options(), 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(), 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_database_ddl_internal(), 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_role_ddl_internal(), pg_get_statisticsobj_worker(), pg_get_statisticsobjdef_expressions(), pg_get_tablespace_ddl_internal(), 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_autovacuum_scores(), 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(), pgpa_destroy_join_unroller(), pgss_shmem_init(), pgss_shmem_shutdown(), 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(), postgres_fdw_connection(), postgresExecForeignTruncate(), postgresGetForeignJoinPaths(), PostmasterMain(), PostPrepare_smgr(), pprint(), pq_cleanup_redirect_to_shm_mq(), 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_rel_infos(), process_target_wal_block_change(), ProcessCommittedInvalidationMessages(), ProcessConfigFileInternal(), ProcessGUCArray(), ProcessParallelApplyMessages(), ProcessParallelMessages(), ProcessPgArchInterrupts(), ProcessRepackMessages(), ProcessSingleRelationFork(), ProcessStandbyHSFeedbackMessage(), ProcessStandbyReplyMessage(), ProcessStartupPacket(), 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(), qtext_load_file(), QTNFree(), QTNTernary(), queryin(), range_fast_cmp(), range_recv(), rbt_populate(), RE_compile(), RE_compile_and_cache(), RE_execute(), read_buffers(), read_client_final_message(), read_dictionary(), 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(), relation_needs_vacanalyze(), RelationBuildPartitionKey(), RelationBuildPublicationDesc(), RelationBuildRowSecurity(), RelationBuildRuleLock(), RelationBuildTriggers(), RelationBuildTupleDesc(), RelationCacheInitializePhase3(), RelationDestroyRelation(), RelationGetDummyIndexExpressions(), RelationGetIndexAttOptions(), RelationGetIndexExpressions(), RelationGetIndexPredicate(), RelationInvalidateRelation(), RelationParseRelOptions(), RelationPreserveStorage(), RelationReloadIndexInfo(), release_change_context(), ReleaseDummy(), ReleaseManyTestResource(), ReleasePostmasterChildSlot(), relmap_redo(), remove_cache_entry(), remove_dbtablespaces(), remove_leftjoinrel_from_query(), remove_self_join_rel(), RemoveLocalLock(), RenameTypeInternal(), ReorderBufferAddDistributedInvalidations(), ReorderBufferFreeChange(), ReorderBufferFreeRelids(), ReorderBufferFreeSnap(), ReorderBufferFreeTupleBuf(), ReorderBufferFreeTXN(), ReorderBufferIterTXNFinish(), ReorderBufferToastReplace(), ReorderBufferToastReset(), reorderqueue_pop(), repack_store_change(), replace_auto_config_value(), replace_text(), replace_text_regexp(), replication_scanner_finish(), ReplicationSlotDropAtPubNode(), ReplicationSlotRelease(), ReplicationSlotValidateName(), 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(), RestoreArchivedFile(), 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(), scan_identifier(), 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(), ShmemInitRequested(), show_memoize_info(), show_trgm(), show_window_def(), show_window_keys(), ShowAllGUCConfig(), ShowTransactionStateRec(), ShowUsage(), ShutdownExprContext(), ShutdownWalRecovery(), 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(), SplitToVariants(), sqlfunction_destroy(), StandbyRecoverPreparedTransactions(), StandbyTransactionIdIsPrepared(), start_table_sync(), StartPrepare(), startScanEntry(), StartupRereadConfig(), StartupXLOG(), statatt_build_stavalues(), statext_dependencies_free(), statext_mcv_build(), statext_mcv_deserialize(), statext_mcv_free(), statext_mcv_import(), statext_mcv_serialize(), statext_ndistinct_free(), stop_repack_decoding_worker(), 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(), SyncPostCheckpoint(), syncrep_scanner_finish(), SyncRepGetNthLatestSyncRecPtr(), SyncRepGetSyncRecPtr(), SysLogger_Start(), SysLoggerMain(), systable_beginscan(), systable_beginscan_ordered(), systable_endscan(), systable_endscan_ordered(), table_recheck_autovac(), tablesample_init(), TablespaceCreateDbspace(), tbm_end_private_iterate(), tbm_end_shared_iterate(), tbm_free(), terminate_brin_buildstate(), test_basic(), test_bms_overlap_list(), test_cplusplus_add(), test_custom_stats_var_from_serialized_data(), test_destroy(), test_enc_conversion(), test_protocol_version(), test_random(), test_random_operations(), test_re_compile(), test_saslprep_ranges(), 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(), 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()

◆ ProcessLogMemoryContextInterrupt()

void ProcessLogMemoryContextInterrupt ( void  )

Definition at line 1343 of file mcxt.c.

1344{
1346
1347 /*
1348 * Exit immediately if memory context logging is already in progress. This
1349 * prevents recursive calls, which could occur if logging is requested
1350 * repeatedly and rapidly, potentially leading to infinite recursion and a
1351 * crash.
1352 */
1354 return;
1356
1357 PG_TRY();
1358 {
1359 /*
1360 * Use LOG_SERVER_ONLY to prevent this message from being sent to the
1361 * connected client.
1362 */
1364 (errhidestmt(true),
1365 errhidecontext(true),
1366 errmsg("logging memory contexts of PID %d", MyProcPid)));
1367
1368 /*
1369 * When a backend process is consuming huge memory, logging all its
1370 * memory contexts might overrun available disk space. To prevent
1371 * this, we limit the depth of the hierarchy, as well as the number of
1372 * child contexts to log per parent to 100.
1373 *
1374 * As with MemoryContextStats(), we suppose that practical cases where
1375 * the dump gets long will typically be huge numbers of siblings under
1376 * the same parent context; while the additional debugging value from
1377 * seeing details about individual siblings beyond 100 will not be
1378 * large.
1379 */
1381 }
1382 PG_FINALLY();
1383 {
1385 }
1386 PG_END_TRY();
1387}

References ereport, errhidecontext(), errhidestmt(), errmsg, LOG_SERVER_ONLY, LogMemoryContextInProgress, LogMemoryContextPending, MemoryContextStatsDetail(), MyProcPid, PG_END_TRY, PG_FINALLY, PG_TRY, and TopMemoryContext.

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

◆ pstrdup()

char * pstrdup ( const char in)

Definition at line 1910 of file mcxt.c.

1911{
1913}

References CurrentMemoryContext, and MemoryContextStrdup().

Referenced by AbsoluteConfigLocation(), accesstype_arg_to_string(), add_row_identity_var(), add_with_check_options(), addCompiledLexeme(), addFkConstraint(), addRangeTableEntryForFunction(), addRangeTableEntryForGraphTable(), addRangeTableEntryForGroup(), addRangeTableEntryForSubquery(), addRangeTableEntryForTableFunc(), addRangeTableEntryForValues(), AddRelationNotNullConstraints(), addToResult(), allocate_reloption(), AllocSlruSegState(), AlterRole(), analyzeCTETargetList(), anytime_typmodout(), anytimestamp_typmodout(), append_database_pattern(), append_guc_value(), append_relation_pattern_helper(), append_schema_pattern(), ApplyRetrieveRule(), array_out(), astreamer_extractor_new(), astreamer_gzip_writer_new(), astreamer_plain_writer_new(), ATExecAddIndexConstraint(), ATExecAlterCheckConstrEnforceability(), ATExecAlterConstraint(), ATExecAlterFKConstrEnforceability(), ATParseTransformCmd(), BaseBackupAddTarget(), be_tls_init(), BeginCopyFrom(), BeginCopyTo(), BootstrapModeMain(), BufFileCreateFileSet(), BufFileOpenFileSet(), build_datatype(), build_minmax_path(), build_remattrmap(), build_server_first_message(), BuildDatabaseList(), 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(), choose_plan_name(), 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(), createTableConstraints(), 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(), exec_bind_message(), exec_command_restrict(), exec_execute_message(), executeItemOptUnwrapTarget(), expand_dynamic_library_name(), expand_inherited_rtentry(), expand_insert_targetlist(), expand_single_inheritance_child(), ExpandRowReference(), expandRTE(), expandTableLikeClause(), expandTupleDesc(), ExportSnapshot(), extension_file_exists(), extract_slot_names(), ExtractExtensionList(), fetch_statentries_for_relation(), fill_hba_line(), filter_list_to_array(), find_in_paths(), find_plan(), flatten_set_variable_args(), 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(), generate_union_from_pathqueries(), 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_propgraph_label_name(), get_propgraph_property_name(), get_publication_name(), get_rel_name(), get_role_password(), get_rolespec_name(), get_source_line(), get_sql_insert(), get_sql_update(), get_subscription_list(), get_subscription_name(), get_tablespace_location(), get_tablespace_name(), getAdditionalACLs(), getAttributesList(), GetConfFilesInDir(), GetConfigOptionValues(), getConnectionByName(), GetDatabasePath(), GetForeignDataWrapperExtended(), GetForeignServerExtended(), GetJsonBehaviorValueString(), getNamespaces(), getObjectIdentityParts(), getOpFamilyIdentity(), GetPublication(), getRecoveryStopReason(), getRelationIdentity(), getRelationStatistics(), GetSubscription(), getTokenTypes(), GetUserNameFromId(), GetWaitEventCustomNames(), gtsvectorout(), heap_vacuum_rel(), host_cache_pointer(), hstore_out(), ImportForeignSchema(), indent_lines(), injection_points_attach(), InjectionPointList(), insert_property_records(), 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_option_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(), LogicalRepSyncSequences(), main(), main(), make_rfile(), makeAlias(), makeColumnDef(), makeJsonTablePathSpec(), makeMultirangeTypeName(), map_sql_value_to_xml_value(), MarkGUCPrefixReserved(), md5_crypt_verify(), MergeAttributes(), MergeCheckConstraint(), name_active_windows(), nameout(), network_out(), new_ExtensionControlFile(), NINormalizeWord(), NormalizeSubWord(), nullable_string(), numeric_normalize(), numeric_out(), numeric_out_sci(), oauth_exchange(), obtain_object_name_namespace(), 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_hosts_line(), parse_ident_line(), parse_output_parameters(), parse_publication_options(), parse_scram_secret(), parse_subscription_options(), ParseConfigFp(), ParseLongOption(), parseNameAndArgTypes(), ParseTzFile(), perform_base_backup(), PerformCursorOpen(), pg_available_extension_versions(), pg_available_extensions(), pg_get_advice_stash_contents(), pg_get_database_ddl_internal(), pg_get_role_ddl_internal(), pg_get_tablespace_ddl_internal(), pg_import_system_collations(), pg_lsn_out(), pg_split_opts(), pg_split_walfile_name(), pg_tzenumerate_next(), pg_tzenumerate_start(), pgfnames(), pgrowlocks(), pgsa_advisor(), pgsa_write_stashes(), 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(), ProcessRepackMessage(), 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(), regdatabaseout(), regdictionaryout(), register_label_provider(), RegisterOAuthHBAOptions(), 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(), transformPathPatternList(), 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(), and X509_NAME_to_cstring().

◆ repalloc()

void * repalloc ( void pointer,
Size  size 
)

Definition at line 1635 of file mcxt.c.

1636{
1637#if defined(USE_ASSERT_CHECKING) || defined(USE_VALGRIND)
1638 MemoryContext context = GetMemoryChunkContext(pointer);
1639#endif
1640 void *ret;
1641
1643
1644 /* isReset must be false already */
1645 Assert(!context->isReset);
1646
1647 /*
1648 * For efficiency reasons, we purposefully offload the handling of
1649 * allocation failures to the MemoryContextMethods implementation as this
1650 * allows these checks to be performed only when an actual malloc needs to
1651 * be done to request more memory from the OS. Additionally, not having
1652 * to execute any instructions after this call allows the compiler to use
1653 * the sibling call optimization. If you're considering adding code after
1654 * this call, consider making it the responsibility of the 'realloc'
1655 * function instead.
1656 */
1657 ret = MCXT_METHOD(pointer, realloc) (pointer, size, 0);
1658
1659 VALGRIND_MEMPOOL_CHANGE(context, pointer, ret, size);
1660
1661 return ret;
1662}

References Assert, AssertNotInCriticalSection, GetMemoryChunkContext(), MemoryContextData::isReset, 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_object_address(), add_reloption(), addCompiledLexeme(), addCompoundAffixFlagValue(), AddInvalidationMessage(), addlit(), addlitchar(), AddStem(), addToArray(), 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(), checkSharedDependencies(), compileTheLexeme(), compileTheSubstitute(), CopyReadAttributesCSV(), CopyReadAttributesText(), core_yyrealloc(), count_usable_fds(), cube_inter(), do_set_block_offsets(), dsnowball_lexize(), dxsyn_lexize(), enlarge_list(), enlarge_trgm_array(), 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(), GetPlannerExtensionId(), GetSingleProcBlockerStatusData(), GinBufferStoreTuple(), GinFormTuple(), ginPostingListDecodeAllSegments(), gistAddLoadedBuffer(), gistBuffersReleaseBlock(), gistGetNodeBuffer(), 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(), ltree_label_match(), ltsGetPreallocBlock(), ltsReleaseBlock(), mark_hl_fragments(), MergeAffix(), multirange_in(), NIAddAffix(), NIAddSpell(), NISortAffixes(), oidvectorin(), oidvectortypes(), okeys_object_field_start(), parse_hstore(), parsetext(), perform_default_encoding_conversion(), pg_do_encoding_conversion(), pg_import_system_collations(), pgsa_read_from_disk(), pgss_shmem_init(), plainnode(), plpgsql_adddatum(), prepare_room(), PrescanPreparedTransactions(), prs_setup_firstcall(), pushval_asis(), pushValue(), record_corrupt_item(), RecordConstLocation(), RegisterExtensionExplainOption(), RelationBuildDesc(), RelationBuildRuleLock(), RelationBuildTriggers(), RememberToFreeTupleDescAtEOX(), ReorderBufferSerializeReserve(), repalloc0(), repalloc_mul(), resize_intArrayType(), resizeString(), rmtree(), SetConstraintStateAddItem(), setup_regexp_matches(), setup_test_matches(), 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(), TidListEval(), tsqueryrecv(), tsvectorin(), tsvectorrecv(), tuplestore_alloc_read_pointer(), uniqueentry(), varstr_abbrev_convert(), varstrfastcmp_locale(), XLogEnsureRecordSpace(), and yyrealloc().

◆ repalloc0()

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

Definition at line 1707 of file mcxt.c.

1708{
1709 void *ret;
1710
1711 /* catch wrong argument order */
1712 if (unlikely(oldsize > size))
1713 elog(ERROR, "invalid repalloc0 call: oldsize %zu, new size %zu",
1714 oldsize, size);
1715
1716 ret = repalloc(pointer, size);
1717 memset((char *) ret + oldsize, 0, (size - oldsize));
1718 return ret;
1719}

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

Referenced by grow_notnull_info().

◆ repalloc_extended()

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

Definition at line 1670 of file mcxt.c.

1671{
1672#if defined(USE_ASSERT_CHECKING) || defined(USE_VALGRIND)
1673 MemoryContext context = GetMemoryChunkContext(pointer);
1674#endif
1675 void *ret;
1676
1678
1679 /* isReset must be false already */
1680 Assert(!context->isReset);
1681
1682 /*
1683 * For efficiency reasons, we purposefully offload the handling of
1684 * allocation failures to the MemoryContextMethods implementation as this
1685 * allows these checks to be performed only when an actual malloc needs to
1686 * be done to request more memory from the OS. Additionally, not having
1687 * to execute any instructions after this call allows the compiler to use
1688 * the sibling call optimization. If you're considering adding code after
1689 * this call, consider making it the responsibility of the 'realloc'
1690 * function instead.
1691 */
1692 ret = MCXT_METHOD(pointer, realloc) (pointer, size, flags);
1693 if (unlikely(ret == NULL))
1694 return NULL;
1695
1696 VALGRIND_MEMPOOL_CHANGE(context, pointer, ret, size);
1697
1698 return ret;
1699}

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

Referenced by guc_realloc(), repalloc_huge(), and repalloc_mul_extended().

◆ repalloc_huge()

void * repalloc_huge ( void pointer,
Size  size 
)

Definition at line 1886 of file mcxt.c.

1887{
1888 /* this one seems not worth its own implementation */
1889 return repalloc_extended(pointer, size, MCXT_ALLOC_HUGE);
1890}

References MCXT_ALLOC_HUGE, and repalloc_extended().

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

◆ repalloc_mul()

void * repalloc_mul ( void p,
Size  s1,
Size  s2 
)

Definition at line 1822 of file mcxt.c.

1823{
1824 /* inline mul_size() for efficiency */
1825 Size req;
1826
1829 return repalloc(p, req);
1830}

References fb(), mul_size_error(), pg_mul_size_overflow(), repalloc(), s1, s2, and unlikely.

◆ repalloc_mul_extended()

void * repalloc_mul_extended ( void p,
Size  s1,
Size  s2,
int  flags 
)

Definition at line 1837 of file mcxt.c.

1838{
1839 /* inline mul_size() for efficiency */
1840 Size req;
1841
1844 return repalloc_extended(p, req, flags);
1845}

References fb(), mul_size_error(), pg_mul_size_overflow(), repalloc_extended(), s1, s2, and unlikely.

Variable Documentation

◆ CacheMemoryContext

MemoryContext CacheMemoryContext = NULL

Definition at line 170 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(), FetchRelationStates(), generate_partition_qual(), get_attribute_options(), get_function_sibling_type(), 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(), plpgsql_compile_callback(), 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 161 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(), be_tls_init(), 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(), BuildDatabaseList(), BuildParamLogString(), BuildRelationExtStatistics(), BuildRelationList(), 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(), eqjoinsel_find_matches(), 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_relation_notnullatts(), get_subscription_list(), GetCachedExpression(), GetConnection(), GetErrorContextStack(), GetSubscription(), 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(), import_expressions(), index_form_tuple(), initBloomState(), InitBufferManagerAccess(), initGinState(), initGISTstate(), initialize_brin_buildstate(), initialize_peragg(), InitPartitionPruneContext(), initTrie(), inline_function(), inline_function_in_from(), intset_create(), json_unique_builder_init(), json_unique_check_init(), JsonTableInitOpaque(), libpqrcv_processTuples(), libpqsrv_PQwrap(), lo_get_fragment_internal(), lo_import_internal(), load_domaintype_info(), load_tzoffsets(), load_validator_library(), LogicalParallelApplyLoop(), makeIndexInfo(), makeNumericAggStateCurrentContext(), MakeTupleTableSlot(), materializeQueryResult(), MemoryContextDeleteOnly(), MemoryContextInit(), MemoryContextSwitchTo(), MJExamineQuals(), multi_sort_add_dimension(), NextCopyFrom(), oauth_init(), open_auth_file(), optionListToArray(), palloc(), palloc0(), palloc_aligned(), palloc_extended(), ParallelWorkerMain(), parse_ident(), perform_default_encoding_conversion(), perform_work_item(), pg_buffercache_os_pages_internal(), pg_do_encoding_conversion(), pg_get_advice_stash_contents(), pg_get_advice_stashes(), pg_get_backend_memory_contexts(), pg_get_logical_snapshot_info(), pg_get_logical_snapshot_meta(), pg_get_statisticsobjdef_expressions(), pg_get_wal_block_info(), pg_plan_advice_advice_check_hook(), pg_stats_ext_mcvlist_items(), pgpa_init_trove_slice(), pgpa_planner_setup(), pgsa_read_from_disk(), pgsa_write_to_disk(), 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_callback(), 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(), prune_append_rel_partitions(), pstrdup(), publicationListToArray(), pull_up_simple_subquery(), pushJsonbValueScalar(), pushState(), RE_compile_and_cache(), regexp_split_to_array(), RelationBuildDesc(), RelationBuildRowSecurity(), ReorderBufferAllocate(), ReorderBufferImmediateInvalidation(), ReorderBufferProcessTXN(), repack_setup_logical_decoding(), ResetUnloggedRelations(), ResetUnloggedRelationsInDbspaceDir(), RevalidateCachedQuery(), ri_populate_fastpath_metadata(), 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(), SyncReplicationSlots(), 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

◆ LogMemoryContextInProgress

bool LogMemoryContextInProgress = false
static

Definition at line 179 of file mcxt.c.

Referenced by ProcessLogMemoryContextInterrupt().

◆ mcxt_methods

const MemoryContextMethods mcxt_methods[]
static

Definition at line 64 of file mcxt.c.

64 {
65 /* aset.c */
67 [MCTX_ASET_ID].free_p = AllocSetFree,
68 [MCTX_ASET_ID].realloc = AllocSetRealloc,
70 [MCTX_ASET_ID].delete_context = AllocSetDelete,
71 [MCTX_ASET_ID].get_chunk_context = AllocSetGetChunkContext,
72 [MCTX_ASET_ID].get_chunk_space = AllocSetGetChunkSpace,
73 [MCTX_ASET_ID].is_empty = AllocSetIsEmpty,
75#ifdef MEMORY_CONTEXT_CHECKING
77#endif
78
79 /* generation.c */
84 [MCTX_GENERATION_ID].delete_context = GenerationDelete,
89#ifdef MEMORY_CONTEXT_CHECKING
91#endif
92
93 /* slab.c */
94 [MCTX_SLAB_ID].alloc = SlabAlloc,
95 [MCTX_SLAB_ID].free_p = SlabFree,
96 [MCTX_SLAB_ID].realloc = SlabRealloc,
97 [MCTX_SLAB_ID].reset = SlabReset,
98 [MCTX_SLAB_ID].delete_context = SlabDelete,
99 [MCTX_SLAB_ID].get_chunk_context = SlabGetChunkContext,
100 [MCTX_SLAB_ID].get_chunk_space = SlabGetChunkSpace,
101 [MCTX_SLAB_ID].is_empty = SlabIsEmpty,
102 [MCTX_SLAB_ID].stats = SlabStats,
103#ifdef MEMORY_CONTEXT_CHECKING
104 [MCTX_SLAB_ID].check = SlabCheck,
105#endif
106
107 /* alignedalloc.c */
108 [MCTX_ALIGNED_REDIRECT_ID].alloc = NULL, /* not required */
111 [MCTX_ALIGNED_REDIRECT_ID].reset = NULL, /* not required */
112 [MCTX_ALIGNED_REDIRECT_ID].delete_context = NULL, /* not required */
115 [MCTX_ALIGNED_REDIRECT_ID].is_empty = NULL, /* not required */
116 [MCTX_ALIGNED_REDIRECT_ID].stats = NULL, /* not required */
117#ifdef MEMORY_CONTEXT_CHECKING
118 [MCTX_ALIGNED_REDIRECT_ID].check = NULL, /* not required */
119#endif
120
121 /* bump.c */
122 [MCTX_BUMP_ID].alloc = BumpAlloc,
123 [MCTX_BUMP_ID].free_p = BumpFree,
124 [MCTX_BUMP_ID].realloc = BumpRealloc,
125 [MCTX_BUMP_ID].reset = BumpReset,
126 [MCTX_BUMP_ID].delete_context = BumpDelete,
127 [MCTX_BUMP_ID].get_chunk_context = BumpGetChunkContext,
128 [MCTX_BUMP_ID].get_chunk_space = BumpGetChunkSpace,
129 [MCTX_BUMP_ID].is_empty = BumpIsEmpty,
130 [MCTX_BUMP_ID].stats = BumpStats,
131#ifdef MEMORY_CONTEXT_CHECKING
132 [MCTX_BUMP_ID].check = BumpCheck,
133#endif
134
135
136 /*
137 * Reserved and unused IDs should have dummy entries here. This allows us
138 * to fail cleanly if a bogus pointer is passed to pfree or the like. It
139 * seems sufficient to provide routines for the methods that might get
140 * invoked from inspection of a chunk (see MCXT_METHOD calls below).
141 */
153};
MemoryContext AlignedAllocGetChunkContext(void *pointer)
void * AlignedAllocRealloc(void *pointer, Size size, int flags)
Size AlignedAllocGetChunkSpace(void *pointer)
void AlignedAllocFree(void *pointer)
void AllocSetReset(MemoryContext context)
Definition aset.c:546
void * AllocSetRealloc(void *pointer, Size size, int flags)
Definition aset.c:1237
Size AllocSetGetChunkSpace(void *pointer)
Definition aset.c:1543
MemoryContext AllocSetGetChunkContext(void *pointer)
Definition aset.c:1514
void AllocSetStats(MemoryContext context, MemoryStatsPrintFunc printfunc, void *passthru, MemoryContextCounters *totals, bool print_to_stderr)
Definition aset.c:1602
bool AllocSetIsEmpty(MemoryContext context)
Definition aset.c:1577
void * AllocSetAlloc(MemoryContext context, Size size, int flags)
Definition aset.c:1012
void AllocSetFree(void *pointer)
Definition aset.c:1107
void AllocSetDelete(MemoryContext context)
Definition aset.c:632
void BumpFree(void *pointer)
Definition bump.c:646
void BumpDelete(MemoryContext context)
Definition bump.c:294
Size BumpGetChunkSpace(void *pointer)
Definition bump.c:678
void BumpStats(MemoryContext context, MemoryStatsPrintFunc printfunc, void *passthru, MemoryContextCounters *totals, bool print_to_stderr)
Definition bump.c:717
MemoryContext BumpGetChunkContext(void *pointer)
Definition bump.c:667
void BumpReset(MemoryContext context)
Definition bump.c:251
bool BumpIsEmpty(MemoryContext context)
Definition bump.c:689
void * BumpRealloc(void *pointer, Size size, int flags)
Definition bump.c:656
void * BumpAlloc(MemoryContext context, Size size, int flags)
Definition bump.c:517
void * GenerationRealloc(void *pointer, Size size, int flags)
Definition generation.c:834
void GenerationReset(MemoryContext context)
Definition generation.c:291
void GenerationFree(void *pointer)
Definition generation.c:718
MemoryContext GenerationGetChunkContext(void *pointer)
Definition generation.c:986
Size GenerationGetChunkSpace(void *pointer)
bool GenerationIsEmpty(MemoryContext context)
void GenerationStats(MemoryContext context, MemoryStatsPrintFunc printfunc, void *passthru, MemoryContextCounters *totals, bool print_to_stderr)
void GenerationDelete(MemoryContext context)
Definition generation.c:344
void * GenerationAlloc(MemoryContext context, Size size, int flags)
Definition generation.c:553
#define BOGUS_MCTX(id)
Definition mcxt.c:58
@ MCTX_15_RESERVED_WIPEDMEM_ID
@ MCTX_GENERATION_ID
@ MCTX_14_UNUSED_ID
@ MCTX_12_UNUSED_ID
@ MCTX_10_UNUSED_ID
@ MCTX_BUMP_ID
@ MCTX_11_UNUSED_ID
@ MCTX_8_UNUSED_ID
@ MCTX_1_RESERVED_GLIBC_ID
@ MCTX_SLAB_ID
@ MCTX_9_UNUSED_ID
@ MCTX_0_RESERVED_UNUSEDMEM_ID
@ MCTX_ASET_ID
@ MCTX_2_RESERVED_GLIBC_ID
@ MCTX_13_UNUSED_ID
void * SlabAlloc(MemoryContext context, Size size, int flags)
Definition slab.c:659
void SlabFree(void *pointer)
Definition slab.c:730
void SlabReset(MemoryContext context)
Definition slab.c:436
Size SlabGetChunkSpace(void *pointer)
Definition slab.c:927
bool SlabIsEmpty(MemoryContext context)
Definition slab.c:952
MemoryContext SlabGetChunkContext(void *pointer)
Definition slab.c:903
void * SlabRealloc(void *pointer, Size size, int flags)
Definition slab.c:866
void SlabStats(MemoryContext context, MemoryStatsPrintFunc printfunc, void *passthru, MemoryContextCounters *totals, bool print_to_stderr)
Definition slab.c:969
void SlabDelete(MemoryContext context)
Definition slab.c:506

Referenced by MemoryContextCreate().

◆ MessageContext

◆ PortalContext

◆ PostmasterContext

◆ TopMemoryContext

MemoryContext TopMemoryContext = NULL

Definition at line 167 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_init(), DCH_cache_getnew(), do_autovacuum(), dsm_create_descriptor(), dsm_impl_sysv(), EnablePortalManager(), EventTriggerBeginCompleteQuery(), exec_replication_command(), executeDateTimeMethod(), find_plan(), finish_xact_command(), GenerationContextCreate(), get_role_password(), GetExplainExtensionId(), GetLocalBufferStorage(), GetLockConflicts(), getmissingattr(), GetNamedDSA(), GetNamedDSHash(), GetNamedDSMSegment(), GetPlannerExtensionId(), GetSessionDsmHandle(), hash_create(), init_database_collation(), init_missing_cache(), init_string_reloption(), InitDeadLockChecking(), initGlobalChannelTable(), initialize_reloptions(), initialize_target_list(), InitializeClientEncoding(), InitializeLogRepWorker(), InitializeParallelDSM(), InitializeSearchPath(), InitializeSession(), InitializeSystemUser(), InitPgFdwOptions(), InitSync(), InitWalSender(), InitXLogInsert(), injection_points_attach(), injection_points_detach(), llvm_compile_module(), llvm_create_context(), llvm_session_initialize(), LockAcquireExtended(), logicalrep_launcher_attach_dshmem(), LogicalRepApplyLoop(), md5_crypt_verify(), mdinit(), MemoryContextAllocationFailure(), MemoryContextDeleteOnly(), MemoryContextInit(), mxid_to_string(), newLOfd(), NUM_cache_getnew(), on_dsm_detach(), ParallelWorkerMain(), PerformAuthentication(), pg_backup_start(), pg_get_backend_memory_contexts(), pg_get_dsm_registry_allocations(), pg_newlocale_from_collation(), pg_plan_advice_get_mcxt(), PgArchiverMain(), pgsa_attach(), 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(), 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(), PreCommit_Notify(), PrepareClientEncoding(), ProcessLogMemoryContextInterrupt(), ProcessParallelApplyMessages(), ProcessParallelMessages(), ProcessRepackMessages(), 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(), ri_populate_fastpath_metadata(), roles_is_member_of(), secure_open_gssapi(), sepgsql_avc_init(), sepgsql_xact_callback(), set_authn_id(), SetDatabasePath(), SharedRecordTypmodRegistryAttach(), SharedRecordTypmodRegistryInit(), ShmemRequestHashWithOpts(), ShmemRequestStructWithOpts(), SimpleLruRequestWithOpts(), SlabContextCreate(), spcache_init(), SPI_connect_ext(), StoreConnectionWarning(), test_create(), WalSummarizerMain(), WalWriterMain(), and XLOGShmemInit().

◆ TopTransactionContext