SECURITY: Refuse negative and large store allocations
[exim.git] / src / src / store.c
1 /*************************************************
2 *     Exim - an Internet mail transport agent    *
3 *************************************************/
4
5 /* Copyright (c) University of Cambridge 1995 - 2018 */
6 /* Copyright (c) The Exim maintainers 2019 - 2020 */
7 /* See the file NOTICE for conditions of use and distribution. */
8
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.
15
16 Obviously the long-running processes (the daemon, the queue runner, and eximon)
17 must take care not to eat store.
18
19 The following different types of store are recognized:
20
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.
24
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.
29
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.
35
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
38   the lookup caching.
39
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.
43
44 . Orthogonal to the three pool types, there are two classes of memory: untainted
45   and tainted.  The latter is used for values derived from untrusted input, and
46   the string-expansion mechanism refuses to operate on such values (obviously,
47   it can expand an untainted value to return a tainted result).  The classes
48   are implemented by duplicating the four pool types.  Pool resets are requested
49   against the nontainted sibling and apply to both siblings.
50
51   Only memory blocks requested for tainted use are regarded as tainted; anything
52   else (including stack auto variables) is untainted.  Care is needed when coding
53   to not copy untrusted data into untainted memory, as downstream taint-checks
54   would be avoided.
55
56   Intermediate layers (eg. the string functions) can test for taint, and use this
57   for ensurinng that results have proper state.  For example the
58   string_vformat_trc() routing supporting the string_sprintf() interface will
59   recopy a string being built into a tainted allocation if it meets a %s for a
60   tainted argument.  Any intermediate-layer function that (can) return a new
61   allocation should behave this way; returning a tainted result if any tainted
62   content is used.  Intermediate-layer functions (eg. Ustrncpy) that modify
63   existing allocations fail if tainted data is written into an untainted area.
64   Users of functions that modify existing allocations should check if a tainted
65   source and an untainted destination is used, and fail instead (sprintf() being
66   the classic case).
67 */
68
69
70 #include "exim.h"
71 /* keep config.h before memcheck.h, for NVALGRIND */
72 #include "config.h"
73
74 #include <sys/mman.h>
75 #include "memcheck.h"
76
77
78 /* We need to know how to align blocks of data for general use. I'm not sure
79 how to get an alignment factor in general. In the current world, a value of 8
80 is probably right, and this is sizeof(double) on some systems and sizeof(void
81 *) on others, so take the larger of those. Since everything in this expression
82 is a constant, the compiler should optimize it to a simple constant wherever it
83 appears (I checked that gcc does do this). */
84
85 #define alignment \
86   (sizeof(void *) > sizeof(double) ? sizeof(void *) : sizeof(double))
87
88 /* store_reset() will not free the following block if the last used block has
89 less than this much left in it. */
90
91 #define STOREPOOL_MIN_SIZE 256
92
93 /* Structure describing the beginning of each big block. */
94
95 typedef struct storeblock {
96   struct storeblock *next;
97   size_t length;
98 } storeblock;
99
100 /* Just in case we find ourselves on a system where the structure above has a
101 length that is not a multiple of the alignment, set up a macro for the padded
102 length. */
103
104 #define ALIGNED_SIZEOF_STOREBLOCK \
105   (((sizeof(storeblock) + alignment - 1) / alignment) * alignment)
106
107 /* Size of block to get from malloc to carve up into smaller ones. This
108 must be a multiple of the alignment. We assume that 4096 is going to be
109 suitably aligned.  Double the size per-pool for every malloc, to mitigate
110 certain denial-of-service attacks.  Don't bother to decrease on block frees.
111 We waste average half the current alloc size per pool.  This could be several
112 hundred kB now, vs. 4kB with a constant-size block size.  But the search time
113 for is_tainted(), linear in the number of blocks for the pool, is O(n log n)
114 rather than O(n^2).
115 A test of 2000 RCPTs and just accept ACL had 370kB in 21 blocks before,
116 504kB in 6 blocks now, for the untainted-main (largest) pool.
117 Builds for restricted-memory system can disable the expansion by
118 defining RESTRICTED_MEMORY */
119 /*XXX should we allow any for malloc's own overhead?  But how much? */
120
121 /* #define RESTRICTED_MEMORY */
122 #define STORE_BLOCK_SIZE(order) ((1U << (order)) - ALIGNED_SIZEOF_STOREBLOCK)
123
124 /* Variables holding data for the local pools of store. The current pool number
125 is held in store_pool, which is global so that it can be changed from outside.
126 Setting the initial length values to -1 forces a malloc for the first call,
127 even if the length is zero (which is used for getting a point to reset to). */
128
129 int store_pool = POOL_MAIN;
130
131 static storeblock *chainbase[NPOOLS];
132 static storeblock *current_block[NPOOLS];
133 static void *next_yield[NPOOLS];
134 static int yield_length[NPOOLS];
135 static unsigned store_block_order[NPOOLS];
136
137 /* pool_malloc holds the amount of memory used by the store pools; this goes up
138 and down as store is reset or released. nonpool_malloc is the total got by
139 malloc from other calls; this doesn't go down because it is just freed by
140 pointer. */
141
142 static int pool_malloc;
143 static int nonpool_malloc;
144
145 /* This variable is set by store_get() to its yield, and by store_reset() to
146 NULL. This enables string_cat() to optimize its store handling for very long
147 strings. That's why the variable is global. */
148
149 void *store_last_get[NPOOLS];
150
151 /* These are purely for stats-gathering */
152
153 static int nbytes[NPOOLS];      /* current bytes allocated */
154 static int maxbytes[NPOOLS];    /* max number reached */
155 static int nblocks[NPOOLS];     /* current number of blocks allocated */
156 static int maxblocks[NPOOLS];
157 static unsigned maxorder[NPOOLS];
158 static int n_nonpool_blocks;    /* current number of direct store_malloc() blocks */
159 static int max_nonpool_blocks;
160 static int max_pool_malloc;     /* max value for pool_malloc */
161 static int max_nonpool_malloc;  /* max value for nonpool_malloc */
162
163
164 #ifndef COMPILE_UTILITY
165 static const uschar * pooluse[NPOOLS] = {
166 [POOL_MAIN] =           US"main",
167 [POOL_PERM] =           US"perm",
168 [POOL_SEARCH] =         US"search",
169 [POOL_MESSAGE] =        US"message",
170 [POOL_TAINT_MAIN] =     US"main",
171 [POOL_TAINT_PERM] =     US"perm",
172 [POOL_TAINT_SEARCH] =   US"search",
173 [POOL_TAINT_SEARCH] =   US"search",
174 [POOL_TAINT_MESSAGE] =  US"message",
175 };
176 static const uschar * poolclass[NPOOLS] = {
177 [POOL_MAIN] =           US"untainted",
178 [POOL_PERM] =           US"untainted",
179 [POOL_SEARCH] =         US"untainted",
180 [POOL_MESSAGE] =        US"untainted",
181 [POOL_TAINT_MAIN] =     US"tainted",
182 [POOL_TAINT_PERM] =     US"tainted",
183 [POOL_TAINT_SEARCH] =   US"tainted",
184 [POOL_TAINT_MESSAGE] =  US"tainted",
185 };
186 #endif
187
188
189 static void * internal_store_malloc(int, const char *, int);
190 static void   internal_store_free(void *, const char *, int linenumber);
191
192 /******************************************************************************/
193 /* Initialisation, for things fragile with parameter channges when using
194 static initialisers. */
195
196 void
197 store_init(void)
198 {
199 for (int i = 0; i < NPOOLS; i++)
200   {
201   yield_length[i] = -1;
202   store_block_order[i] = 12; /* log2(allocation_size) ie. 4kB */
203   }
204 }
205
206 /******************************************************************************/
207
208 /* Test if a pointer refers to tainted memory.
209
210 Slower version check, for use when platform intermixes malloc and mmap area
211 addresses. Test against the current-block of all tainted pools first, then all
212 blocks of all tainted pools.
213
214 Return: TRUE iff tainted
215 */
216
217 BOOL
218 is_tainted_fn(const void * p)
219 {
220 storeblock * b;
221
222 for (int pool = POOL_TAINT_BASE; pool < nelem(chainbase); pool++)
223   if ((b = current_block[pool]))
224     {
225     uschar * bc = US b + ALIGNED_SIZEOF_STOREBLOCK;
226     if (US p >= bc && US p < bc + b->length) return TRUE;
227     }
228
229 for (int pool = POOL_TAINT_BASE; pool < nelem(chainbase); pool++)
230   for (b = chainbase[pool]; b; b = b->next)
231     {
232     uschar * bc = US b + ALIGNED_SIZEOF_STOREBLOCK;
233     if (US p >= bc && US p < bc + b->length) return TRUE;
234     }
235 return FALSE;
236 }
237
238
239 void
240 die_tainted(const uschar * msg, const uschar * func, int line)
241 {
242 log_write(0, LOG_MAIN|LOG_PANIC_DIE, "Taint mismatch, %s: %s %d\n",
243         msg, func, line);
244 }
245
246
247
248 /*************************************************
249 *       Get a block from the current pool        *
250 *************************************************/
251
252 /* Running out of store is a total disaster. This function is called via the
253 macro store_get(). It passes back a block of store within the current big
254 block, getting a new one if necessary. The address is saved in
255 store_last_was_get.
256
257 Arguments:
258   size        amount wanted, bytes
259   tainted     class: set to true for untrusted data (eg. from smtp input)
260   func        function from which called
261   linenumber  line number in source file
262
263 Returns:      pointer to store (panic on malloc failure)
264 */
265
266 void *
267 store_get_3(int size, BOOL tainted, const char *func, int linenumber)
268 {
269 int pool = tainted ? store_pool + POOL_TAINT_BASE : store_pool;
270
271 /* Ensure we've been asked to allocate memory.
272 A negative size is a sign of a security problem.
273 A zero size might be also suspect, but our internal usage deliberately
274 does this to return a current watermark value for a later release of
275 allocated store. */
276
277 if (size < 0 || size >= INT_MAX/2)
278   log_write(0, LOG_MAIN|LOG_PANIC_DIE,
279             "bad memory allocation requested (%d bytes) at %s %d",
280             size, func, linenumber);
281
282 /* Round up the size to a multiple of the alignment. Although this looks a
283 messy statement, because "alignment" is a constant expression, the compiler can
284 do a reasonable job of optimizing, especially if the value of "alignment" is a
285 power of two. I checked this with -O2, and gcc did very well, compiling it to 4
286 instructions on a Sparc (alignment = 8). */
287
288 if (size % alignment != 0) size += alignment - (size % alignment);
289
290 /* If there isn't room in the current block, get a new one. The minimum
291 size is STORE_BLOCK_SIZE, and we would expect this to be the norm, since
292 these functions are mostly called for small amounts of store. */
293
294 if (size > yield_length[pool])
295   {
296   int length = MAX(
297           STORE_BLOCK_SIZE(store_block_order[pool]) - ALIGNED_SIZEOF_STOREBLOCK,
298           size);
299   int mlength = length + ALIGNED_SIZEOF_STOREBLOCK;
300   storeblock * newblock;
301
302   /* Sometimes store_reset() may leave a block for us; check if we can use it */
303
304   if (  (newblock = current_block[pool])
305      && (newblock = newblock->next)
306      && newblock->length < length
307      )
308     {
309     /* Give up on this block, because it's too small */
310     nblocks[pool]--;
311     internal_store_free(newblock, func, linenumber);
312     newblock = NULL;
313     }
314
315   /* If there was no free block, get a new one */
316
317   if (!newblock)
318     {
319     if ((nbytes[pool] += mlength) > maxbytes[pool])
320       maxbytes[pool] = nbytes[pool];
321     if ((pool_malloc += mlength) > max_pool_malloc)     /* Used in pools */
322       max_pool_malloc = pool_malloc;
323     nonpool_malloc -= mlength;                  /* Exclude from overall total */
324     if (++nblocks[pool] > maxblocks[pool])
325       maxblocks[pool] = nblocks[pool];
326
327     newblock = internal_store_malloc(mlength, func, linenumber);
328     newblock->next = NULL;
329     newblock->length = length;
330 #ifndef RESTRICTED_MEMORY
331     if (store_block_order[pool]++ > maxorder[pool])
332       maxorder[pool] = store_block_order[pool];
333 #endif
334
335     if (!chainbase[pool])
336       chainbase[pool] = newblock;
337     else
338       current_block[pool]->next = newblock;
339     }
340
341   current_block[pool] = newblock;
342   yield_length[pool] = newblock->length;
343   next_yield[pool] =
344     (void *)(CS current_block[pool] + ALIGNED_SIZEOF_STOREBLOCK);
345   (void) VALGRIND_MAKE_MEM_NOACCESS(next_yield[pool], yield_length[pool]);
346   }
347
348 /* There's (now) enough room in the current block; the yield is the next
349 pointer. */
350
351 store_last_get[pool] = next_yield[pool];
352
353 /* Cut out the debugging stuff for utilities, but stop picky compilers from
354 giving warnings. */
355
356 #ifndef COMPILE_UTILITY
357 DEBUG(D_memory)
358   debug_printf("---%d Get %6p %5d %-14s %4d\n", pool,
359     store_last_get[pool], size, func, linenumber);
360 #endif  /* COMPILE_UTILITY */
361
362 (void) VALGRIND_MAKE_MEM_UNDEFINED(store_last_get[pool], size);
363 /* Update next pointer and number of bytes left in the current block. */
364
365 next_yield[pool] = (void *)(CS next_yield[pool] + size);
366 yield_length[pool] -= size;
367 return store_last_get[pool];
368 }
369
370
371
372 /*************************************************
373 *       Get a block from the PERM pool           *
374 *************************************************/
375
376 /* This is just a convenience function, useful when just a single block is to
377 be obtained.
378
379 Arguments:
380   size        amount wanted
381   func        function from which called
382   linenumber  line number in source file
383
384 Returns:      pointer to store (panic on malloc failure)
385 */
386
387 void *
388 store_get_perm_3(int size, BOOL tainted, const char *func, int linenumber)
389 {
390 void *yield;
391 int old_pool = store_pool;
392 store_pool = POOL_PERM;
393 yield = store_get_3(size, tainted, func, linenumber);
394 store_pool = old_pool;
395 return yield;
396 }
397
398
399
400 /*************************************************
401 *      Extend a block if it is at the top        *
402 *************************************************/
403
404 /* While reading strings of unknown length, it is often the case that the
405 string is being read into the block at the top of the stack. If it needs to be
406 extended, it is more efficient just to extend within the top block rather than
407 allocate a new block and then have to copy the data. This function is provided
408 for the use of string_cat(), but of course can be used elsewhere too.
409 The block itself is not expanded; only the top allocation from it.
410
411 Arguments:
412   ptr        pointer to store block
413   oldsize    current size of the block, as requested by user
414   newsize    new size required
415   func       function from which called
416   linenumber line number in source file
417
418 Returns:     TRUE if the block is at the top of the stack and has been
419              extended; FALSE if it isn't at the top of the stack, or cannot
420              be extended
421 */
422
423 BOOL
424 store_extend_3(void *ptr, BOOL tainted, int oldsize, int newsize,
425    const char *func, int linenumber)
426 {
427 int pool = tainted ? store_pool + POOL_TAINT_BASE : store_pool;
428 int inc = newsize - oldsize;
429 int rounded_oldsize = oldsize;
430
431 if (oldsize < 0 || newsize < oldsize || newsize >= INT_MAX/2)
432   log_write(0, LOG_MAIN|LOG_PANIC_DIE,
433             "bad memory extension requested (%d -> %d bytes) at %s %d",
434             oldsize, newsize, func, linenumber);
435
436 /* Check that the block being extended was already of the required taint status;
437 refuse to extend if not. */
438
439 if (is_tainted(ptr) != tainted)
440   return FALSE;
441
442 if (rounded_oldsize % alignment != 0)
443   rounded_oldsize += alignment - (rounded_oldsize % alignment);
444
445 if (CS ptr + rounded_oldsize != CS (next_yield[pool]) ||
446     inc > yield_length[pool] + rounded_oldsize - oldsize)
447   return FALSE;
448
449 /* Cut out the debugging stuff for utilities, but stop picky compilers from
450 giving warnings. */
451
452 #ifndef COMPILE_UTILITY
453 DEBUG(D_memory)
454   debug_printf("---%d Ext %6p %5d %-14s %4d\n", pool, ptr, newsize,
455     func, linenumber);
456 #endif  /* COMPILE_UTILITY */
457
458 if (newsize % alignment != 0) newsize += alignment - (newsize % alignment);
459 next_yield[pool] = CS ptr + newsize;
460 yield_length[pool] -= newsize - rounded_oldsize;
461 (void) VALGRIND_MAKE_MEM_UNDEFINED(ptr + oldsize, inc);
462 return TRUE;
463 }
464
465
466
467
468 static BOOL
469 is_pwr2_size(int len)
470 {
471 unsigned x = len;
472 return (x & (x - 1)) == 0;
473 }
474
475
476 /*************************************************
477 *    Back up to a previous point on the stack    *
478 *************************************************/
479
480 /* This function resets the next pointer, freeing any subsequent whole blocks
481 that are now unused. Call with a cookie obtained from store_mark() only; do
482 not call with a pointer returned by store_get().  Both the untainted and tainted
483 pools corresposding to store_pool are reset.
484
485 Arguments:
486   r           place to back up to
487   func        function from which called
488   linenumber  line number in source file
489
490 Returns:      nothing
491 */
492
493 static void
494 internal_store_reset(void * ptr, int pool, const char *func, int linenumber)
495 {
496 storeblock * bb;
497 storeblock * b = current_block[pool];
498 char * bc = CS b + ALIGNED_SIZEOF_STOREBLOCK;
499 int newlength, count;
500 #ifndef COMPILE_UTILITY
501 int oldmalloc = pool_malloc;
502 #endif
503
504 /* Last store operation was not a get */
505
506 store_last_get[pool] = NULL;
507
508 /* See if the place is in the current block - as it often will be. Otherwise,
509 search for the block in which it lies. */
510
511 if (CS ptr < bc || CS ptr > bc + b->length)
512   {
513   for (b = chainbase[pool]; b; b = b->next)
514     {
515     bc = CS b + ALIGNED_SIZEOF_STOREBLOCK;
516     if (CS ptr >= bc && CS ptr <= bc + b->length) break;
517     }
518   if (!b)
519     log_write(0, LOG_MAIN|LOG_PANIC_DIE, "internal error: store_reset(%p) "
520       "failed: pool=%d %-14s %4d", ptr, pool, func, linenumber);
521   }
522
523 /* Back up, rounding to the alignment if necessary. When testing, flatten
524 the released memory. */
525
526 newlength = bc + b->length - CS ptr;
527 #ifndef COMPILE_UTILITY
528 if (debug_store)
529   {
530   assert_no_variables(ptr, newlength, func, linenumber);
531   if (f.running_in_test_harness)
532     {
533     (void) VALGRIND_MAKE_MEM_DEFINED(ptr, newlength);
534     memset(ptr, 0xF0, newlength);
535     }
536   }
537 #endif
538 (void) VALGRIND_MAKE_MEM_NOACCESS(ptr, newlength);
539 next_yield[pool] = CS ptr + (newlength % alignment);
540 count = yield_length[pool];
541 count = (yield_length[pool] = newlength - (newlength % alignment)) - count;
542 current_block[pool] = b;
543
544 /* Free any subsequent block. Do NOT free the first
545 successor, if our current block has less than 256 bytes left. This should
546 prevent us from flapping memory. However, keep this block only when it has
547 a power-of-two size so probably is not a custom inflated one. */
548
549 if (  yield_length[pool] < STOREPOOL_MIN_SIZE
550    && b->next
551    && is_pwr2_size(b->next->length + ALIGNED_SIZEOF_STOREBLOCK))
552   {
553   b = b->next;
554 #ifndef COMPILE_UTILITY
555   if (debug_store)
556     assert_no_variables(b, b->length + ALIGNED_SIZEOF_STOREBLOCK,
557                         func, linenumber);
558 #endif
559   (void) VALGRIND_MAKE_MEM_NOACCESS(CS b + ALIGNED_SIZEOF_STOREBLOCK,
560                 b->length - ALIGNED_SIZEOF_STOREBLOCK);
561   }
562
563 bb = b->next;
564 b->next = NULL;
565
566 while ((b = bb))
567   {
568   int siz = b->length + ALIGNED_SIZEOF_STOREBLOCK;
569
570 #ifndef COMPILE_UTILITY
571   if (debug_store)
572     assert_no_variables(b, b->length + ALIGNED_SIZEOF_STOREBLOCK,
573                         func, linenumber);
574 #endif
575   bb = bb->next;
576   nbytes[pool] -= siz;
577   pool_malloc -= siz;
578   nblocks[pool]--;
579   internal_store_free(b, func, linenumber);
580
581 #ifndef RESTRICTED_MEMORY
582   if (store_block_order[pool] > 13) store_block_order[pool]--;
583 #endif
584   }
585
586 /* Cut out the debugging stuff for utilities, but stop picky compilers from
587 giving warnings. */
588
589 #ifndef COMPILE_UTILITY
590 DEBUG(D_memory)
591   debug_printf("---%d Rst %6p %5d %-14s %4d\tpool %d\n", pool, ptr,
592     count + oldmalloc - pool_malloc,
593     func, linenumber, pool_malloc);
594 #endif  /* COMPILE_UTILITY */
595 }
596
597
598 rmark
599 store_reset_3(rmark r, const char *func, int linenumber)
600 {
601 void ** ptr = r;
602
603 if (store_pool >= POOL_TAINT_BASE)
604   log_write(0, LOG_MAIN|LOG_PANIC_DIE,
605     "store_reset called for pool %d: %s %d\n", store_pool, func, linenumber);
606 if (!r)
607   log_write(0, LOG_MAIN|LOG_PANIC_DIE,
608     "store_reset called with bad mark: %s %d\n", func, linenumber);
609
610 internal_store_reset(*ptr, store_pool + POOL_TAINT_BASE, func, linenumber);
611 internal_store_reset(ptr,  store_pool,             func, linenumber);
612 return NULL;
613 }
614
615
616
617 /* Free tail-end unused allocation.  This lets us allocate a big chunk
618 early, for cases when we only discover later how much was really needed.
619
620 Can be called with a value from store_get(), or an offset after such.  Only
621 the tainted or untainted pool that serviced the store_get() will be affected.
622
623 This is mostly a cut-down version of internal_store_reset().
624 XXX needs rationalising
625 */
626
627 void
628 store_release_above_3(void *ptr, const char *func, int linenumber)
629 {
630 /* Search all pools' "current" blocks.  If it isn't one of those,
631 ignore it (it usually will be). */
632
633 for (int pool = 0; pool < nelem(current_block); pool++)
634   {
635   storeblock * b = current_block[pool];
636   char * bc;
637   int count, newlength;
638
639   if (!b)
640     continue;
641
642   bc = CS b + ALIGNED_SIZEOF_STOREBLOCK;
643   if (CS ptr < bc || CS ptr > bc + b->length)
644     continue;
645
646   /* Last store operation was not a get */
647
648   store_last_get[pool] = NULL;
649
650   /* Back up, rounding to the alignment if necessary. When testing, flatten
651   the released memory. */
652
653   newlength = bc + b->length - CS ptr;
654 #ifndef COMPILE_UTILITY
655   if (debug_store)
656     {
657     assert_no_variables(ptr, newlength, func, linenumber);
658     if (f.running_in_test_harness)
659       {
660       (void) VALGRIND_MAKE_MEM_DEFINED(ptr, newlength);
661       memset(ptr, 0xF0, newlength);
662       }
663     }
664 #endif
665   (void) VALGRIND_MAKE_MEM_NOACCESS(ptr, newlength);
666   next_yield[pool] = CS ptr + (newlength % alignment);
667   count = yield_length[pool];
668   count = (yield_length[pool] = newlength - (newlength % alignment)) - count;
669
670   /* Cut out the debugging stuff for utilities, but stop picky compilers from
671   giving warnings. */
672
673 #ifndef COMPILE_UTILITY
674   DEBUG(D_memory)
675     debug_printf("---%d Rel %6p %5d %-14s %4d\tpool %d\n", pool, ptr, count,
676       func, linenumber, pool_malloc);
677 #endif
678   return;
679   }
680 #ifndef COMPILE_UTILITY
681 DEBUG(D_memory)
682   debug_printf("non-last memory release try: %s %d\n", func, linenumber);
683 #endif
684 }
685
686
687
688 rmark
689 store_mark_3(const char *func, int linenumber)
690 {
691 void ** p;
692
693 #ifndef COMPILE_UTILITY
694 DEBUG(D_memory)
695   debug_printf("---%d Mrk                    %-14s %4d\tpool %d\n",
696     store_pool, func, linenumber, pool_malloc);
697 #endif  /* COMPILE_UTILITY */
698
699 if (store_pool >= POOL_TAINT_BASE)
700   log_write(0, LOG_MAIN|LOG_PANIC_DIE,
701     "store_mark called for pool %d: %s %d\n", store_pool, func, linenumber);
702
703 /* Stash a mark for the tainted-twin release, in the untainted twin. Return
704 a cookie (actually the address in the untainted pool) to the caller.
705 Reset uses the cookie to recover the t-mark, winds back the tainted pool with it
706 and winds back the untainted pool with the cookie. */
707
708 p = store_get_3(sizeof(void *), FALSE, func, linenumber);
709 *p = store_get_3(0, TRUE, func, linenumber);
710 return p;
711 }
712
713
714
715
716 /************************************************
717 *             Release store                     *
718 ************************************************/
719
720 /* This function checks that the pointer it is given is the first thing in a
721 block, and if so, releases that block.
722
723 Arguments:
724   block       block of store to consider
725   func        function from which called
726   linenumber  line number in source file
727
728 Returns:      nothing
729 */
730
731 static void
732 store_release_3(void * block, int pool, const char * func, int linenumber)
733 {
734 /* It will never be the first block, so no need to check that. */
735
736 for (storeblock * b = chainbase[pool]; b; b = b->next)
737   {
738   storeblock * bb = b->next;
739   if (bb && CS block == CS bb + ALIGNED_SIZEOF_STOREBLOCK)
740     {
741     int siz = bb->length + ALIGNED_SIZEOF_STOREBLOCK;
742     b->next = bb->next;
743     nbytes[pool] -= siz;
744     pool_malloc -= siz;
745     nblocks[pool]--;
746
747     /* Cut out the debugging stuff for utilities, but stop picky compilers
748     from giving warnings. */
749
750 #ifndef COMPILE_UTILITY
751     DEBUG(D_memory)
752       debug_printf("-Release %6p %-20s %4d %d\n", (void *)bb, func,
753         linenumber, pool_malloc);
754
755     if (f.running_in_test_harness)
756       memset(bb, 0xF0, bb->length+ALIGNED_SIZEOF_STOREBLOCK);
757 #endif  /* COMPILE_UTILITY */
758
759     internal_store_free(bb, func, linenumber);
760     return;
761     }
762   }
763 }
764
765
766 /************************************************
767 *             Move store                        *
768 ************************************************/
769
770 /* Allocate a new block big enough to expend to the given size and
771 copy the current data into it.  Free the old one if possible.
772
773 This function is specifically provided for use when reading very
774 long strings, e.g. header lines. When the string gets longer than a
775 complete block, it gets copied to a new block. It is helpful to free
776 the old block iff the previous copy of the string is at its start,
777 and therefore the only thing in it. Otherwise, for very long strings,
778 dead store can pile up somewhat disastrously. This function checks that
779 the pointer it is given is the first thing in a block, and that nothing
780 has been allocated since. If so, releases that block.
781
782 Arguments:
783   block
784   newsize
785   len
786
787 Returns:        new location of data
788 */
789
790 void *
791 store_newblock_3(void * block, BOOL tainted, int newsize, int len,
792   const char * func, int linenumber)
793 {
794 int pool = tainted ? store_pool + POOL_TAINT_BASE : store_pool;
795 BOOL release_ok = !tainted && store_last_get[pool] == block;
796 uschar * newtext;
797
798 #if !defined(MACRO_PREDEF) && !defined(COMPILE_UTILITY)
799 if (is_tainted(block) != tainted)
800   die_tainted(US"store_newblock", CUS func, linenumber);
801 #endif
802
803 if (len < 0 || len > newsize)
804   log_write(0, LOG_MAIN|LOG_PANIC_DIE,
805             "bad memory extension requested (%d -> %d bytes) at %s %d",
806             len, newsize, func, linenumber);
807
808 newtext = store_get(newsize, tainted);
809 memcpy(newtext, block, len);
810 if (release_ok) store_release_3(block, pool, func, linenumber);
811 return (void *)newtext;
812 }
813
814
815
816
817 /*************************************************
818 *                Malloc store                    *
819 *************************************************/
820
821 /* Running out of store is a total disaster for exim. Some malloc functions
822 do not run happily on very small sizes, nor do they document this fact. This
823 function is called via the macro store_malloc().
824
825 Arguments:
826   size        amount of store wanted
827   func        function from which called
828   line        line number in source file
829
830 Returns:      pointer to gotten store (panic on failure)
831 */
832
833 static void *
834 internal_store_malloc(int size, const char *func, int line)
835 {
836 void * yield;
837
838 if (size < 0 || size >= INT_MAX/2)
839   log_write(0, LOG_MAIN|LOG_PANIC_DIE,
840             "bad memory allocation requested (%d bytes) at %s %d",
841             size, func, line);
842
843 size += sizeof(int);    /* space to store the size, used under debug */
844 if (size < 16) size = 16;
845
846 if (!(yield = malloc((size_t)size)))
847   log_write(0, LOG_MAIN|LOG_PANIC_DIE, "failed to malloc %d bytes of memory: "
848     "called from line %d in %s", size, line, func);
849
850 #ifndef COMPILE_UTILITY
851 DEBUG(D_any) *(int *)yield = size;
852 #endif
853 yield = US yield + sizeof(int);
854
855 if ((nonpool_malloc += size) > max_nonpool_malloc)
856   max_nonpool_malloc = nonpool_malloc;
857
858 /* Cut out the debugging stuff for utilities, but stop picky compilers from
859 giving warnings. */
860
861 #ifndef COMPILE_UTILITY
862 /* If running in test harness, spend time making sure all the new store
863 is not filled with zeros so as to catch problems. */
864
865 if (f.running_in_test_harness)
866   memset(yield, 0xF0, (size_t)size - sizeof(int));
867 DEBUG(D_memory) debug_printf("--Malloc %6p %5d bytes\t%-20s %4d\tpool %5d  nonpool %5d\n",
868   yield, size, func, line, pool_malloc, nonpool_malloc);
869 #endif  /* COMPILE_UTILITY */
870
871 return yield;
872 }
873
874 void *
875 store_malloc_3(int size, const char *func, int linenumber)
876 {
877 if (n_nonpool_blocks++ > max_nonpool_blocks)
878   max_nonpool_blocks = n_nonpool_blocks;
879 return internal_store_malloc(size, func, linenumber);
880 }
881
882
883 /************************************************
884 *             Free store                        *
885 ************************************************/
886
887 /* This function is called by the macro store_free().
888
889 Arguments:
890   block       block of store to free
891   func        function from which called
892   linenumber  line number in source file
893
894 Returns:      nothing
895 */
896
897 static void
898 internal_store_free(void * block, const char * func, int linenumber)
899 {
900 uschar * p = US block - sizeof(int);
901 #ifndef COMPILE_UTILITY
902 DEBUG(D_any) nonpool_malloc -= *(int *)p;
903 DEBUG(D_memory) debug_printf("----Free %6p %5d bytes\t%-20s %4d\n", block, *(int *)p, func, linenumber);
904 #endif
905 free(p);
906 }
907
908 void
909 store_free_3(void * block, const char * func, int linenumber)
910 {
911 n_nonpool_blocks--;
912 internal_store_free(block, func, linenumber);
913 }
914
915 /******************************************************************************/
916 /* Stats output on process exit */
917 void
918 store_exit(void)
919 {
920 #ifndef COMPILE_UTILITY
921 DEBUG(D_memory)
922  {
923  debug_printf("----Exit nonpool max: %3d kB in %d blocks\n",
924   (max_nonpool_malloc+1023)/1024, max_nonpool_blocks);
925  debug_printf("----Exit npools  max: %3d kB\n", max_pool_malloc/1024);
926  for (int i = 0; i < NPOOLS; i++)
927   debug_printf("----Exit  pool %d max: %3d kB in %d blocks at order %u\t%s %s\n",
928     i, (maxbytes[i]+1023)/1024, maxblocks[i], maxorder[i],
929     poolclass[i], pooluse[i]);
930  }
931 #endif
932 }
933
934
935 /******************************************************************************/
936 /* Per-message pool management */
937
938 static rmark   message_reset_point    = NULL;
939
940 void
941 message_start(void)
942 {
943 int oldpool = store_pool;
944 store_pool = POOL_MESSAGE;
945 if (!message_reset_point) message_reset_point = store_mark();
946 store_pool = oldpool;
947 }
948
949 void message_tidyup(void)
950 {
951 int oldpool;
952 if (!message_reset_point) return;
953 oldpool = store_pool;
954 store_pool = POOL_MESSAGE;
955 message_reset_point = store_reset(message_reset_point);
956 store_pool = oldpool;
957 }
958
959 /* End of store.c */