PostgreSQL Source Code  git master
mcxt.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * mcxt.c
4  * POSTGRES memory context management code.
5  *
6  * This module handles context management operations that are independent
7  * of the particular kind of context being operated on. It calls
8  * context-type-specific operations via the function pointers in a
9  * context's MemoryContextMethods struct.
10  *
11  *
12  * Portions Copyright (c) 1996-2022, PostgreSQL Global Development Group
13  * Portions Copyright (c) 1994, Regents of the University of California
14  *
15  *
16  * IDENTIFICATION
17  * src/backend/utils/mmgr/mcxt.c
18  *
19  *-------------------------------------------------------------------------
20  */
21 
22 #include "postgres.h"
23 
24 #include "mb/pg_wchar.h"
25 #include "miscadmin.h"
26 #include "storage/proc.h"
27 #include "storage/procarray.h"
28 #include "storage/procsignal.h"
29 #include "utils/fmgrprotos.h"
30 #include "utils/memdebug.h"
31 #include "utils/memutils.h"
32 
33 
34 /*****************************************************************************
35  * GLOBAL MEMORY *
36  *****************************************************************************/
37 
38 /*
39  * CurrentMemoryContext
40  * Default memory context for allocations.
41  */
43 
44 /*
45  * Standard top-level contexts. For a description of the purpose of each
46  * of these contexts, refer to src/backend/utils/mmgr/README
47  */
55 
56 /* This is a transient link to the active portal's memory context: */
58 
60 static void MemoryContextStatsInternal(MemoryContext context, int level,
61  bool print, int max_children,
62  MemoryContextCounters *totals,
63  bool print_to_stderr);
64 static void MemoryContextStatsPrint(MemoryContext context, void *passthru,
65  const char *stats_string,
66  bool print_to_stderr);
67 
68 /*
69  * You should not do memory allocations within a critical section, because
70  * an out-of-memory error will be escalated to a PANIC. To enforce that
71  * rule, the allocation functions Assert that.
72  */
73 #define AssertNotInCriticalSection(context) \
74  Assert(CritSectionCount == 0 || (context)->allowInCritSection)
75 
76 
77 /*****************************************************************************
78  * EXPORTED ROUTINES *
79  *****************************************************************************/
80 
81 
82 /*
83  * MemoryContextInit
84  * Start up the memory-context subsystem.
85  *
86  * This must be called before creating contexts or allocating memory in
87  * contexts. TopMemoryContext and ErrorContext are initialized here;
88  * other contexts must be created afterwards.
89  *
90  * In normal multi-backend operation, this is called once during
91  * postmaster startup, and not at all by individual backend startup
92  * (since the backends inherit an already-initialized context subsystem
93  * by virtue of being forked off the postmaster). But in an EXEC_BACKEND
94  * build, each process must do this for itself.
95  *
96  * In a standalone backend this must be called during backend startup.
97  */
98 void
100 {
101  AssertState(TopMemoryContext == NULL);
102 
103  /*
104  * First, initialize TopMemoryContext, which is the parent of all others.
105  */
107  "TopMemoryContext",
109 
110  /*
111  * Not having any other place to point CurrentMemoryContext, make it point
112  * to TopMemoryContext. Caller should change this soon!
113  */
115 
116  /*
117  * Initialize ErrorContext as an AllocSetContext with slow growth rate ---
118  * we don't really expect much to be allocated in it. More to the point,
119  * require it to contain at least 8K at all times. This is the only case
120  * where retained memory in a context is *essential* --- we want to be
121  * sure ErrorContext still has some memory even if we've run out
122  * elsewhere! Also, allow allocations in ErrorContext within a critical
123  * section. Otherwise a PANIC will cause an assertion failure in the error
124  * reporting code, before printing out the real cause of the failure.
125  *
126  * This should be the last step in this function, as elog.c assumes memory
127  * management works once ErrorContext is non-null.
128  */
130  "ErrorContext",
131  8 * 1024,
132  8 * 1024,
133  8 * 1024);
135 }
136 
137 /*
138  * MemoryContextReset
139  * Release all space allocated within a context and delete all its
140  * descendant contexts (but not the named context itself).
141  */
142 void
144 {
146 
147  /* save a function call in common case where there are no children */
148  if (context->firstchild != NULL)
150 
151  /* save a function call if no pallocs since startup or last reset */
152  if (!context->isReset)
153  MemoryContextResetOnly(context);
154 }
155 
156 /*
157  * MemoryContextResetOnly
158  * Release all space allocated within a context.
159  * Nothing is done to the context's descendant contexts.
160  */
161 void
163 {
165 
166  /* Nothing to do if no pallocs since startup or last reset */
167  if (!context->isReset)
168  {
170 
171  /*
172  * If context->ident points into the context's memory, it will become
173  * a dangling pointer. We could prevent that by setting it to NULL
174  * here, but that would break valid coding patterns that keep the
175  * ident elsewhere, e.g. in a parent context. Another idea is to use
176  * MemoryContextContains(), but we don't require ident strings to be
177  * in separately-palloc'd chunks, so that risks false positives. So
178  * for now we assume the programmer got it right.
179  */
180 
181  context->methods->reset(context);
182  context->isReset = true;
183  VALGRIND_DESTROY_MEMPOOL(context);
184  VALGRIND_CREATE_MEMPOOL(context, 0, false);
185  }
186 }
187 
188 /*
189  * MemoryContextResetChildren
190  * Release all space allocated within a context's descendants,
191  * but don't delete the contexts themselves. The named context
192  * itself is not touched.
193  */
194 void
196 {
197  MemoryContext child;
198 
200 
201  for (child = context->firstchild; child != NULL; child = child->nextchild)
202  {
204  MemoryContextResetOnly(child);
205  }
206 }
207 
208 /*
209  * MemoryContextDelete
210  * Delete a context and its descendants, and release all space
211  * allocated therein.
212  *
213  * The type-specific delete routine removes all storage for the context,
214  * but we have to recurse to handle the children.
215  * We must also delink the context from its parent, if it has one.
216  */
217 void
219 {
221  /* We had better not be deleting TopMemoryContext ... */
222  Assert(context != TopMemoryContext);
223  /* And not CurrentMemoryContext, either */
224  Assert(context != CurrentMemoryContext);
225 
226  /* save a function call in common case where there are no children */
227  if (context->firstchild != NULL)
229 
230  /*
231  * It's not entirely clear whether 'tis better to do this before or after
232  * delinking the context; but an error in a callback will likely result in
233  * leaking the whole context (if it's not a root context) if we do it
234  * after, so let's do it before.
235  */
237 
238  /*
239  * We delink the context from its parent before deleting it, so that if
240  * there's an error we won't have deleted/busted contexts still attached
241  * to the context tree. Better a leak than a crash.
242  */
243  MemoryContextSetParent(context, NULL);
244 
245  /*
246  * Also reset the context's ident pointer, in case it points into the
247  * context. This would only matter if someone tries to get stats on the
248  * (already unlinked) context, which is unlikely, but let's be safe.
249  */
250  context->ident = NULL;
251 
252  context->methods->delete_context(context);
253 
254  VALGRIND_DESTROY_MEMPOOL(context);
255 }
256 
257 /*
258  * MemoryContextDeleteChildren
259  * Delete all the descendants of the named context and release all
260  * space allocated therein. The named context itself is not touched.
261  */
262 void
264 {
266 
267  /*
268  * MemoryContextDelete will delink the child from me, so just iterate as
269  * long as there is a child.
270  */
271  while (context->firstchild != NULL)
273 }
274 
275 /*
276  * MemoryContextRegisterResetCallback
277  * Register a function to be called before next context reset/delete.
278  * Such callbacks will be called in reverse order of registration.
279  *
280  * The caller is responsible for allocating a MemoryContextCallback struct
281  * to hold the info about this callback request, and for filling in the
282  * "func" and "arg" fields in the struct to show what function to call with
283  * what argument. Typically the callback struct should be allocated within
284  * the specified context, since that means it will automatically be freed
285  * when no longer needed.
286  *
287  * There is no API for deregistering a callback once registered. If you
288  * want it to not do anything anymore, adjust the state pointed to by its
289  * "arg" to indicate that.
290  */
291 void
294 {
296 
297  /* Push onto head so this will be called before older registrants. */
298  cb->next = context->reset_cbs;
299  context->reset_cbs = cb;
300  /* Mark the context as non-reset (it probably is already). */
301  context->isReset = false;
302 }
303 
304 /*
305  * MemoryContextCallResetCallbacks
306  * Internal function to call all registered callbacks for context.
307  */
308 static void
310 {
312 
313  /*
314  * We pop each callback from the list before calling. That way, if an
315  * error occurs inside the callback, we won't try to call it a second time
316  * in the likely event that we reset or delete the context later.
317  */
318  while ((cb = context->reset_cbs) != NULL)
319  {
320  context->reset_cbs = cb->next;
321  cb->func(cb->arg);
322  }
323 }
324 
325 /*
326  * MemoryContextSetIdentifier
327  * Set the identifier string for a memory context.
328  *
329  * An identifier can be provided to help distinguish among different contexts
330  * of the same kind in memory context stats dumps. The identifier string
331  * must live at least as long as the context it is for; typically it is
332  * allocated inside that context, so that it automatically goes away on
333  * context deletion. Pass id = NULL to forget any old identifier.
334  */
335 void
337 {
339  context->ident = id;
340 }
341 
342 /*
343  * MemoryContextSetParent
344  * Change a context to belong to a new parent (or no parent).
345  *
346  * We provide this as an API function because it is sometimes useful to
347  * change a context's lifespan after creation. For example, a context
348  * might be created underneath a transient context, filled with data,
349  * and then reparented underneath CacheMemoryContext to make it long-lived.
350  * In this way no special effort is needed to get rid of the context in case
351  * a failure occurs before its contents are completely set up.
352  *
353  * Callers often assume that this function cannot fail, so don't put any
354  * elog(ERROR) calls in it.
355  *
356  * A possible caller error is to reparent a context under itself, creating
357  * a loop in the context graph. We assert here that context != new_parent,
358  * but checking for multi-level loops seems more trouble than it's worth.
359  */
360 void
362 {
364  AssertArg(context != new_parent);
365 
366  /* Fast path if it's got correct parent already */
367  if (new_parent == context->parent)
368  return;
369 
370  /* Delink from existing parent, if any */
371  if (context->parent)
372  {
373  MemoryContext parent = context->parent;
374 
375  if (context->prevchild != NULL)
376  context->prevchild->nextchild = context->nextchild;
377  else
378  {
379  Assert(parent->firstchild == context);
380  parent->firstchild = context->nextchild;
381  }
382 
383  if (context->nextchild != NULL)
384  context->nextchild->prevchild = context->prevchild;
385  }
386 
387  /* And relink */
388  if (new_parent)
389  {
390  AssertArg(MemoryContextIsValid(new_parent));
391  context->parent = new_parent;
392  context->prevchild = NULL;
393  context->nextchild = new_parent->firstchild;
394  if (new_parent->firstchild != NULL)
395  new_parent->firstchild->prevchild = context;
396  new_parent->firstchild = context;
397  }
398  else
399  {
400  context->parent = NULL;
401  context->prevchild = NULL;
402  context->nextchild = NULL;
403  }
404 }
405 
406 /*
407  * MemoryContextAllowInCriticalSection
408  * Allow/disallow allocations in this memory context within a critical
409  * section.
410  *
411  * Normally, memory allocations are not allowed within a critical section,
412  * because a failure would lead to PANIC. There are a few exceptions to
413  * that, like allocations related to debugging code that is not supposed to
414  * be enabled in production. This function can be used to exempt specific
415  * memory contexts from the assertion in palloc().
416  */
417 void
419 {
421 
422  context->allowInCritSection = allow;
423 }
424 
425 /*
426  * GetMemoryChunkSpace
427  * Given a currently-allocated chunk, determine the total space
428  * it occupies (including all memory-allocation overhead).
429  *
430  * This is useful for measuring the total space occupied by a set of
431  * allocated chunks.
432  */
433 Size
434 GetMemoryChunkSpace(void *pointer)
435 {
436  MemoryContext context = GetMemoryChunkContext(pointer);
437 
438  return context->methods->get_chunk_space(context, pointer);
439 }
440 
441 /*
442  * MemoryContextGetParent
443  * Get the parent context (if any) of the specified context
444  */
447 {
449 
450  return context->parent;
451 }
452 
453 /*
454  * MemoryContextIsEmpty
455  * Is a memory context empty of any allocated space?
456  */
457 bool
459 {
461 
462  /*
463  * For now, we consider a memory context nonempty if it has any children;
464  * perhaps this should be changed later.
465  */
466  if (context->firstchild != NULL)
467  return false;
468  /* Otherwise use the type-specific inquiry */
469  return context->methods->is_empty(context);
470 }
471 
472 /*
473  * Find the memory allocated to blocks for this memory context. If recurse is
474  * true, also include children.
475  */
476 Size
478 {
479  Size total = context->mem_allocated;
480 
482 
483  if (recurse)
484  {
485  MemoryContext child;
486 
487  for (child = context->firstchild;
488  child != NULL;
489  child = child->nextchild)
490  total += MemoryContextMemAllocated(child, true);
491  }
492 
493  return total;
494 }
495 
496 /*
497  * MemoryContextStats
498  * Print statistics about the named context and all its descendants.
499  *
500  * This is just a debugging utility, so it's not very fancy. However, we do
501  * make some effort to summarize when the output would otherwise be very long.
502  * The statistics are sent to stderr.
503  */
504 void
506 {
507  /* A hard-wired limit on the number of children is usually good enough */
508  MemoryContextStatsDetail(context, 100, true);
509 }
510 
511 /*
512  * MemoryContextStatsDetail
513  *
514  * Entry point for use if you want to vary the number of child contexts shown.
515  *
516  * If print_to_stderr is true, print statistics about the memory contexts
517  * with fprintf(stderr), otherwise use ereport().
518  */
519 void
520 MemoryContextStatsDetail(MemoryContext context, int max_children,
521  bool print_to_stderr)
522 {
523  MemoryContextCounters grand_totals;
524 
525  memset(&grand_totals, 0, sizeof(grand_totals));
526 
527  MemoryContextStatsInternal(context, 0, true, max_children, &grand_totals, print_to_stderr);
528 
529  if (print_to_stderr)
530  fprintf(stderr,
531  "Grand total: %zu bytes in %zu blocks; %zu free (%zu chunks); %zu used\n",
532  grand_totals.totalspace, grand_totals.nblocks,
533  grand_totals.freespace, grand_totals.freechunks,
534  grand_totals.totalspace - grand_totals.freespace);
535  else
536 
537  /*
538  * Use LOG_SERVER_ONLY to prevent the memory contexts from being sent
539  * to the connected client.
540  *
541  * We don't buffer the information about all memory contexts in a
542  * backend into StringInfo and log it as one message. Otherwise which
543  * may require the buffer to be enlarged very much and lead to OOM
544  * error since there can be a large number of memory contexts in a
545  * backend. Instead, we log one message per memory context.
546  */
548  (errhidestmt(true),
549  errhidecontext(true),
550  errmsg_internal("Grand total: %zu bytes in %zu blocks; %zu free (%zu chunks); %zu used",
551  grand_totals.totalspace, grand_totals.nblocks,
552  grand_totals.freespace, grand_totals.freechunks,
553  grand_totals.totalspace - grand_totals.freespace)));
554 }
555 
556 /*
557  * MemoryContextStatsInternal
558  * One recursion level for MemoryContextStats
559  *
560  * Print this context if print is true, but in any case accumulate counts into
561  * *totals (if given).
562  */
563 static void
565  bool print, int max_children,
566  MemoryContextCounters *totals,
567  bool print_to_stderr)
568 {
569  MemoryContextCounters local_totals;
570  MemoryContext child;
571  int ichild;
572 
574 
575  /* Examine the context itself */
576  context->methods->stats(context,
578  (void *) &level,
579  totals, print_to_stderr);
580 
581  /*
582  * Examine children. If there are more than max_children of them, we do
583  * not print the rest explicitly, but just summarize them.
584  */
585  memset(&local_totals, 0, sizeof(local_totals));
586 
587  for (child = context->firstchild, ichild = 0;
588  child != NULL;
589  child = child->nextchild, ichild++)
590  {
591  if (ichild < max_children)
592  MemoryContextStatsInternal(child, level + 1,
593  print, max_children,
594  totals,
595  print_to_stderr);
596  else
597  MemoryContextStatsInternal(child, level + 1,
598  false, max_children,
599  &local_totals,
600  print_to_stderr);
601  }
602 
603  /* Deal with excess children */
604  if (ichild > max_children)
605  {
606  if (print)
607  {
608  if (print_to_stderr)
609  {
610  int i;
611 
612  for (i = 0; i <= level; i++)
613  fprintf(stderr, " ");
614  fprintf(stderr,
615  "%d more child contexts containing %zu total in %zu blocks; %zu free (%zu chunks); %zu used\n",
616  ichild - max_children,
617  local_totals.totalspace,
618  local_totals.nblocks,
619  local_totals.freespace,
620  local_totals.freechunks,
621  local_totals.totalspace - local_totals.freespace);
622  }
623  else
625  (errhidestmt(true),
626  errhidecontext(true),
627  errmsg_internal("level: %d; %d more child contexts containing %zu total in %zu blocks; %zu free (%zu chunks); %zu used",
628  level,
629  ichild - max_children,
630  local_totals.totalspace,
631  local_totals.nblocks,
632  local_totals.freespace,
633  local_totals.freechunks,
634  local_totals.totalspace - local_totals.freespace)));
635  }
636 
637  if (totals)
638  {
639  totals->nblocks += local_totals.nblocks;
640  totals->freechunks += local_totals.freechunks;
641  totals->totalspace += local_totals.totalspace;
642  totals->freespace += local_totals.freespace;
643  }
644  }
645 }
646 
647 /*
648  * MemoryContextStatsPrint
649  * Print callback used by MemoryContextStatsInternal
650  *
651  * For now, the passthru pointer just points to "int level"; later we might
652  * make that more complicated.
653  */
654 static void
655 MemoryContextStatsPrint(MemoryContext context, void *passthru,
656  const char *stats_string,
657  bool print_to_stderr)
658 {
659  int level = *(int *) passthru;
660  const char *name = context->name;
661  const char *ident = context->ident;
662  char truncated_ident[110];
663  int i;
664 
665  /*
666  * It seems preferable to label dynahash contexts with just the hash table
667  * name. Those are already unique enough, so the "dynahash" part isn't
668  * very helpful, and this way is more consistent with pre-v11 practice.
669  */
670  if (ident && strcmp(name, "dynahash") == 0)
671  {
672  name = ident;
673  ident = NULL;
674  }
675 
676  truncated_ident[0] = '\0';
677 
678  if (ident)
679  {
680  /*
681  * Some contexts may have very long identifiers (e.g., SQL queries).
682  * Arbitrarily truncate at 100 bytes, but be careful not to break
683  * multibyte characters. Also, replace ASCII control characters, such
684  * as newlines, with spaces.
685  */
686  int idlen = strlen(ident);
687  bool truncated = false;
688 
689  strcpy(truncated_ident, ": ");
690  i = strlen(truncated_ident);
691 
692  if (idlen > 100)
693  {
694  idlen = pg_mbcliplen(ident, idlen, 100);
695  truncated = true;
696  }
697 
698  while (idlen-- > 0)
699  {
700  unsigned char c = *ident++;
701 
702  if (c < ' ')
703  c = ' ';
704  truncated_ident[i++] = c;
705  }
706  truncated_ident[i] = '\0';
707 
708  if (truncated)
709  strcat(truncated_ident, "...");
710  }
711 
712  if (print_to_stderr)
713  {
714  for (i = 0; i < level; i++)
715  fprintf(stderr, " ");
716  fprintf(stderr, "%s: %s%s\n", name, stats_string, truncated_ident);
717  }
718  else
720  (errhidestmt(true),
721  errhidecontext(true),
722  errmsg_internal("level: %d; %s: %s%s",
723  level, name, stats_string, truncated_ident)));
724 }
725 
726 /*
727  * MemoryContextCheck
728  * Check all chunks in the named context.
729  *
730  * This is just a debugging utility, so it's not fancy.
731  */
732 #ifdef MEMORY_CONTEXT_CHECKING
733 void
734 MemoryContextCheck(MemoryContext context)
735 {
736  MemoryContext child;
737 
739 
740  context->methods->check(context);
741  for (child = context->firstchild; child != NULL; child = child->nextchild)
742  MemoryContextCheck(child);
743 }
744 #endif
745 
746 /*
747  * MemoryContextContains
748  * Detect whether an allocated chunk of memory belongs to a given
749  * context or not.
750  *
751  * Caution: this test is reliable as long as 'pointer' does point to
752  * a chunk of memory allocated from *some* context. If 'pointer' points
753  * at memory obtained in some other way, there is a small chance of a
754  * false-positive result, since the bits right before it might look like
755  * a valid chunk header by chance.
756  */
757 bool
758 MemoryContextContains(MemoryContext context, void *pointer)
759 {
760  MemoryContext ptr_context;
761 
762  /*
763  * NB: Can't use GetMemoryChunkContext() here - that performs assertions
764  * that aren't acceptable here since we might be passed memory not
765  * allocated by any memory context.
766  *
767  * Try to detect bogus pointers handed to us, poorly though we can.
768  * Presumably, a pointer that isn't MAXALIGNED isn't pointing at an
769  * allocated chunk.
770  */
771  if (pointer == NULL || pointer != (void *) MAXALIGN(pointer))
772  return false;
773 
774  /*
775  * OK, it's probably safe to look at the context.
776  */
777  ptr_context = *(MemoryContext *) (((char *) pointer) - sizeof(void *));
778 
779  return ptr_context == context;
780 }
781 
782 /*
783  * MemoryContextCreate
784  * Context-type-independent part of context creation.
785  *
786  * This is only intended to be called by context-type-specific
787  * context creation routines, not by the unwashed masses.
788  *
789  * The memory context creation procedure goes like this:
790  * 1. Context-type-specific routine makes some initial space allocation,
791  * including enough space for the context header. If it fails,
792  * it can ereport() with no damage done.
793  * 2. Context-type-specific routine sets up all type-specific fields of
794  * the header (those beyond MemoryContextData proper), as well as any
795  * other management fields it needs to have a fully valid context.
796  * Usually, failure in this step is impossible, but if it's possible
797  * the initial space allocation should be freed before ereport'ing.
798  * 3. Context-type-specific routine calls MemoryContextCreate() to fill in
799  * the generic header fields and link the context into the context tree.
800  * 4. We return to the context-type-specific routine, which finishes
801  * up type-specific initialization. This routine can now do things
802  * that might fail (like allocate more memory), so long as it's
803  * sure the node is left in a state that delete will handle.
804  *
805  * node: the as-yet-uninitialized common part of the context header node.
806  * tag: NodeTag code identifying the memory context type.
807  * methods: context-type-specific methods (usually statically allocated).
808  * parent: parent context, or NULL if this will be a top-level context.
809  * name: name of context (must be statically allocated).
810  *
811  * Context routines generally assume that MemoryContextCreate can't fail,
812  * so this can contain Assert but not elog/ereport.
813  */
814 void
816  NodeTag tag,
817  const MemoryContextMethods *methods,
818  MemoryContext parent,
819  const char *name)
820 {
821  /* Creating new memory contexts is not allowed in a critical section */
822  Assert(CritSectionCount == 0);
823 
824  /* Initialize all standard fields of memory context header */
825  node->type = tag;
826  node->isReset = true;
827  node->methods = methods;
828  node->parent = parent;
829  node->firstchild = NULL;
830  node->mem_allocated = 0;
831  node->prevchild = NULL;
832  node->name = name;
833  node->ident = NULL;
834  node->reset_cbs = NULL;
835 
836  /* OK to link node into context tree */
837  if (parent)
838  {
839  node->nextchild = parent->firstchild;
840  if (parent->firstchild != NULL)
841  parent->firstchild->prevchild = node;
842  parent->firstchild = node;
843  /* inherit allowInCritSection flag from parent */
844  node->allowInCritSection = parent->allowInCritSection;
845  }
846  else
847  {
848  node->nextchild = NULL;
849  node->allowInCritSection = false;
850  }
851 
852  VALGRIND_CREATE_MEMPOOL(node, 0, false);
853 }
854 
855 /*
856  * MemoryContextAlloc
857  * Allocate space within the specified context.
858  *
859  * This could be turned into a macro, but we'd have to import
860  * nodes/memnodes.h into postgres.h which seems a bad idea.
861  */
862 void *
864 {
865  void *ret;
866 
869 
870  if (!AllocSizeIsValid(size))
871  elog(ERROR, "invalid memory alloc request size %zu", size);
872 
873  context->isReset = false;
874 
875  ret = context->methods->alloc(context, size);
876  if (unlikely(ret == NULL))
877  {
879 
880  /*
881  * Here, and elsewhere in this module, we show the target context's
882  * "name" but not its "ident" (if any) in user-visible error messages.
883  * The "ident" string might contain security-sensitive data, such as
884  * values in SQL commands.
885  */
886  ereport(ERROR,
887  (errcode(ERRCODE_OUT_OF_MEMORY),
888  errmsg("out of memory"),
889  errdetail("Failed on request of size %zu in memory context \"%s\".",
890  size, context->name)));
891  }
892 
893  VALGRIND_MEMPOOL_ALLOC(context, ret, size);
894 
895  return ret;
896 }
897 
898 /*
899  * MemoryContextAllocZero
900  * Like MemoryContextAlloc, but clears allocated memory
901  *
902  * We could just call MemoryContextAlloc then clear the memory, but this
903  * is a very common combination, so we provide the combined operation.
904  */
905 void *
907 {
908  void *ret;
909 
912 
913  if (!AllocSizeIsValid(size))
914  elog(ERROR, "invalid memory alloc request size %zu", size);
915 
916  context->isReset = false;
917 
918  ret = context->methods->alloc(context, size);
919  if (unlikely(ret == NULL))
920  {
922  ereport(ERROR,
923  (errcode(ERRCODE_OUT_OF_MEMORY),
924  errmsg("out of memory"),
925  errdetail("Failed on request of size %zu in memory context \"%s\".",
926  size, context->name)));
927  }
928 
929  VALGRIND_MEMPOOL_ALLOC(context, ret, size);
930 
931  MemSetAligned(ret, 0, size);
932 
933  return ret;
934 }
935 
936 /*
937  * MemoryContextAllocZeroAligned
938  * MemoryContextAllocZero where length is suitable for MemSetLoop
939  *
940  * This might seem overly specialized, but it's not because newNode()
941  * is so often called with compile-time-constant sizes.
942  */
943 void *
945 {
946  void *ret;
947 
950 
951  if (!AllocSizeIsValid(size))
952  elog(ERROR, "invalid memory alloc request size %zu", size);
953 
954  context->isReset = false;
955 
956  ret = context->methods->alloc(context, size);
957  if (unlikely(ret == NULL))
958  {
960  ereport(ERROR,
961  (errcode(ERRCODE_OUT_OF_MEMORY),
962  errmsg("out of memory"),
963  errdetail("Failed on request of size %zu in memory context \"%s\".",
964  size, context->name)));
965  }
966 
967  VALGRIND_MEMPOOL_ALLOC(context, ret, size);
968 
969  MemSetLoop(ret, 0, size);
970 
971  return ret;
972 }
973 
974 /*
975  * MemoryContextAllocExtended
976  * Allocate space within the specified context using the given flags.
977  */
978 void *
980 {
981  void *ret;
982 
985 
986  if (((flags & MCXT_ALLOC_HUGE) != 0 && !AllocHugeSizeIsValid(size)) ||
987  ((flags & MCXT_ALLOC_HUGE) == 0 && !AllocSizeIsValid(size)))
988  elog(ERROR, "invalid memory alloc request size %zu", size);
989 
990  context->isReset = false;
991 
992  ret = context->methods->alloc(context, size);
993  if (unlikely(ret == NULL))
994  {
995  if ((flags & MCXT_ALLOC_NO_OOM) == 0)
996  {
998  ereport(ERROR,
999  (errcode(ERRCODE_OUT_OF_MEMORY),
1000  errmsg("out of memory"),
1001  errdetail("Failed on request of size %zu in memory context \"%s\".",
1002  size, context->name)));
1003  }
1004  return NULL;
1005  }
1006 
1007  VALGRIND_MEMPOOL_ALLOC(context, ret, size);
1008 
1009  if ((flags & MCXT_ALLOC_ZERO) != 0)
1010  MemSetAligned(ret, 0, size);
1011 
1012  return ret;
1013 }
1014 
1015 /*
1016  * HandleLogMemoryContextInterrupt
1017  * Handle receipt of an interrupt indicating logging of memory
1018  * contexts.
1019  *
1020  * All the actual work is deferred to ProcessLogMemoryContextInterrupt(),
1021  * because we cannot safely emit a log message inside the signal handler.
1022  */
1023 void
1025 {
1026  InterruptPending = true;
1027  LogMemoryContextPending = true;
1028  /* latch will be set by procsignal_sigusr1_handler */
1029 }
1030 
1031 /*
1032  * ProcessLogMemoryContextInterrupt
1033  * Perform logging of memory contexts of this backend process.
1034  *
1035  * Any backend that participates in ProcSignal signaling must arrange
1036  * to call this function if we see LogMemoryContextPending set.
1037  * It is called from CHECK_FOR_INTERRUPTS(), which is enough because
1038  * the target process for logging of memory contexts is a backend.
1039  */
1040 void
1042 {
1043  LogMemoryContextPending = false;
1044 
1045  /*
1046  * Use LOG_SERVER_ONLY to prevent this message from being sent to the
1047  * connected client.
1048  */
1050  (errhidestmt(true),
1051  errhidecontext(true),
1052  errmsg("logging memory contexts of PID %d", MyProcPid)));
1053 
1054  /*
1055  * When a backend process is consuming huge memory, logging all its memory
1056  * contexts might overrun available disk space. To prevent this, we limit
1057  * the number of child contexts to log per parent to 100.
1058  *
1059  * As with MemoryContextStats(), we suppose that practical cases where the
1060  * dump gets long will typically be huge numbers of siblings under the
1061  * same parent context; while the additional debugging value from seeing
1062  * details about individual siblings beyond 100 will not be large.
1063  */
1065 }
1066 
1067 void *
1069 {
1070  /* duplicates MemoryContextAlloc to avoid increased overhead */
1071  void *ret;
1073 
1074  AssertArg(MemoryContextIsValid(context));
1075  AssertNotInCriticalSection(context);
1076 
1077  if (!AllocSizeIsValid(size))
1078  elog(ERROR, "invalid memory alloc request size %zu", size);
1079 
1080  context->isReset = false;
1081 
1082  ret = context->methods->alloc(context, size);
1083  if (unlikely(ret == NULL))
1084  {
1086  ereport(ERROR,
1087  (errcode(ERRCODE_OUT_OF_MEMORY),
1088  errmsg("out of memory"),
1089  errdetail("Failed on request of size %zu in memory context \"%s\".",
1090  size, context->name)));
1091  }
1092 
1093  VALGRIND_MEMPOOL_ALLOC(context, ret, size);
1094 
1095  return ret;
1096 }
1097 
1098 void *
1100 {
1101  /* duplicates MemoryContextAllocZero to avoid increased overhead */
1102  void *ret;
1104 
1105  AssertArg(MemoryContextIsValid(context));
1106  AssertNotInCriticalSection(context);
1107 
1108  if (!AllocSizeIsValid(size))
1109  elog(ERROR, "invalid memory alloc request size %zu", size);
1110 
1111  context->isReset = false;
1112 
1113  ret = context->methods->alloc(context, size);
1114  if (unlikely(ret == NULL))
1115  {
1117  ereport(ERROR,
1118  (errcode(ERRCODE_OUT_OF_MEMORY),
1119  errmsg("out of memory"),
1120  errdetail("Failed on request of size %zu in memory context \"%s\".",
1121  size, context->name)));
1122  }
1123 
1124  VALGRIND_MEMPOOL_ALLOC(context, ret, size);
1125 
1126  MemSetAligned(ret, 0, size);
1127 
1128  return ret;
1129 }
1130 
1131 void *
1132 palloc_extended(Size size, int flags)
1133 {
1134  /* duplicates MemoryContextAllocExtended to avoid increased overhead */
1135  void *ret;
1137 
1138  AssertArg(MemoryContextIsValid(context));
1139  AssertNotInCriticalSection(context);
1140 
1141  if (((flags & MCXT_ALLOC_HUGE) != 0 && !AllocHugeSizeIsValid(size)) ||
1142  ((flags & MCXT_ALLOC_HUGE) == 0 && !AllocSizeIsValid(size)))
1143  elog(ERROR, "invalid memory alloc request size %zu", size);
1144 
1145  context->isReset = false;
1146 
1147  ret = context->methods->alloc(context, size);
1148  if (unlikely(ret == NULL))
1149  {
1150  if ((flags & MCXT_ALLOC_NO_OOM) == 0)
1151  {
1153  ereport(ERROR,
1154  (errcode(ERRCODE_OUT_OF_MEMORY),
1155  errmsg("out of memory"),
1156  errdetail("Failed on request of size %zu in memory context \"%s\".",
1157  size, context->name)));
1158  }
1159  return NULL;
1160  }
1161 
1162  VALGRIND_MEMPOOL_ALLOC(context, ret, size);
1163 
1164  if ((flags & MCXT_ALLOC_ZERO) != 0)
1165  MemSetAligned(ret, 0, size);
1166 
1167  return ret;
1168 }
1169 
1170 /*
1171  * pfree
1172  * Release an allocated chunk.
1173  */
1174 void
1175 pfree(void *pointer)
1176 {
1177  MemoryContext context = GetMemoryChunkContext(pointer);
1178 
1179  context->methods->free_p(context, pointer);
1180  VALGRIND_MEMPOOL_FREE(context, pointer);
1181 }
1182 
1183 /*
1184  * repalloc
1185  * Adjust the size of a previously allocated chunk.
1186  */
1187 void *
1188 repalloc(void *pointer, Size size)
1189 {
1190  MemoryContext context = GetMemoryChunkContext(pointer);
1191  void *ret;
1192 
1193  if (!AllocSizeIsValid(size))
1194  elog(ERROR, "invalid memory alloc request size %zu", size);
1195 
1196  AssertNotInCriticalSection(context);
1197 
1198  /* isReset must be false already */
1199  Assert(!context->isReset);
1200 
1201  ret = context->methods->realloc(context, pointer, size);
1202  if (unlikely(ret == NULL))
1203  {
1205  ereport(ERROR,
1206  (errcode(ERRCODE_OUT_OF_MEMORY),
1207  errmsg("out of memory"),
1208  errdetail("Failed on request of size %zu in memory context \"%s\".",
1209  size, context->name)));
1210  }
1211 
1212  VALGRIND_MEMPOOL_CHANGE(context, pointer, ret, size);
1213 
1214  return ret;
1215 }
1216 
1217 /*
1218  * MemoryContextAllocHuge
1219  * Allocate (possibly-expansive) space within the specified context.
1220  *
1221  * See considerations in comment at MaxAllocHugeSize.
1222  */
1223 void *
1225 {
1226  void *ret;
1227 
1228  AssertArg(MemoryContextIsValid(context));
1229  AssertNotInCriticalSection(context);
1230 
1231  if (!AllocHugeSizeIsValid(size))
1232  elog(ERROR, "invalid memory alloc request size %zu", size);
1233 
1234  context->isReset = false;
1235 
1236  ret = context->methods->alloc(context, size);
1237  if (unlikely(ret == NULL))
1238  {
1240  ereport(ERROR,
1241  (errcode(ERRCODE_OUT_OF_MEMORY),
1242  errmsg("out of memory"),
1243  errdetail("Failed on request of size %zu in memory context \"%s\".",
1244  size, context->name)));
1245  }
1246 
1247  VALGRIND_MEMPOOL_ALLOC(context, ret, size);
1248 
1249  return ret;
1250 }
1251 
1252 /*
1253  * repalloc_huge
1254  * Adjust the size of a previously allocated chunk, permitting a large
1255  * value. The previous allocation need not have been "huge".
1256  */
1257 void *
1258 repalloc_huge(void *pointer, Size size)
1259 {
1260  MemoryContext context = GetMemoryChunkContext(pointer);
1261  void *ret;
1262 
1263  if (!AllocHugeSizeIsValid(size))
1264  elog(ERROR, "invalid memory alloc request size %zu", size);
1265 
1266  AssertNotInCriticalSection(context);
1267 
1268  /* isReset must be false already */
1269  Assert(!context->isReset);
1270 
1271  ret = context->methods->realloc(context, pointer, size);
1272  if (unlikely(ret == NULL))
1273  {
1275  ereport(ERROR,
1276  (errcode(ERRCODE_OUT_OF_MEMORY),
1277  errmsg("out of memory"),
1278  errdetail("Failed on request of size %zu in memory context \"%s\".",
1279  size, context->name)));
1280  }
1281 
1282  VALGRIND_MEMPOOL_CHANGE(context, pointer, ret, size);
1283 
1284  return ret;
1285 }
1286 
1287 /*
1288  * MemoryContextStrdup
1289  * Like strdup(), but allocate from the specified context
1290  */
1291 char *
1292 MemoryContextStrdup(MemoryContext context, const char *string)
1293 {
1294  char *nstr;
1295  Size len = strlen(string) + 1;
1296 
1297  nstr = (char *) MemoryContextAlloc(context, len);
1298 
1299  memcpy(nstr, string, len);
1300 
1301  return nstr;
1302 }
1303 
1304 char *
1305 pstrdup(const char *in)
1306 {
1308 }
1309 
1310 /*
1311  * pnstrdup
1312  * Like pstrdup(), but append null byte to a
1313  * not-necessarily-null-terminated input string.
1314  */
1315 char *
1316 pnstrdup(const char *in, Size len)
1317 {
1318  char *out;
1319 
1320  len = strnlen(in, len);
1321 
1322  out = palloc(len + 1);
1323  memcpy(out, in, len);
1324  out[len] = '\0';
1325 
1326  return out;
1327 }
1328 
1329 /*
1330  * Make copy of string with all trailing newline characters removed.
1331  */
1332 char *
1333 pchomp(const char *in)
1334 {
1335  size_t n;
1336 
1337  n = strlen(in);
1338  while (n > 0 && in[n - 1] == '\n')
1339  n--;
1340  return pnstrdup(in, n);
1341 }
void print(const void *obj)
Definition: print.c:36
#define AssertState(condition)
Definition: c.h:807
#define MAXALIGN(LEN)
Definition: c.h:757
#define MemSetAligned(start, val, len)
Definition: c.h:1038
#define unlikely(x)
Definition: c.h:273
size_t Size
Definition: c.h:540
#define MemSetLoop(start, val, len)
Definition: c.h:1073
#define AssertArg(condition)
Definition: c.h:806
int errmsg_internal(const char *fmt,...)
Definition: elog.c:991
int errhidestmt(bool hide_stmt)
Definition: elog.c:1245
int errdetail(const char *fmt,...)
Definition: elog.c:1037
int errhidecontext(bool hide_ctx)
Definition: elog.c:1264
int errcode(int sqlerrcode)
Definition: elog.c:693
int errmsg(const char *fmt,...)
Definition: elog.c:904
#define LOG_SERVER_ONLY
Definition: elog.h:26
#define ERROR
Definition: elog.h:33
#define elog(elevel,...)
Definition: elog.h:218
#define ereport(elevel,...)
Definition: elog.h:143
const char * name
Definition: encode.c:561
#define MCXT_ALLOC_ZERO
Definition: fe_memutils.h:18
#define MCXT_ALLOC_HUGE
Definition: fe_memutils.h:16
#define MCXT_ALLOC_NO_OOM
Definition: fe_memutils.h:17
volatile sig_atomic_t LogMemoryContextPending
Definition: globals.c:38
volatile sig_atomic_t InterruptPending
Definition: globals.c:30
int MyProcPid
Definition: globals.c:44
volatile uint32 CritSectionCount
Definition: globals.c:42
int i
Definition: isn.c:73
Assert(fmt[strlen(fmt) - 1] !='\n')
int pg_mbcliplen(const char *mbstr, int len, int limit)
Definition: mbutils.c:1026
char * pnstrdup(const char *in, Size len)
Definition: mcxt.c:1316
static void MemoryContextCallResetCallbacks(MemoryContext context)
Definition: mcxt.c:309
MemoryContext MessageContext
Definition: mcxt.c:52
bool MemoryContextIsEmpty(MemoryContext context)
Definition: mcxt.c:458
void MemoryContextReset(MemoryContext context)
Definition: mcxt.c:143
MemoryContext TopTransactionContext
Definition: mcxt.c:53
char * pchomp(const char *in)
Definition: mcxt.c:1333
void HandleLogMemoryContextInterrupt(void)
Definition: mcxt.c:1024
void MemoryContextRegisterResetCallback(MemoryContext context, MemoryContextCallback *cb)
Definition: mcxt.c:292
void MemoryContextSetParent(MemoryContext context, MemoryContext new_parent)
Definition: mcxt.c:361
void MemoryContextStatsDetail(MemoryContext context, int max_children, bool print_to_stderr)
Definition: mcxt.c:520
char * pstrdup(const char *in)
Definition: mcxt.c:1305
void pfree(void *pointer)
Definition: mcxt.c:1175
Size GetMemoryChunkSpace(void *pointer)
Definition: mcxt.c:434
void MemoryContextDeleteChildren(MemoryContext context)
Definition: mcxt.c:263
MemoryContext TopMemoryContext
Definition: mcxt.c:48
#define AssertNotInCriticalSection(context)
Definition: mcxt.c:73
void * palloc0(Size size)
Definition: mcxt.c:1099
void * MemoryContextAllocZero(MemoryContext context, Size size)
Definition: mcxt.c:906
MemoryContext CurTransactionContext
Definition: mcxt.c:54
void * MemoryContextAllocExtended(MemoryContext context, Size size, int flags)
Definition: mcxt.c:979
MemoryContext CurrentMemoryContext
Definition: mcxt.c:42
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:1188
void * palloc_extended(Size size, int flags)
Definition: mcxt.c:1132
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:863
void * MemoryContextAllocZeroAligned(MemoryContext context, Size size)
Definition: mcxt.c:944
Size MemoryContextMemAllocated(MemoryContext context, bool recurse)
Definition: mcxt.c:477
void MemoryContextStats(MemoryContext context)
Definition: mcxt.c:505
void MemoryContextInit(void)
Definition: mcxt.c:99
bool MemoryContextContains(MemoryContext context, void *pointer)
Definition: mcxt.c:758
MemoryContext PostmasterContext
Definition: mcxt.c:50
char * MemoryContextStrdup(MemoryContext context, const char *string)
Definition: mcxt.c:1292
static void MemoryContextStatsInternal(MemoryContext context, int level, bool print, int max_children, MemoryContextCounters *totals, bool print_to_stderr)
Definition: mcxt.c:564
MemoryContext MemoryContextGetParent(MemoryContext context)
Definition: mcxt.c:446
void ProcessLogMemoryContextInterrupt(void)
Definition: mcxt.c:1041
MemoryContext ErrorContext
Definition: mcxt.c:49
MemoryContext CacheMemoryContext
Definition: mcxt.c:51
void MemoryContextCreate(MemoryContext node, NodeTag tag, const MemoryContextMethods *methods, MemoryContext parent, const char *name)
Definition: mcxt.c:815
void * MemoryContextAllocHuge(MemoryContext context, Size size)
Definition: mcxt.c:1224
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:218
void MemoryContextAllowInCriticalSection(MemoryContext context, bool allow)
Definition: mcxt.c:418
void MemoryContextResetChildren(MemoryContext context)
Definition: mcxt.c:195
static void MemoryContextStatsPrint(MemoryContext context, void *passthru, const char *stats_string, bool print_to_stderr)
Definition: mcxt.c:655
void * palloc(Size size)
Definition: mcxt.c:1068
void MemoryContextSetIdentifier(MemoryContext context, const char *id)
Definition: mcxt.c:336
void MemoryContextResetOnly(MemoryContext context)
Definition: mcxt.c:162
MemoryContext PortalContext
Definition: mcxt.c:57
void * repalloc_huge(void *pointer, Size size)
Definition: mcxt.c:1258
#define VALGRIND_DESTROY_MEMPOOL(context)
Definition: memdebug.h:25
#define VALGRIND_MEMPOOL_CHANGE(context, optr, nptr, size)
Definition: memdebug.h:31
#define VALGRIND_CREATE_MEMPOOL(context, redzones, zeroed)
Definition: memdebug.h:24
#define VALGRIND_MEMPOOL_ALLOC(context, addr, size)
Definition: memdebug.h:29
#define VALGRIND_MEMPOOL_FREE(context, addr)
Definition: memdebug.h:30
#define MemoryContextIsValid(context)
Definition: memnodes.h:104
#define AllocSetContextCreate
Definition: memutils.h:173
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:197
#define AllocHugeSizeIsValid(size)
Definition: memutils.h:46
#define AllocSizeIsValid(size)
Definition: memutils.h:42
static MemoryContext GetMemoryChunkContext(void *pointer)
Definition: memutils.h:114
NodeTag
Definition: nodes.h:27
const void size_t len
#define fprintf
Definition: port.h:229
size_t strnlen(const char *str, size_t maxlen)
Definition: strnlen.c:26
char * c
struct MemoryContextCallback * next
Definition: palloc.h:51
MemoryContextCallbackFunction func
Definition: palloc.h:49
MemoryContext prevchild
Definition: memnodes.h:88
MemoryContext firstchild
Definition: memnodes.h:87
bool allowInCritSection
Definition: memnodes.h:83
const char * ident
Definition: memnodes.h:91
MemoryContext parent
Definition: memnodes.h:86
MemoryContextCallback * reset_cbs
Definition: memnodes.h:92
const MemoryContextMethods * methods
Definition: memnodes.h:85
NodeTag type
Definition: memnodes.h:80
MemoryContext nextchild
Definition: memnodes.h:89
Size mem_allocated
Definition: memnodes.h:84
const char * name
Definition: memnodes.h:90
Size(* get_chunk_space)(MemoryContext context, void *pointer)
Definition: memnodes.h:66
void(* delete_context)(MemoryContext context)
Definition: memnodes.h:65
void(* stats)(MemoryContext context, MemoryStatsPrintFunc printfunc, void *passthru, MemoryContextCounters *totals, bool print_to_stderr)
Definition: memnodes.h:68
void *(* realloc)(MemoryContext context, void *pointer, Size size)
Definition: memnodes.h:63
bool(* is_empty)(MemoryContext context)
Definition: memnodes.h:67
void(* reset)(MemoryContext context)
Definition: memnodes.h:64
void *(* alloc)(MemoryContext context, Size size)
Definition: memnodes.h:60
void(* free_p)(MemoryContext context, void *pointer)
Definition: memnodes.h:62