1 /*************************************************
2 * Exim - an Internet mail transport agent *
3 *************************************************/
5 /* Copyright (c) The Exim maintainers 2019 - 2022 */
6 /* Copyright (c) University of Cambridge 1995 - 2018 */
7 /* See the file NOTICE for conditions of use and distribution. */
9 /* Exim gets and frees all its store through these functions. In the original
10 implementation there was a lot of mallocing and freeing of small bits of store.
11 The philosophy has now changed to a scheme which includes the concept of
12 "stacking pools" of store. For the short-lived processes, there isn't any real
13 need to do any garbage collection, but the stack concept allows quick resetting
14 in places where this seems sensible.
16 Obviously the long-running processes (the daemon, the queue runner, and eximon)
17 must take care not to eat store.
19 The following different types of store are recognized:
21 . Long-lived, large blocks: This is implemented by retaining the original
22 malloc/free functions, and it used for permanent working buffers and for
23 getting blocks to cut up for the other types.
25 . Long-lived, small blocks: This is used for blocks that have to survive until
26 the process exits. It is implemented as a stacking pool (POOL_PERM). This is
27 functionally the same as store_malloc(), except that the store can't be
28 freed, but I expect it to be more efficient for handling small blocks.
30 . Short-lived, short blocks: Most of the dynamic store falls into this
31 category. It is implemented as a stacking pool (POOL_MAIN) which is reset
32 after accepting a message when multiple messages are received by a single
33 process. Resetting happens at some other times as well, usually fairly
34 locally after some specific processing that needs working store.
36 . There is a separate pool (POOL_SEARCH) that is used only for lookup storage.
37 This means it can be freed when search_tidyup() is called to close down all
40 - There is another pool (POOL_MESSAGE) used for medium-lifetime objects; within
41 a single message transaction but needed for longer than the use of the main
42 pool permits. Currently this means only receive-time DKIM information.
44 - There is a dedicated pool for configuration data read from the config file(s).
45 Once complete, it is made readonly.
47 - There are pools for each active combination of lookup-quoting, dynamically created.
49 . Orthogonal to the four main pool types, there are two classes of memory: untainted
50 and tainted. The latter is used for values derived from untrusted input, and
51 the string-expansion mechanism refuses to operate on such values (obviously,
52 it can expand an untainted value to return a tainted result). The classes
53 are implemented by duplicating the four pool types. Pool resets are requested
54 against the nontainted sibling and apply to both siblings.
56 Only memory blocks requested for tainted use are regarded as tainted; anything
57 else (including stack auto variables) is untainted. Care is needed when coding
58 to not copy untrusted data into untainted memory, as downstream taint-checks
61 Intermediate layers (eg. the string functions) can test for taint, and use this
62 for ensurinng that results have proper state. For example the
63 string_vformat_trc() routing supporting the string_sprintf() interface will
64 recopy a string being built into a tainted allocation if it meets a %s for a
65 tainted argument. Any intermediate-layer function that (can) return a new
66 allocation should behave this way; returning a tainted result if any tainted
67 content is used. Intermediate-layer functions (eg. Ustrncpy) that modify
68 existing allocations fail if tainted data is written into an untainted area.
69 Users of functions that modify existing allocations should check if a tainted
70 source and an untainted destination is used, and fail instead (sprintf() being
76 /* keep config.h before memcheck.h, for NVALGRIND */
83 /* We need to know how to align blocks of data for general use. I'm not sure
84 how to get an alignment factor in general. In the current world, a value of 8
85 is probably right, and this is sizeof(double) on some systems and sizeof(void
86 *) on others, so take the larger of those. Since everything in this expression
87 is a constant, the compiler should optimize it to a simple constant wherever it
88 appears (I checked that gcc does do this). */
91 (sizeof(void *) > sizeof(double) ? sizeof(void *) : sizeof(double))
93 /* store_reset() will not free the following block if the last used block has
94 less than this much left in it. */
96 #define STOREPOOL_MIN_SIZE 256
98 /* Structure describing the beginning of each big block. */
100 typedef struct storeblock {
101 struct storeblock *next;
105 /* Pool descriptor struct */
107 typedef struct pooldesc {
108 storeblock * chainbase; /* list of blocks in pool */
109 storeblock * current_block; /* top block, still with free space */
110 void * next_yield; /* next allocation point */
111 int yield_length; /* remaining space in current block */
112 unsigned store_block_order; /* log2(size) block allocation size */
114 /* This variable is set by store_get() to its yield, and by store_reset() to
115 NULL. This enables string_cat() to optimize its store handling for very long
116 strings. That's why the variable is global. */
118 void * store_last_get;
120 /* These are purely for stats-gathering */
129 /* Enhanced pool descriptor for quoted pools */
131 typedef struct quoted_pooldesc {
134 struct quoted_pooldesc * next;
137 /* Just in case we find ourselves on a system where the structure above has a
138 length that is not a multiple of the alignment, set up a macro for the padded
141 #define ALIGNED_SIZEOF_STOREBLOCK \
142 (((sizeof(storeblock) + alignment - 1) / alignment) * alignment)
144 /* Size of block to get from malloc to carve up into smaller ones. This
145 must be a multiple of the alignment. We assume that 4096 is going to be
146 suitably aligned. Double the size per-pool for every malloc, to mitigate
147 certain denial-of-service attacks. Don't bother to decrease on block frees.
148 We waste average half the current alloc size per pool. This could be several
149 hundred kB now, vs. 4kB with a constant-size block size. But the search time
150 for is_tainted(), linear in the number of blocks for the pool, is O(n log n)
152 A test of 2000 RCPTs and just accept ACL had 370kB in 21 blocks before,
153 504kB in 6 blocks now, for the untainted-main (largest) pool.
154 Builds for restricted-memory system can disable the expansion by
155 defining RESTRICTED_MEMORY */
156 /*XXX should we allow any for malloc's own overhead? But how much? */
158 /* #define RESTRICTED_MEMORY */
159 #define STORE_BLOCK_SIZE(order) ((1U << (order)) - ALIGNED_SIZEOF_STOREBLOCK)
161 /* Variables holding data for the local pools of store. The current pool number
162 is held in store_pool, which is global so that it can be changed from outside.
163 Setting the initial length values to -1 forces a malloc for the first call,
164 even if the length is zero (which is used for getting a point to reset to). */
166 int store_pool = POOL_MAIN;
168 pooldesc paired_pools[N_PAIRED_POOLS];
169 quoted_pooldesc * quoted_pools = NULL;
171 static int n_nonpool_blocks; /* current number of direct store_malloc() blocks */
172 static int max_nonpool_blocks;
173 static int max_pool_malloc; /* max value for pool_malloc */
174 static int max_nonpool_malloc; /* max value for nonpool_malloc */
176 /* pool_malloc holds the amount of memory used by the store pools; this goes up
177 and down as store is reset or released. nonpool_malloc is the total got by
178 malloc from other calls; this doesn't go down because it is just freed by
181 static int pool_malloc;
182 static int nonpool_malloc;
185 #ifndef COMPILE_UTILITY
186 static const uschar * pooluse[N_PAIRED_POOLS] = {
187 [POOL_MAIN] = US"main",
188 [POOL_PERM] = US"perm",
189 [POOL_CONFIG] = US"config",
190 [POOL_SEARCH] = US"search",
191 [POOL_MESSAGE] = US"message",
192 [POOL_TAINT_MAIN] = US"main",
193 [POOL_TAINT_PERM] = US"perm",
194 [POOL_TAINT_CONFIG] = US"config",
195 [POOL_TAINT_SEARCH] = US"search",
196 [POOL_TAINT_MESSAGE] = US"message",
198 static const uschar * poolclass[N_PAIRED_POOLS] = {
199 [POOL_MAIN] = US"untainted",
200 [POOL_PERM] = US"untainted",
201 [POOL_CONFIG] = US"untainted",
202 [POOL_SEARCH] = US"untainted",
203 [POOL_MESSAGE] = US"untainted",
204 [POOL_TAINT_MAIN] = US"tainted",
205 [POOL_TAINT_PERM] = US"tainted",
206 [POOL_TAINT_CONFIG] = US"tainted",
207 [POOL_TAINT_SEARCH] = US"tainted",
208 [POOL_TAINT_MESSAGE] = US"tainted",
213 static void * internal_store_malloc(size_t, const char *, int);
214 static void internal_store_free(void *, const char *, int linenumber);
216 /******************************************************************************/
219 pool_init(pooldesc * pp)
221 memset(pp, 0, sizeof(*pp));
222 pp->yield_length = -1;
223 pp->store_block_order = 12; /* log2(allocation_size) ie. 4kB */
226 /* Initialisation, for things fragile with parameter channges when using
227 static initialisers. */
232 for (pooldesc * pp = paired_pools; pp < paired_pools + N_PAIRED_POOLS; pp++)
236 /******************************************************************************/
237 /* Locating elements given memory pointer */
240 is_pointer_in_block(const storeblock * b, const void * p)
242 uschar * bc = US b + ALIGNED_SIZEOF_STOREBLOCK;
243 return US p >= bc && US p < bc + b->length;
247 pool_current_for_pointer(const void * p)
251 for (quoted_pooldesc * qp = quoted_pools; qp; qp = qp->next)
252 if ((b = qp->pool.current_block) && is_pointer_in_block(b, p))
255 for (pooldesc * pp = paired_pools; pp < paired_pools + N_PAIRED_POOLS; pp++)
256 if ((b = pp->current_block) && is_pointer_in_block(b, p))
262 pool_for_pointer(const void * p, const char * func, int linenumber)
267 if ((pp = pool_current_for_pointer(p))) return pp;
269 for (quoted_pooldesc * qp = quoted_pools; qp; qp = qp->next)
270 for (b = qp->pool.chainbase; b; b = b->next)
271 if (is_pointer_in_block(b, p)) return &qp->pool;
273 for (pp = paired_pools; pp < paired_pools + N_PAIRED_POOLS; pp++)
274 for (b = pp->chainbase; b; b = b->next)
275 if (is_pointer_in_block(b, p)) return pp;
277 #ifndef COMPILE_UTILITY
280 log_write(0, LOG_MAIN|LOG_PANIC_DIE,
281 "bad memory reference; pool not found, at %s %d", func, linenumber);
285 /******************************************************************************/
286 /* Test if a pointer refers to tainted memory.
288 Slower version check, for use when platform intermixes malloc and mmap area
289 addresses. Test against the current-block of all tainted pools first, then all
290 blocks of all tainted pools.
292 Return: TRUE iff tainted
296 is_tainted_fn(const void * p)
300 if (p == GET_UNTAINTED) return FALSE;
301 if (p == GET_TAINTED) return TRUE;
303 for (pooldesc * pp = paired_pools + POOL_TAINT_BASE;
304 pp < paired_pools + N_PAIRED_POOLS; pp++)
305 if ((b = pp->current_block))
306 if (is_pointer_in_block(b, p)) return TRUE;
308 for (quoted_pooldesc * qp = quoted_pools; qp; qp = qp->next)
309 if (b = qp->pool.current_block)
310 if (is_pointer_in_block(b, p)) return TRUE;
312 for (pooldesc * pp = paired_pools + POOL_TAINT_BASE;
313 pp < paired_pools + N_PAIRED_POOLS; pp++)
314 for (b = pp->chainbase; b; b = b->next)
315 if (is_pointer_in_block(b, p)) return TRUE;
317 for (quoted_pooldesc * qp = quoted_pools; qp; qp = qp->next)
318 for (b = qp->pool.chainbase; b; b = b->next)
319 if (is_pointer_in_block(b, p)) return TRUE;
326 die_tainted(const uschar * msg, const uschar * func, int line)
328 log_write(0, LOG_MAIN|LOG_PANIC_DIE, "Taint mismatch, %s: %s %d\n",
333 #ifndef COMPILE_UTILITY
334 /* Return the pool for the given quoter, or null */
337 pool_for_quoter(unsigned quoter)
339 for (quoted_pooldesc * qp = quoted_pools; qp; qp = qp->next)
340 if (qp->quoter == quoter)
345 /* Allocate/init a new quoted-pool and return the pool */
348 quoted_pool_new(unsigned quoter)
350 // debug_printf("allocating quoted-pool\n");
351 quoted_pooldesc * qp = store_get_perm(sizeof(quoted_pooldesc), GET_UNTAINTED);
353 pool_init(&qp->pool);
355 qp->next = quoted_pools;
362 /******************************************************************************/
364 store_writeprotect(int pool)
366 #if !defined(COMPILE_UTILITY) && !defined(MISSING_POSIX_MEMALIGN)
367 for (storeblock * b = paired_pools[pool].chainbase; b; b = b->next)
368 if (mprotect(b, ALIGNED_SIZEOF_STOREBLOCK + b->length, PROT_READ) != 0)
369 DEBUG(D_any) debug_printf("config block mprotect: (%d) %s\n", errno, strerror(errno));
373 /******************************************************************************/
376 pool_get(pooldesc * pp, int size, BOOL align_mem, const char * func, int linenumber)
378 /* Ensure we've been asked to allocate memory.
379 A negative size is a sign of a security problem.
380 A zero size might be also suspect, but our internal usage deliberately
381 does this to return a current watermark value for a later release of
384 if (size < 0 || size >= INT_MAX/2)
385 log_write(0, LOG_MAIN|LOG_PANIC_DIE,
386 "bad memory allocation requested (%d bytes) from %s %d",
387 size, func, linenumber);
389 /* Round up the size to a multiple of the alignment. Although this looks a
390 messy statement, because "alignment" is a constant expression, the compiler can
391 do a reasonable job of optimizing, especially if the value of "alignment" is a
392 power of two. I checked this with -O2, and gcc did very well, compiling it to 4
393 instructions on a Sparc (alignment = 8). */
395 if (size % alignment != 0) size += alignment - (size % alignment);
397 /* If there isn't room in the current block, get a new one. The minimum
398 size is STORE_BLOCK_SIZE, and we would expect this to be the norm, since
399 these functions are mostly called for small amounts of store. */
401 if (size > pp->yield_length)
404 STORE_BLOCK_SIZE(pp->store_block_order) - ALIGNED_SIZEOF_STOREBLOCK,
406 int mlength = length + ALIGNED_SIZEOF_STOREBLOCK;
407 storeblock * newblock;
409 /* Sometimes store_reset() may leave a block for us; check if we can use it */
411 if ( (newblock = pp->current_block)
412 && (newblock = newblock->next)
413 && newblock->length < length
416 /* Give up on this block, because it's too small */
418 internal_store_free(newblock, func, linenumber);
422 /* If there was no free block, get a new one */
426 if ((pp->nbytes += mlength) > pp->maxbytes)
427 pp->maxbytes = pp->nbytes;
428 if ((pool_malloc += mlength) > max_pool_malloc) /* Used in pools */
429 max_pool_malloc = pool_malloc;
430 nonpool_malloc -= mlength; /* Exclude from overall total */
431 if (++pp->nblocks > pp->maxblocks)
432 pp->maxblocks = pp->nblocks;
434 #ifndef MISSING_POSIX_MEMALIGN
437 long pgsize = sysconf(_SC_PAGESIZE);
438 int err = posix_memalign((void **)&newblock,
439 pgsize, (mlength + pgsize - 1) & ~(pgsize - 1));
441 log_write(0, LOG_MAIN|LOG_PANIC_DIE,
442 "failed to alloc (using posix_memalign) %d bytes of memory: '%s'"
443 "called from line %d in %s",
444 size, strerror(err), linenumber, func);
448 newblock = internal_store_malloc(mlength, func, linenumber);
449 newblock->next = NULL;
450 newblock->length = length;
451 #ifndef RESTRICTED_MEMORY
452 if (pp->store_block_order++ > pp->maxorder)
453 pp->maxorder = pp->store_block_order;
457 pp->chainbase = newblock;
459 pp->current_block->next = newblock;
462 pp->current_block = newblock;
463 pp->yield_length = newblock->length;
465 (void *)(CS pp->current_block + ALIGNED_SIZEOF_STOREBLOCK);
466 (void) VALGRIND_MAKE_MEM_NOACCESS(pp->next_yield, pp->yield_length);
469 /* There's (now) enough room in the current block; the yield is the next
472 pp->store_last_get = pp->next_yield;
474 (void) VALGRIND_MAKE_MEM_UNDEFINED(pp->store_last_get, size);
475 /* Update next pointer and number of bytes left in the current block. */
477 pp->next_yield = (void *)(CS pp->next_yield + size);
478 pp->yield_length -= size;
479 return pp->store_last_get;
482 /*************************************************
483 * Get a block from the current pool *
484 *************************************************/
486 /* Running out of store is a total disaster. This function is called via the
487 macro store_get(). The current store_pool is used, adjusting for taint.
488 If the protoype is quoted, use a quoted-pool.
489 Return a block of store within the current big block of the pool, getting a new
490 one if necessary. The address is saved in store_last_get for the pool.
493 size amount wanted, bytes
494 proto_mem class: get store conformant to this
495 Special values: 0 forces untainted, 1 forces tainted
496 func function from which called
497 linenumber line number in source file
499 Returns: pointer to store (panic on malloc failure)
503 store_get_3(int size, const void * proto_mem, const char * func, int linenumber)
505 #ifndef COMPILE_UTILITY
506 int quoter = quoter_for_address(proto_mem);
511 #ifndef COMPILE_UTILITY
512 if (!is_real_quoter(quoter))
515 BOOL tainted = is_tainted(proto_mem);
516 int pool = tainted ? store_pool + POOL_TAINT_BASE : store_pool;
517 pp = paired_pools + pool;
518 yield = pool_get(pp, size, (pool == POOL_CONFIG), func, linenumber);
520 /* Cut out the debugging stuff for utilities, but stop picky compilers from
523 #ifndef COMPILE_UTILITY
525 debug_printf("---%d Get %6p %5d %-14s %4d\n", pool,
526 pp->store_last_get, size, func, linenumber);
529 #ifndef COMPILE_UTILITY
533 debug_printf("allocating quoted-block for quoter %u (from %s %d)\n",
534 quoter, func, linenumber);
535 if (!(pp = pool_for_quoter(quoter))) pp = quoted_pool_new(quoter);
536 yield = pool_get(pp, size, FALSE, func, linenumber);
538 debug_printf("---QQ Get %6p %5d %-14s %4d\n",
539 pp->store_last_get, size, func, linenumber);
547 /*************************************************
548 * Get a block from the PERM pool *
549 *************************************************/
551 /* This is just a convenience function, useful when just a single block is to
556 proto_mem class: get store conformant to this
557 func function from which called
558 linenumber line number in source file
560 Returns: pointer to store (panic on malloc failure)
564 store_get_perm_3(int size, const void * proto_mem, const char * func, int linenumber)
567 int old_pool = store_pool;
568 store_pool = POOL_PERM;
569 yield = store_get_3(size, proto_mem, func, linenumber);
570 store_pool = old_pool;
575 #ifndef COMPILE_UTILITY
576 /*************************************************
577 * Get a block annotated as being lookup-quoted *
578 *************************************************/
580 /* Allocate from pool a pool consistent with the proto_mem augmented by the
581 requested quoter type.
583 XXX currently not handling mark/release
585 Args: size number of bytes to allocate
586 quoter id for the quoting type
587 func caller, for debug
588 linenumber caller, for debug
590 Return: allocated memory block
594 store_force_get_quoted(int size, unsigned quoter,
595 const char * func, int linenumber)
597 pooldesc * pp = pool_for_quoter(quoter);
601 debug_printf("allocating quoted-block for quoter %u (from %s %d)\n", quoter, func, linenumber);
603 if (!pp) pp = quoted_pool_new(quoter);
604 yield = pool_get(pp, size, FALSE, func, linenumber);
607 debug_printf("---QQ Get %6p %5d %-14s %4d\n",
608 pp->store_last_get, size, func, linenumber);
613 /* Maybe get memory for the specified quoter, but only if the
614 prototype memory is tainted. Otherwise, get plain memory.
617 store_get_quoted_3(int size, const void * proto_mem, unsigned quoter,
618 const char * func, int linenumber)
620 // debug_printf("store_get_quoted_3: quoter %u\n", quoter);
621 return is_tainted(proto_mem)
622 ? store_force_get_quoted(size, quoter, func, linenumber)
623 : store_get_3(size, proto_mem, func, linenumber);
626 /* Return quoter for given address, or -1 if not in a quoted-pool. */
628 quoter_for_address(const void * p)
630 for (quoted_pooldesc * qp = quoted_pools; qp; qp = qp->next)
632 pooldesc * pp = &qp->pool;
635 if (b = pp->current_block)
636 if (is_pointer_in_block(b, p))
639 for (b = pp->chainbase; b; b = b->next)
640 if (is_pointer_in_block(b, p))
646 /* Return TRUE iff the given address is quoted for the given type.
647 There is extra complexity to handle lookup providers with multiple
648 find variants but shared quote functions. */
650 is_quoted_like(const void * p, unsigned quoter)
652 int pq = quoter_for_address(p);
654 is_real_quoter(pq) && lookup_list[pq]->quote == lookup_list[quoter]->quote;
655 /* debug_printf("is_quoted(%p, %u): %c\n", p, quoter, y?'T':'F'); */
659 /* Return TRUE if the quoter value indicates an actual quoter */
661 is_real_quoter(int quoter)
666 /* Return TRUE if the "new" data requires that the "old" data
667 be recopied to new-class memory. We order the classes as
669 2: tainted, not quoted
670 1: quoted (which is also tainted)
673 If the "new" is higher-order than the "old", they are not compatible
674 and a copy is needed. If both are quoted, but the quoters differ,
675 not compatible. Otherwise they are compatible.
678 is_incompatible_fn(const void * old, const void * new)
683 ni = is_real_quoter(nq = quoter_for_address(new)) ? 1 : is_tainted(new) ? 2 : 0;
684 oi = is_real_quoter(oq = quoter_for_address(old)) ? 1 : is_tainted(old) ? 2 : 0;
685 return ni > oi || ni == oi && nq != oq;
688 #endif /*!COMPILE_UTILITY*/
690 /*************************************************
691 * Extend a block if it is at the top *
692 *************************************************/
694 /* While reading strings of unknown length, it is often the case that the
695 string is being read into the block at the top of the stack. If it needs to be
696 extended, it is more efficient just to extend within the top block rather than
697 allocate a new block and then have to copy the data. This function is provided
698 for the use of string_cat(), but of course can be used elsewhere too.
699 The block itself is not expanded; only the top allocation from it.
702 ptr pointer to store block
703 oldsize current size of the block, as requested by user
704 newsize new size required
705 func function from which called
706 linenumber line number in source file
708 Returns: TRUE if the block is at the top of the stack and has been
709 extended; FALSE if it isn't at the top of the stack, or cannot
712 XXX needs extension for quoted-tracking. This assumes that the global store_pool
713 is the one to alloc from, which breaks with separated pools.
717 store_extend_3(void * ptr, int oldsize, int newsize,
718 const char * func, int linenumber)
720 pooldesc * pp = pool_for_pointer(ptr, func, linenumber);
721 int inc = newsize - oldsize;
722 int rounded_oldsize = oldsize;
724 if (oldsize < 0 || newsize < oldsize || newsize >= INT_MAX/2)
725 log_write(0, LOG_MAIN|LOG_PANIC_DIE,
726 "bad memory extension requested (%d -> %d bytes) at %s %d",
727 oldsize, newsize, func, linenumber);
729 if (rounded_oldsize % alignment != 0)
730 rounded_oldsize += alignment - (rounded_oldsize % alignment);
732 if (CS ptr + rounded_oldsize != CS (pp->next_yield) ||
733 inc > pp->yield_length + rounded_oldsize - oldsize)
736 /* Cut out the debugging stuff for utilities, but stop picky compilers from
739 #ifndef COMPILE_UTILITY
742 quoted_pooldesc * qp;
743 for (qp = quoted_pools; qp; qp = qp->next)
746 debug_printf("---Q%d Ext %6p %5d %-14s %4d\n",
747 (int)(qp - quoted_pools),
748 ptr, newsize, func, linenumber);
752 debug_printf("---%d Ext %6p %5d %-14s %4d\n",
753 (int)(pp - paired_pools),
754 ptr, newsize, func, linenumber);
756 #endif /* COMPILE_UTILITY */
758 if (newsize % alignment != 0) newsize += alignment - (newsize % alignment);
759 pp->next_yield = CS ptr + newsize;
760 pp->yield_length -= newsize - rounded_oldsize;
761 (void) VALGRIND_MAKE_MEM_UNDEFINED(ptr + oldsize, inc);
769 is_pwr2_size(int len)
772 return (x & (x - 1)) == 0;
776 /*************************************************
777 * Back up to a previous point on the stack *
778 *************************************************/
780 /* This function resets the next pointer, freeing any subsequent whole blocks
781 that are now unused. Call with a cookie obtained from store_mark() only; do
782 not call with a pointer returned by store_get(). Both the untainted and tainted
783 pools corresposding to store_pool are reset.
785 Quoted pools are not handled.
788 ptr place to back up to
789 pool pool holding the pointer
790 func function from which called
791 linenumber line number in source file
797 internal_store_reset(void * ptr, int pool, const char *func, int linenumber)
800 pooldesc * pp = paired_pools + pool;
801 storeblock * b = pp->current_block;
802 char * bc = CS b + ALIGNED_SIZEOF_STOREBLOCK;
803 int newlength, count;
804 #ifndef COMPILE_UTILITY
805 int oldmalloc = pool_malloc;
808 if (!b) return; /* exim_dumpdb gets this, becuse it has never used tainted mem */
810 /* Last store operation was not a get */
812 pp->store_last_get = NULL;
814 /* See if the place is in the current block - as it often will be. Otherwise,
815 search for the block in which it lies. */
817 if (CS ptr < bc || CS ptr > bc + b->length)
819 for (b = pp->chainbase; b; b = b->next)
821 bc = CS b + ALIGNED_SIZEOF_STOREBLOCK;
822 if (CS ptr >= bc && CS ptr <= bc + b->length) break;
825 log_write(0, LOG_MAIN|LOG_PANIC_DIE, "internal error: store_reset(%p) "
826 "failed: pool=%d %-14s %4d", ptr, pool, func, linenumber);
829 /* Back up, rounding to the alignment if necessary. When testing, flatten
830 the released memory. */
832 newlength = bc + b->length - CS ptr;
833 #ifndef COMPILE_UTILITY
836 assert_no_variables(ptr, newlength, func, linenumber);
837 if (f.running_in_test_harness)
839 (void) VALGRIND_MAKE_MEM_DEFINED(ptr, newlength);
840 memset(ptr, 0xF0, newlength);
844 (void) VALGRIND_MAKE_MEM_NOACCESS(ptr, newlength);
845 pp->next_yield = CS ptr + (newlength % alignment);
846 count = pp->yield_length;
847 count = (pp->yield_length = newlength - (newlength % alignment)) - count;
848 pp->current_block = b;
850 /* Free any subsequent block. Do NOT free the first
851 successor, if our current block has less than 256 bytes left. This should
852 prevent us from flapping memory. However, keep this block only when it has
853 a power-of-two size so probably is not a custom inflated one. */
855 if ( pp->yield_length < STOREPOOL_MIN_SIZE
857 && is_pwr2_size(b->next->length + ALIGNED_SIZEOF_STOREBLOCK))
860 #ifndef COMPILE_UTILITY
862 assert_no_variables(b, b->length + ALIGNED_SIZEOF_STOREBLOCK,
865 (void) VALGRIND_MAKE_MEM_NOACCESS(CS b + ALIGNED_SIZEOF_STOREBLOCK,
866 b->length - ALIGNED_SIZEOF_STOREBLOCK);
870 if (pool != POOL_CONFIG)
875 int siz = b->length + ALIGNED_SIZEOF_STOREBLOCK;
877 #ifndef COMPILE_UTILITY
879 assert_no_variables(b, b->length + ALIGNED_SIZEOF_STOREBLOCK,
886 if (pool != POOL_CONFIG)
887 internal_store_free(b, func, linenumber);
889 #ifndef RESTRICTED_MEMORY
890 if (pp->store_block_order > 13) pp->store_block_order--;
894 /* Cut out the debugging stuff for utilities, but stop picky compilers from
897 #ifndef COMPILE_UTILITY
899 debug_printf("---%d Rst %6p %5d %-14s %4d\tpool %d\n", pool, ptr,
900 count + oldmalloc - pool_malloc,
901 func, linenumber, pool_malloc);
902 #endif /* COMPILE_UTILITY */
906 /* Back up the pool pair, untainted and tainted, of the store_pool setting.
907 Quoted pools are not handled.
911 store_reset_3(rmark r, const char * func, int linenumber)
915 if (store_pool >= POOL_TAINT_BASE)
916 log_write(0, LOG_MAIN|LOG_PANIC_DIE,
917 "store_reset called for pool %d: %s %d\n", store_pool, func, linenumber);
919 log_write(0, LOG_MAIN|LOG_PANIC_DIE,
920 "store_reset called with bad mark: %s %d\n", func, linenumber);
922 internal_store_reset(*ptr, store_pool + POOL_TAINT_BASE, func, linenumber);
923 internal_store_reset(ptr, store_pool, func, linenumber);
930 /* Free tail-end unused allocation. This lets us allocate a big chunk
931 early, for cases when we only discover later how much was really needed.
933 Can be called with a value from store_get(), or an offset after such. Only
934 the tainted or untainted pool that serviced the store_get() will be affected.
936 This is mostly a cut-down version of internal_store_reset().
937 XXX needs rationalising
941 store_release_above_3(void * ptr, const char * func, int linenumber)
945 /* Search all pools' "current" blocks. If it isn't one of those,
946 ignore it (it usually will be). */
948 if ((pp = pool_current_for_pointer(ptr)))
950 storeblock * b = pp->current_block;
951 int count, newlength;
953 /* Last store operation was not a get */
955 pp->store_last_get = NULL;
957 /* Back up, rounding to the alignment if necessary. When testing, flatten
958 the released memory. */
960 newlength = (CS b + ALIGNED_SIZEOF_STOREBLOCK) + b->length - CS ptr;
961 #ifndef COMPILE_UTILITY
964 assert_no_variables(ptr, newlength, func, linenumber);
965 if (f.running_in_test_harness)
967 (void) VALGRIND_MAKE_MEM_DEFINED(ptr, newlength);
968 memset(ptr, 0xF0, newlength);
972 (void) VALGRIND_MAKE_MEM_NOACCESS(ptr, newlength);
973 pp->next_yield = CS ptr + (newlength % alignment);
974 count = pp->yield_length;
975 count = (pp->yield_length = newlength - (newlength % alignment)) - count;
977 /* Cut out the debugging stuff for utilities, but stop picky compilers from
980 #ifndef COMPILE_UTILITY
983 quoted_pooldesc * qp;
984 for (qp = quoted_pools; qp; qp = qp->next)
986 debug_printf("---Q%d Rel %6p %5d %-14s %4d\tpool %d\n",
987 (int)(qp - quoted_pools),
988 ptr, count, func, linenumber, pool_malloc);
990 debug_printf("---%d Rel %6p %5d %-14s %4d\tpool %d\n",
991 (int)(pp - paired_pools), ptr, count,
992 func, linenumber, pool_malloc);
997 #ifndef COMPILE_UTILITY
999 debug_printf("non-last memory release try: %s %d\n", func, linenumber);
1006 store_mark_3(const char * func, int linenumber)
1010 #ifndef COMPILE_UTILITY
1012 debug_printf("---%d Mrk %-14s %4d\tpool %d\n",
1013 store_pool, func, linenumber, pool_malloc);
1014 #endif /* COMPILE_UTILITY */
1016 if (store_pool >= POOL_TAINT_BASE)
1017 log_write(0, LOG_MAIN|LOG_PANIC_DIE,
1018 "store_mark called for pool %d: %s %d\n", store_pool, func, linenumber);
1020 /* Stash a mark for the tainted-twin release, in the untainted twin. Return
1021 a cookie (actually the address in the untainted pool) to the caller.
1022 Reset uses the cookie to recover the t-mark, winds back the tainted pool with it
1023 and winds back the untainted pool with the cookie. */
1025 p = store_get_3(sizeof(void *), GET_UNTAINTED, func, linenumber);
1026 *p = store_get_3(0, GET_TAINTED, func, linenumber);
1033 /************************************************
1035 ************************************************/
1037 /* This function checks that the pointer it is given is the first thing in a
1038 block, and if so, releases that block.
1041 block block of store to consider
1042 pp pool containing the block
1043 func function from which called
1044 linenumber line number in source file
1050 store_release_3(void * block, pooldesc * pp, const char * func, int linenumber)
1052 /* It will never be the first block, so no need to check that. */
1054 for (storeblock * b = pp->chainbase; b; b = b->next)
1056 storeblock * bb = b->next;
1057 if (bb && CS block == CS bb + ALIGNED_SIZEOF_STOREBLOCK)
1059 int siz = bb->length + ALIGNED_SIZEOF_STOREBLOCK;
1065 /* Cut out the debugging stuff for utilities, but stop picky compilers
1066 from giving warnings. */
1068 #ifndef COMPILE_UTILITY
1070 debug_printf("-Release %6p %-20s %4d %d\n", (void *)bb, func,
1071 linenumber, pool_malloc);
1073 if (f.running_in_test_harness)
1074 memset(bb, 0xF0, bb->length+ALIGNED_SIZEOF_STOREBLOCK);
1075 #endif /* COMPILE_UTILITY */
1077 internal_store_free(bb, func, linenumber);
1084 /************************************************
1086 ************************************************/
1088 /* Allocate a new block big enough to expend to the given size and
1089 copy the current data into it. Free the old one if possible.
1091 This function is specifically provided for use when reading very
1092 long strings, e.g. header lines. When the string gets longer than a
1093 complete block, it gets copied to a new block. It is helpful to free
1094 the old block iff the previous copy of the string is at its start,
1095 and therefore the only thing in it. Otherwise, for very long strings,
1096 dead store can pile up somewhat disastrously. This function checks that
1097 the pointer it is given is the first thing in a block, and that nothing
1098 has been allocated since. If so, releases that block.
1102 newsize requested size
1105 Returns: new location of data
1109 store_newblock_3(void * oldblock, int newsize, int len,
1110 const char * func, int linenumber)
1112 pooldesc * pp = pool_for_pointer(oldblock, func, linenumber);
1113 BOOL release_ok = !is_tainted(oldblock) && pp->store_last_get == oldblock; /*XXX why tainted not handled? */
1116 if (len < 0 || len > newsize)
1117 log_write(0, LOG_MAIN|LOG_PANIC_DIE,
1118 "bad memory extension requested (%d -> %d bytes) at %s %d",
1119 len, newsize, func, linenumber);
1121 newblock = store_get(newsize, oldblock);
1122 memcpy(newblock, oldblock, len);
1123 if (release_ok) store_release_3(oldblock, pp, func, linenumber);
1124 return (void *)newblock;
1130 /*************************************************
1132 *************************************************/
1134 /* Running out of store is a total disaster for exim. Some malloc functions
1135 do not run happily on very small sizes, nor do they document this fact. This
1136 function is called via the macro store_malloc().
1139 size amount of store wanted
1140 func function from which called
1141 line line number in source file
1143 Returns: pointer to gotten store (panic on failure)
1147 internal_store_malloc(size_t size, const char *func, int line)
1151 /* Check specifically for a possibly result of conversion from
1152 a negative int, to the (unsigned, wider) size_t */
1154 if (size >= INT_MAX/2)
1155 log_write(0, LOG_MAIN|LOG_PANIC_DIE,
1156 "bad internal_store_malloc request (" SIZE_T_FMT " bytes) from %s %d",
1159 size += sizeof(size_t); /* space to store the size, used under debug */
1160 if (size < 16) size = 16;
1162 if (!(yield = malloc(size)))
1163 log_write(0, LOG_MAIN|LOG_PANIC_DIE, "failed to malloc " SIZE_T_FMT " bytes of memory: "
1164 "called from line %d in %s", size, line, func);
1166 #ifndef COMPILE_UTILITY
1167 DEBUG(D_any) *(size_t *)yield = size;
1169 yield = US yield + sizeof(size_t);
1171 if ((nonpool_malloc += size) > max_nonpool_malloc)
1172 max_nonpool_malloc = nonpool_malloc;
1174 /* Cut out the debugging stuff for utilities, but stop picky compilers from
1177 #ifndef COMPILE_UTILITY
1178 /* If running in test harness, spend time making sure all the new store
1179 is not filled with zeros so as to catch problems. */
1181 if (f.running_in_test_harness)
1182 memset(yield, 0xF0, size - sizeof(size_t));
1183 DEBUG(D_memory) debug_printf("--Malloc %6p %5lu bytes\t%-20s %4d\tpool %5d nonpool %5d\n",
1184 yield, size, func, line, pool_malloc, nonpool_malloc);
1185 #endif /* COMPILE_UTILITY */
1191 store_malloc_3(size_t size, const char *func, int linenumber)
1193 if (n_nonpool_blocks++ > max_nonpool_blocks)
1194 max_nonpool_blocks = n_nonpool_blocks;
1195 return internal_store_malloc(size, func, linenumber);
1199 /************************************************
1201 ************************************************/
1203 /* This function is called by the macro store_free().
1206 block block of store to free
1207 func function from which called
1208 linenumber line number in source file
1214 internal_store_free(void * block, const char * func, int linenumber)
1216 uschar * p = US block - sizeof(size_t);
1217 #ifndef COMPILE_UTILITY
1218 DEBUG(D_any) nonpool_malloc -= *(size_t *)p;
1219 DEBUG(D_memory) debug_printf("----Free %6p %5ld bytes\t%-20s %4d\n",
1220 block, *(size_t *)p, func, linenumber);
1226 store_free_3(void * block, const char * func, int linenumber)
1229 internal_store_free(block, func, linenumber);
1232 /******************************************************************************/
1233 /* Stats output on process exit */
1237 #ifndef COMPILE_UTILITY
1241 debug_printf("----Exit nonpool max: %3d kB in %d blocks\n",
1242 (max_nonpool_malloc+1023)/1024, max_nonpool_blocks);
1243 debug_printf("----Exit npools max: %3d kB\n", max_pool_malloc/1024);
1245 for (i = 0; i < N_PAIRED_POOLS; i++)
1247 pooldesc * pp = paired_pools + i;
1248 debug_printf("----Exit pool %2d max: %3d kB in %d blocks at order %u\t%s %s\n",
1249 i, (pp->maxbytes+1023)/1024, pp->maxblocks, pp->maxorder,
1250 poolclass[i], pooluse[i]);
1253 for (quoted_pooldesc * qp = quoted_pools; qp; i++, qp = qp->next)
1255 pooldesc * pp = &qp->pool;
1256 debug_printf("----Exit pool Q%d max: %3d kB in %d blocks at order %u\ttainted quoted:%s\n",
1257 i, (pp->maxbytes+1023)/1024, pp->maxblocks, pp->maxorder, lookup_list[qp->quoter]->name);
1264 /******************************************************************************/
1265 /* Per-message pool management */
1267 static rmark message_reset_point = NULL;
1272 int oldpool = store_pool;
1273 store_pool = POOL_MESSAGE;
1274 if (!message_reset_point) message_reset_point = store_mark();
1275 store_pool = oldpool;
1279 message_tidyup(void)
1282 if (!message_reset_point) return;
1283 oldpool = store_pool;
1284 store_pool = POOL_MESSAGE;
1285 message_reset_point = store_reset(message_reset_point);
1286 store_pool = oldpool;
1289 /******************************************************************************/
1290 /* Debug analysis of address */
1292 #ifndef COMPILE_UTILITY
1294 debug_print_taint(const void * p)
1296 int q = quoter_for_address(p);
1297 if (!is_tainted(p)) return;
1298 debug_printf("(tainted");
1299 if (is_real_quoter(q)) debug_printf(", quoted:%s", lookup_list[q]->name);
1300 debug_printf(")\n");
1304 /* End of store.c */