Logging: distinguish mem-allocation errors
[exim.git] / src / src / store.c
1 /*************************************************
2 *     Exim - an Internet mail transport agent    *
3 *************************************************/
4
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. */
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 - There is a dedicated pool for configuration data read from the config file(s).
45   Once complete, it is made readonly.
46
47 - There are pools for each active combination of lookup-quoting, dynamically created.
48
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.
55
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
59   would be avoided.
60
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
71   the classic case).
72 */
73
74
75 #include "exim.h"
76 /* keep config.h before memcheck.h, for NVALGRIND */
77 #include "config.h"
78
79 #include <sys/mman.h>
80 #include "memcheck.h"
81
82
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). */
89
90 #define alignment \
91   (sizeof(void *) > sizeof(double) ? sizeof(void *) : sizeof(double))
92
93 /* store_reset() will not free the following block if the last used block has
94 less than this much left in it. */
95
96 #define STOREPOOL_MIN_SIZE 256
97
98 /* Structure describing the beginning of each big block. */
99
100 typedef struct storeblock {
101   struct storeblock *next;
102   size_t length;
103 } storeblock;
104
105 /* Pool descriptor struct */
106
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 */
113
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. */
117
118   void *        store_last_get;
119
120   /* These are purely for stats-gathering */
121
122   int           nbytes;
123   int           maxbytes;
124   int           nblocks;
125   int           maxblocks;
126   unsigned      maxorder;
127 } pooldesc;
128
129 /* Enhanced pool descriptor for quoted pools */
130
131 typedef struct quoted_pooldesc {
132   pooldesc                      pool;
133   unsigned                      quoter;
134   struct quoted_pooldesc *      next;
135 } quoted_pooldesc;
136
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
139 length. */
140
141 #define ALIGNED_SIZEOF_STOREBLOCK \
142   (((sizeof(storeblock) + alignment - 1) / alignment) * alignment)
143
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)
151 rather than O(n^2).
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? */
157
158 /* #define RESTRICTED_MEMORY */
159 #define STORE_BLOCK_SIZE(order) ((1U << (order)) - ALIGNED_SIZEOF_STOREBLOCK)
160
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). */
165
166 int store_pool = POOL_MAIN;
167
168 pooldesc paired_pools[N_PAIRED_POOLS];
169 quoted_pooldesc * quoted_pools = NULL;
170
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 */
175
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
179 pointer. */
180
181 static int pool_malloc;
182 static int nonpool_malloc;
183
184
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",
197 };
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",
209 };
210 #endif
211
212
213 static void * internal_store_malloc(size_t, const char *, int);
214 static void   internal_store_free(void *, const char *, int linenumber);
215
216 /******************************************************************************/
217
218 static void
219 pool_init(pooldesc * pp)
220 {
221 memset(pp, 0, sizeof(*pp));
222 pp->yield_length = -1;
223 pp->store_block_order = 12; /* log2(allocation_size) ie. 4kB */
224 }
225
226 /* Initialisation, for things fragile with parameter channges when using
227 static initialisers. */
228
229 void
230 store_init(void)
231 {
232 for (pooldesc * pp = paired_pools; pp < paired_pools + N_PAIRED_POOLS; pp++)
233   pool_init(pp);
234 }
235
236 /******************************************************************************/
237 /* Locating elements given memory pointer */
238
239 static BOOL
240 is_pointer_in_block(const storeblock * b, const void * p)
241 {
242 uschar * bc = US b + ALIGNED_SIZEOF_STOREBLOCK;
243 return US p >= bc && US p < bc + b->length;
244 }
245
246 static pooldesc *
247 pool_current_for_pointer(const void * p)
248 {
249 storeblock * b;
250
251 for (quoted_pooldesc * qp = quoted_pools; qp; qp = qp->next)
252   if ((b = qp->pool.current_block) && is_pointer_in_block(b, p))
253     return &qp->pool;
254
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))
257     return pp;
258 return NULL;
259 }
260
261 static pooldesc *
262 pool_for_pointer(const void * p, const char * func, int linenumber)
263 {
264 pooldesc * pp;
265 storeblock * b;
266
267 if ((pp = pool_current_for_pointer(p))) return pp;
268
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;
272
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;
276
277 log_write(0, LOG_MAIN|LOG_PANIC_DIE,
278   "bad memory reference; pool not found, at %s %d", func, linenumber);
279 return NULL;
280 }
281
282 /******************************************************************************/
283 /* Test if a pointer refers to tainted memory.
284
285 Slower version check, for use when platform intermixes malloc and mmap area
286 addresses. Test against the current-block of all tainted pools first, then all
287 blocks of all tainted pools.
288
289 Return: TRUE iff tainted
290 */
291
292 BOOL
293 is_tainted_fn(const void * p)
294 {
295 storeblock * b;
296
297 if (p == GET_UNTAINTED) return FALSE;
298 if (p == GET_TAINTED) return TRUE;
299
300 for (pooldesc * pp = paired_pools + POOL_TAINT_BASE;
301      pp < paired_pools + N_PAIRED_POOLS; pp++)
302   if ((b = pp->current_block))
303     if (is_pointer_in_block(b, p)) return TRUE;
304
305 for (quoted_pooldesc * qp = quoted_pools; qp; qp = qp->next)
306   if (b = qp->pool.current_block)
307     if (is_pointer_in_block(b, p)) return TRUE;
308
309 for (pooldesc * pp = paired_pools + POOL_TAINT_BASE;
310      pp < paired_pools + N_PAIRED_POOLS; pp++)
311   for (b = pp->chainbase; b; b = b->next)
312     if (is_pointer_in_block(b, p)) return TRUE;
313
314 for (quoted_pooldesc * qp = quoted_pools; qp; qp = qp->next)
315   for (b = qp->pool.chainbase; b; b = b->next)
316     if (is_pointer_in_block(b, p)) return TRUE;
317
318 return FALSE;
319 }
320
321
322 void
323 die_tainted(const uschar * msg, const uschar * func, int line)
324 {
325 log_write(0, LOG_MAIN|LOG_PANIC_DIE, "Taint mismatch, %s: %s %d\n",
326         msg, func, line);
327 }
328
329
330 #ifndef COMPILE_UTILITY
331 /* Return the pool for the given quoter, or null */
332
333 static pooldesc *
334 pool_for_quoter(unsigned quoter)
335 {
336 for (quoted_pooldesc * qp = quoted_pools; qp; qp = qp->next)
337   if (qp->quoter == quoter)
338     return &qp->pool;
339 return NULL;
340 }
341
342 /* Allocate/init a new quoted-pool and return the pool */
343
344 static pooldesc *
345 quoted_pool_new(unsigned quoter)
346 {
347 // debug_printf("allocating quoted-pool\n");
348 quoted_pooldesc * qp = store_get_perm(sizeof(quoted_pooldesc), GET_UNTAINTED);
349
350 pool_init(&qp->pool);
351 qp->quoter = quoter;
352 qp->next = quoted_pools;
353 quoted_pools = qp;
354 return &qp->pool;
355 }
356 #endif
357
358
359 /******************************************************************************/
360 void
361 store_writeprotect(int pool)
362 {
363 #if !defined(COMPILE_UTILITY) && !defined(MISSING_POSIX_MEMALIGN)
364 for (storeblock * b =  paired_pools[pool].chainbase; b; b = b->next)
365   if (mprotect(b, ALIGNED_SIZEOF_STOREBLOCK + b->length, PROT_READ) != 0)
366     DEBUG(D_any) debug_printf("config block mprotect: (%d) %s\n", errno, strerror(errno));
367 #endif
368 }
369
370 /******************************************************************************/
371
372 static void *
373 pool_get(pooldesc * pp, int size, BOOL align_mem, const char * func, int linenumber)
374 {
375 /* Ensure we've been asked to allocate memory.
376 A negative size is a sign of a security problem.
377 A zero size might be also suspect, but our internal usage deliberately
378 does this to return a current watermark value for a later release of
379 allocated store. */
380
381 if (size < 0 || size >= INT_MAX/2)
382   log_write(0, LOG_MAIN|LOG_PANIC_DIE,
383             "bad memory allocation requested (%d bytes) from %s %d",
384             size, func, linenumber);
385
386 /* Round up the size to a multiple of the alignment. Although this looks a
387 messy statement, because "alignment" is a constant expression, the compiler can
388 do a reasonable job of optimizing, especially if the value of "alignment" is a
389 power of two. I checked this with -O2, and gcc did very well, compiling it to 4
390 instructions on a Sparc (alignment = 8). */
391
392 if (size % alignment != 0) size += alignment - (size % alignment);
393
394 /* If there isn't room in the current block, get a new one. The minimum
395 size is STORE_BLOCK_SIZE, and we would expect this to be the norm, since
396 these functions are mostly called for small amounts of store. */
397
398 if (size > pp->yield_length)
399   {
400   int length = MAX(
401           STORE_BLOCK_SIZE(pp->store_block_order) - ALIGNED_SIZEOF_STOREBLOCK,
402           size);
403   int mlength = length + ALIGNED_SIZEOF_STOREBLOCK;
404   storeblock * newblock;
405
406   /* Sometimes store_reset() may leave a block for us; check if we can use it */
407
408   if (  (newblock = pp->current_block)
409      && (newblock = newblock->next)
410      && newblock->length < length
411      )
412     {
413     /* Give up on this block, because it's too small */
414     pp->nblocks--;
415     internal_store_free(newblock, func, linenumber);
416     newblock = NULL;
417     }
418
419   /* If there was no free block, get a new one */
420
421   if (!newblock)
422     {
423     if ((pp->nbytes += mlength) > pp->maxbytes)
424       pp->maxbytes = pp->nbytes;
425     if ((pool_malloc += mlength) > max_pool_malloc)     /* Used in pools */
426       max_pool_malloc = pool_malloc;
427     nonpool_malloc -= mlength;                  /* Exclude from overall total */
428     if (++pp->nblocks > pp->maxblocks)
429       pp->maxblocks = pp->nblocks;
430
431 #ifndef MISSING_POSIX_MEMALIGN
432     if (align_mem)
433       {
434       long pgsize = sysconf(_SC_PAGESIZE);
435       int err = posix_memalign((void **)&newblock,
436                                 pgsize, (mlength + pgsize - 1) & ~(pgsize - 1));
437       if (err)
438         log_write(0, LOG_MAIN|LOG_PANIC_DIE,
439           "failed to alloc (using posix_memalign) %d bytes of memory: '%s'"
440           "called from line %d in %s",
441           size, strerror(err), linenumber, func);
442       }
443     else
444 #endif
445       newblock = internal_store_malloc(mlength, func, linenumber);
446     newblock->next = NULL;
447     newblock->length = length;
448 #ifndef RESTRICTED_MEMORY
449     if (pp->store_block_order++ > pp->maxorder)
450       pp->maxorder = pp->store_block_order;
451 #endif
452
453     if (! pp->chainbase)
454        pp->chainbase = newblock;
455     else
456       pp->current_block->next = newblock;
457     }
458
459   pp->current_block = newblock;
460   pp->yield_length = newblock->length;
461   pp->next_yield =
462     (void *)(CS pp->current_block + ALIGNED_SIZEOF_STOREBLOCK);
463   (void) VALGRIND_MAKE_MEM_NOACCESS(pp->next_yield, pp->yield_length);
464   }
465
466 /* There's (now) enough room in the current block; the yield is the next
467 pointer. */
468
469 pp->store_last_get = pp->next_yield;
470
471 (void) VALGRIND_MAKE_MEM_UNDEFINED(pp->store_last_get, size);
472 /* Update next pointer and number of bytes left in the current block. */
473
474 pp->next_yield = (void *)(CS pp->next_yield + size);
475 pp->yield_length -= size;
476 return pp->store_last_get;
477 }
478
479 /*************************************************
480 *       Get a block from the current pool        *
481 *************************************************/
482
483 /* Running out of store is a total disaster. This function is called via the
484 macro store_get(). The current store_pool is used, adjusting for taint.
485 If the protoype is quoted, use a quoted-pool.
486 Return a block of store within the current big block of the pool, getting a new
487 one if necessary. The address is saved in store_last_get for the pool.
488
489 Arguments:
490   size        amount wanted, bytes
491   proto_mem   class: get store conformant to this
492                 Special values: 0 forces untainted, 1 forces tainted
493   func        function from which called
494   linenumber  line number in source file
495
496 Returns:      pointer to store (panic on malloc failure)
497 */
498
499 void *
500 store_get_3(int size, const void * proto_mem, const char * func, int linenumber)
501 {
502 #ifndef COMPILE_UTILITY
503 int quoter = quoter_for_address(proto_mem);
504 #endif
505 pooldesc * pp;
506 void * yield;
507
508 #ifndef COMPILE_UTILITY
509 if (!is_real_quoter(quoter))
510 #endif
511   {
512   BOOL tainted = is_tainted(proto_mem);
513   int pool = tainted ? store_pool + POOL_TAINT_BASE : store_pool;
514   pp = paired_pools + pool;
515   yield = pool_get(pp, size, (pool == POOL_CONFIG), func, linenumber);
516
517   /* Cut out the debugging stuff for utilities, but stop picky compilers from
518   giving warnings. */
519
520 #ifndef COMPILE_UTILITY
521   DEBUG(D_memory)
522     debug_printf("---%d Get %6p %5d %-14s %4d\n", pool,
523       pp->store_last_get, size, func, linenumber);
524 #endif
525   }
526 #ifndef COMPILE_UTILITY
527 else
528   {
529   DEBUG(D_memory)
530     debug_printf("allocating quoted-block for quoter %u (from %s %d)\n",
531       quoter, func, linenumber);
532   if (!(pp = pool_for_quoter(quoter))) pp = quoted_pool_new(quoter);
533   yield = pool_get(pp, size, FALSE, func, linenumber);
534   DEBUG(D_memory)
535     debug_printf("---QQ Get %6p %5d %-14s %4d\n",
536       pp->store_last_get, size, func, linenumber);
537   }
538 #endif
539 return yield;
540 }
541
542
543
544 /*************************************************
545 *       Get a block from the PERM pool           *
546 *************************************************/
547
548 /* This is just a convenience function, useful when just a single block is to
549 be obtained.
550
551 Arguments:
552   size        amount wanted
553   proto_mem   class: get store conformant to this
554   func        function from which called
555   linenumber  line number in source file
556
557 Returns:      pointer to store (panic on malloc failure)
558 */
559
560 void *
561 store_get_perm_3(int size, const void * proto_mem, const char * func, int linenumber)
562 {
563 void * yield;
564 int old_pool = store_pool;
565 store_pool = POOL_PERM;
566 yield = store_get_3(size, proto_mem, func, linenumber);
567 store_pool = old_pool;
568 return yield;
569 }
570
571
572 #ifndef COMPILE_UTILITY
573 /*************************************************
574 *  Get a block annotated as being lookup-quoted  *
575 *************************************************/
576
577 /* Allocate from pool a pool consistent with the proto_mem augmented by the
578 requested quoter type.
579
580 XXX currently not handling mark/release
581
582 Args:   size            number of bytes to allocate
583         quoter          id for the quoting type
584         func            caller, for debug
585         linenumber      caller, for debug
586
587 Return: allocated memory block
588 */
589
590 static void *
591 store_force_get_quoted(int size, unsigned quoter,
592   const char * func, int linenumber)
593 {
594 pooldesc * pp = pool_for_quoter(quoter);
595 void * yield;
596
597 DEBUG(D_memory)
598   debug_printf("allocating quoted-block for quoter %u (from %s %d)\n", quoter, func, linenumber);
599
600 if (!pp) pp = quoted_pool_new(quoter);
601 yield = pool_get(pp, size, FALSE, func, linenumber);
602
603 DEBUG(D_memory)
604   debug_printf("---QQ Get %6p %5d %-14s %4d\n",
605     pp->store_last_get, size, func, linenumber);
606
607 return yield;
608 }
609
610 /* Maybe get memory for the specified quoter, but only if the
611 prototype memory is tainted. Otherwise, get plain memory.
612 */
613 void *
614 store_get_quoted_3(int size, const void * proto_mem, unsigned quoter,
615   const char * func, int linenumber)
616 {
617 // debug_printf("store_get_quoted_3: quoter %u\n", quoter);
618 return is_tainted(proto_mem)
619   ? store_force_get_quoted(size, quoter, func, linenumber)
620   : store_get_3(size, proto_mem, func, linenumber);
621 }
622
623 /* Return quoter for given address, or -1 if not in a quoted-pool. */
624 int
625 quoter_for_address(const void * p)
626 {
627 for (quoted_pooldesc * qp = quoted_pools; qp; qp = qp->next)
628   {
629   pooldesc * pp = &qp->pool;
630   storeblock * b;
631
632   if (b = pp->current_block)
633     if (is_pointer_in_block(b, p))
634       return qp->quoter;
635
636   for (b = pp->chainbase; b; b = b->next)
637     if (is_pointer_in_block(b, p))
638       return qp->quoter;
639   }
640 return -1;
641 }
642
643 /* Return TRUE iff the given address is quoted for the given type.
644 There is extra complexity to handle lookup providers with multiple
645 find variants but shared quote functions. */
646 BOOL
647 is_quoted_like(const void * p, unsigned quoter)
648 {
649 int pq = quoter_for_address(p);
650 BOOL y =
651   is_real_quoter(pq) && lookup_list[pq]->quote == lookup_list[quoter]->quote;
652 /* debug_printf("is_quoted(%p, %u): %c\n", p, quoter, y?'T':'F'); */
653 return y;
654 }
655
656 /* Return TRUE if the quoter value indicates an actual quoter */
657 BOOL
658 is_real_quoter(int quoter)
659 {
660 return quoter >= 0;
661 }
662
663 /* Return TRUE if the "new" data requires that the "old" data
664 be recopied to new-class memory.  We order the classes as
665
666   2: tainted, not quoted
667   1: quoted (which is also tainted)
668   0: untainted
669
670 If the "new" is higher-order than the "old", they are not compatible
671 and a copy is needed.  If both are quoted, but the quoters differ,
672 not compatible.  Otherwise they are compatible.
673 */
674 BOOL
675 is_incompatible_fn(const void * old, const void * new)
676 {
677 int oq, nq;
678 unsigned oi, ni;
679
680 ni = is_real_quoter(nq = quoter_for_address(new)) ? 1 : is_tainted(new) ? 2 : 0;
681 oi = is_real_quoter(oq = quoter_for_address(old)) ? 1 : is_tainted(old) ? 2 : 0;
682 return ni > oi || ni == oi && nq != oq;
683 }
684
685 #endif  /*!COMPILE_UTILITY*/
686
687 /*************************************************
688 *      Extend a block if it is at the top        *
689 *************************************************/
690
691 /* While reading strings of unknown length, it is often the case that the
692 string is being read into the block at the top of the stack. If it needs to be
693 extended, it is more efficient just to extend within the top block rather than
694 allocate a new block and then have to copy the data. This function is provided
695 for the use of string_cat(), but of course can be used elsewhere too.
696 The block itself is not expanded; only the top allocation from it.
697
698 Arguments:
699   ptr        pointer to store block
700   oldsize    current size of the block, as requested by user
701   newsize    new size required
702   func       function from which called
703   linenumber line number in source file
704
705 Returns:     TRUE if the block is at the top of the stack and has been
706              extended; FALSE if it isn't at the top of the stack, or cannot
707              be extended
708
709 XXX needs extension for quoted-tracking.  This assumes that the global store_pool
710 is the one to alloc from, which breaks with separated pools.
711 */
712
713 BOOL
714 store_extend_3(void * ptr, int oldsize, int newsize,
715    const char * func, int linenumber)
716 {
717 pooldesc * pp = pool_for_pointer(ptr, func, linenumber);
718 int inc = newsize - oldsize;
719 int rounded_oldsize = oldsize;
720
721 if (oldsize < 0 || newsize < oldsize || newsize >= INT_MAX/2)
722   log_write(0, LOG_MAIN|LOG_PANIC_DIE,
723             "bad memory extension requested (%d -> %d bytes) at %s %d",
724             oldsize, newsize, func, linenumber);
725
726 if (rounded_oldsize % alignment != 0)
727   rounded_oldsize += alignment - (rounded_oldsize % alignment);
728
729 if (CS ptr + rounded_oldsize != CS (pp->next_yield) ||
730     inc > pp->yield_length + rounded_oldsize - oldsize)
731   return FALSE;
732
733 /* Cut out the debugging stuff for utilities, but stop picky compilers from
734 giving warnings. */
735
736 #ifndef COMPILE_UTILITY
737 DEBUG(D_memory)
738   {
739   quoted_pooldesc * qp;
740   for (qp = quoted_pools; qp; qp = qp->next)
741     if (pp == &qp->pool)
742       {
743       debug_printf("---Q%d Ext %6p %5d %-14s %4d\n",
744         (int)(qp - quoted_pools),
745         ptr, newsize, func, linenumber);
746       break;
747       }
748   if (!qp)
749     debug_printf("---%d Ext %6p %5d %-14s %4d\n",
750       (int)(pp - paired_pools),
751       ptr, newsize, func, linenumber);
752   }
753 #endif  /* COMPILE_UTILITY */
754
755 if (newsize % alignment != 0) newsize += alignment - (newsize % alignment);
756 pp->next_yield = CS ptr + newsize;
757 pp->yield_length -= newsize - rounded_oldsize;
758 (void) VALGRIND_MAKE_MEM_UNDEFINED(ptr + oldsize, inc);
759 return TRUE;
760 }
761
762
763
764
765 static BOOL
766 is_pwr2_size(int len)
767 {
768 unsigned x = len;
769 return (x & (x - 1)) == 0;
770 }
771
772
773 /*************************************************
774 *    Back up to a previous point on the stack    *
775 *************************************************/
776
777 /* This function resets the next pointer, freeing any subsequent whole blocks
778 that are now unused. Call with a cookie obtained from store_mark() only; do
779 not call with a pointer returned by store_get().  Both the untainted and tainted
780 pools corresposding to store_pool are reset.
781
782 Quoted pools are not handled.
783
784 Arguments:
785   ptr         place to back up to
786   pool        pool holding the pointer
787   func        function from which called
788   linenumber  line number in source file
789
790 Returns:      nothing
791 */
792
793 static void
794 internal_store_reset(void * ptr, int pool, const char *func, int linenumber)
795 {
796 storeblock * bb;
797 pooldesc * pp = paired_pools + pool;
798 storeblock * b = pp->current_block;
799 char * bc = CS b + ALIGNED_SIZEOF_STOREBLOCK;
800 int newlength, count;
801 #ifndef COMPILE_UTILITY
802 int oldmalloc = pool_malloc;
803 #endif
804
805 if (!b) return; /* exim_dumpdb gets this, becuse it has never used tainted mem */
806
807 /* Last store operation was not a get */
808
809 pp->store_last_get = NULL;
810
811 /* See if the place is in the current block - as it often will be. Otherwise,
812 search for the block in which it lies. */
813
814 if (CS ptr < bc || CS ptr > bc + b->length)
815   {
816   for (b =  pp->chainbase; b; b = b->next)
817     {
818     bc = CS b + ALIGNED_SIZEOF_STOREBLOCK;
819     if (CS ptr >= bc && CS ptr <= bc + b->length) break;
820     }
821   if (!b)
822     log_write(0, LOG_MAIN|LOG_PANIC_DIE, "internal error: store_reset(%p) "
823       "failed: pool=%d %-14s %4d", ptr, pool, func, linenumber);
824   }
825
826 /* Back up, rounding to the alignment if necessary. When testing, flatten
827 the released memory. */
828
829 newlength = bc + b->length - CS ptr;
830 #ifndef COMPILE_UTILITY
831 if (debug_store)
832   {
833   assert_no_variables(ptr, newlength, func, linenumber);
834   if (f.running_in_test_harness)
835     {
836     (void) VALGRIND_MAKE_MEM_DEFINED(ptr, newlength);
837     memset(ptr, 0xF0, newlength);
838     }
839   }
840 #endif
841 (void) VALGRIND_MAKE_MEM_NOACCESS(ptr, newlength);
842 pp->next_yield = CS ptr + (newlength % alignment);
843 count = pp->yield_length;
844 count = (pp->yield_length = newlength - (newlength % alignment)) - count;
845 pp->current_block = b;
846
847 /* Free any subsequent block. Do NOT free the first
848 successor, if our current block has less than 256 bytes left. This should
849 prevent us from flapping memory. However, keep this block only when it has
850 a power-of-two size so probably is not a custom inflated one. */
851
852 if (  pp->yield_length < STOREPOOL_MIN_SIZE
853    && b->next
854    && is_pwr2_size(b->next->length + ALIGNED_SIZEOF_STOREBLOCK))
855   {
856   b = b->next;
857 #ifndef COMPILE_UTILITY
858   if (debug_store)
859     assert_no_variables(b, b->length + ALIGNED_SIZEOF_STOREBLOCK,
860                         func, linenumber);
861 #endif
862   (void) VALGRIND_MAKE_MEM_NOACCESS(CS b + ALIGNED_SIZEOF_STOREBLOCK,
863                 b->length - ALIGNED_SIZEOF_STOREBLOCK);
864   }
865
866 bb = b->next;
867 if (pool != POOL_CONFIG)
868   b->next = NULL;
869
870 while ((b = bb))
871   {
872   int siz = b->length + ALIGNED_SIZEOF_STOREBLOCK;
873
874 #ifndef COMPILE_UTILITY
875   if (debug_store)
876     assert_no_variables(b, b->length + ALIGNED_SIZEOF_STOREBLOCK,
877                         func, linenumber);
878 #endif
879   bb = bb->next;
880   pp->nbytes -= siz;
881   pool_malloc -= siz;
882   pp->nblocks--;
883   if (pool != POOL_CONFIG)
884     internal_store_free(b, func, linenumber);
885
886 #ifndef RESTRICTED_MEMORY
887   if (pp->store_block_order > 13) pp->store_block_order--;
888 #endif
889   }
890
891 /* Cut out the debugging stuff for utilities, but stop picky compilers from
892 giving warnings. */
893
894 #ifndef COMPILE_UTILITY
895 DEBUG(D_memory)
896   debug_printf("---%d Rst %6p %5d %-14s %4d\tpool %d\n", pool, ptr,
897     count + oldmalloc - pool_malloc,
898     func, linenumber, pool_malloc);
899 #endif  /* COMPILE_UTILITY */
900 }
901
902
903 /* Back up the pool pair, untainted and tainted, of the store_pool setting.
904 Quoted pools are not handled.
905 */
906
907 rmark
908 store_reset_3(rmark r, const char * func, int linenumber)
909 {
910 void ** ptr = r;
911
912 if (store_pool >= POOL_TAINT_BASE)
913   log_write(0, LOG_MAIN|LOG_PANIC_DIE,
914     "store_reset called for pool %d: %s %d\n", store_pool, func, linenumber);
915 if (!r)
916   log_write(0, LOG_MAIN|LOG_PANIC_DIE,
917     "store_reset called with bad mark: %s %d\n", func, linenumber);
918
919 internal_store_reset(*ptr, store_pool + POOL_TAINT_BASE, func, linenumber);
920 internal_store_reset(ptr,  store_pool,             func, linenumber);
921 return NULL;
922 }
923
924
925 /**************/
926
927 /* Free tail-end unused allocation.  This lets us allocate a big chunk
928 early, for cases when we only discover later how much was really needed.
929
930 Can be called with a value from store_get(), or an offset after such.  Only
931 the tainted or untainted pool that serviced the store_get() will be affected.
932
933 This is mostly a cut-down version of internal_store_reset().
934 XXX needs rationalising
935 */
936
937 void
938 store_release_above_3(void * ptr, const char * func, int linenumber)
939 {
940 pooldesc * pp;
941
942 /* Search all pools' "current" blocks.  If it isn't one of those,
943 ignore it (it usually will be). */
944
945 if ((pp = pool_current_for_pointer(ptr)))
946   {
947   storeblock * b = pp->current_block;
948   int count, newlength;
949
950   /* Last store operation was not a get */
951
952   pp->store_last_get = NULL;
953
954   /* Back up, rounding to the alignment if necessary. When testing, flatten
955   the released memory. */
956
957   newlength = (CS b + ALIGNED_SIZEOF_STOREBLOCK) + b->length - CS ptr;
958 #ifndef COMPILE_UTILITY
959   if (debug_store)
960     {
961     assert_no_variables(ptr, newlength, func, linenumber);
962     if (f.running_in_test_harness)
963       {
964       (void) VALGRIND_MAKE_MEM_DEFINED(ptr, newlength);
965       memset(ptr, 0xF0, newlength);
966       }
967     }
968 #endif
969   (void) VALGRIND_MAKE_MEM_NOACCESS(ptr, newlength);
970   pp->next_yield = CS ptr + (newlength % alignment);
971   count = pp->yield_length;
972   count = (pp->yield_length = newlength - (newlength % alignment)) - count;
973
974   /* Cut out the debugging stuff for utilities, but stop picky compilers from
975   giving warnings. */
976
977 #ifndef COMPILE_UTILITY
978   DEBUG(D_memory)
979     {
980     quoted_pooldesc * qp;
981     for (qp = quoted_pools; qp; qp = qp->next)
982       if (pp == &qp->pool)
983         debug_printf("---Q%d Rel %6p %5d %-14s %4d\tpool %d\n",
984           (int)(qp - quoted_pools),
985           ptr, count, func, linenumber, pool_malloc);
986     if (!qp)
987       debug_printf("---%d Rel %6p %5d %-14s %4d\tpool %d\n",
988         (int)(pp - paired_pools), ptr, count,
989         func, linenumber, pool_malloc);
990     }
991 #endif
992   return;
993   }
994 #ifndef COMPILE_UTILITY
995 DEBUG(D_memory)
996   debug_printf("non-last memory release try: %s %d\n", func, linenumber);
997 #endif
998 }
999
1000
1001
1002 rmark
1003 store_mark_3(const char * func, int linenumber)
1004 {
1005 void ** p;
1006
1007 #ifndef COMPILE_UTILITY
1008 DEBUG(D_memory)
1009   debug_printf("---%d Mrk                    %-14s %4d\tpool %d\n",
1010     store_pool, func, linenumber, pool_malloc);
1011 #endif  /* COMPILE_UTILITY */
1012
1013 if (store_pool >= POOL_TAINT_BASE)
1014   log_write(0, LOG_MAIN|LOG_PANIC_DIE,
1015     "store_mark called for pool %d: %s %d\n", store_pool, func, linenumber);
1016
1017 /* Stash a mark for the tainted-twin release, in the untainted twin. Return
1018 a cookie (actually the address in the untainted pool) to the caller.
1019 Reset uses the cookie to recover the t-mark, winds back the tainted pool with it
1020 and winds back the untainted pool with the cookie. */
1021
1022 p = store_get_3(sizeof(void *), GET_UNTAINTED, func, linenumber);
1023 *p = store_get_3(0, GET_TAINTED, func, linenumber);
1024 return p;
1025 }
1026
1027
1028
1029
1030 /************************************************
1031 *             Release store                     *
1032 ************************************************/
1033
1034 /* This function checks that the pointer it is given is the first thing in a
1035 block, and if so, releases that block.
1036
1037 Arguments:
1038   block       block of store to consider
1039   pp          pool containing the block
1040   func        function from which called
1041   linenumber  line number in source file
1042
1043 Returns:      nothing
1044 */
1045
1046 static void
1047 store_release_3(void * block, pooldesc * pp, const char * func, int linenumber)
1048 {
1049 /* It will never be the first block, so no need to check that. */
1050
1051 for (storeblock * b =  pp->chainbase; b; b = b->next)
1052   {
1053   storeblock * bb = b->next;
1054   if (bb && CS block == CS bb + ALIGNED_SIZEOF_STOREBLOCK)
1055     {
1056     int siz = bb->length + ALIGNED_SIZEOF_STOREBLOCK;
1057     b->next = bb->next;
1058     pp->nbytes -= siz;
1059     pool_malloc -= siz;
1060     pp->nblocks--;
1061
1062     /* Cut out the debugging stuff for utilities, but stop picky compilers
1063     from giving warnings. */
1064
1065 #ifndef COMPILE_UTILITY
1066     DEBUG(D_memory)
1067       debug_printf("-Release %6p %-20s %4d %d\n", (void *)bb, func,
1068         linenumber, pool_malloc);
1069
1070     if (f.running_in_test_harness)
1071       memset(bb, 0xF0, bb->length+ALIGNED_SIZEOF_STOREBLOCK);
1072 #endif  /* COMPILE_UTILITY */
1073
1074     internal_store_free(bb, func, linenumber);
1075     return;
1076     }
1077   }
1078 }
1079
1080
1081 /************************************************
1082 *             Move store                        *
1083 ************************************************/
1084
1085 /* Allocate a new block big enough to expend to the given size and
1086 copy the current data into it.  Free the old one if possible.
1087
1088 This function is specifically provided for use when reading very
1089 long strings, e.g. header lines. When the string gets longer than a
1090 complete block, it gets copied to a new block. It is helpful to free
1091 the old block iff the previous copy of the string is at its start,
1092 and therefore the only thing in it. Otherwise, for very long strings,
1093 dead store can pile up somewhat disastrously. This function checks that
1094 the pointer it is given is the first thing in a block, and that nothing
1095 has been allocated since. If so, releases that block.
1096
1097 Arguments:
1098   oldblock
1099   newsize       requested size
1100   len           current size
1101
1102 Returns:        new location of data
1103 */
1104
1105 void *
1106 store_newblock_3(void * oldblock, int newsize, int len,
1107   const char * func, int linenumber)
1108 {
1109 pooldesc * pp = pool_for_pointer(oldblock, func, linenumber);
1110 BOOL release_ok = !is_tainted(oldblock) && pp->store_last_get == oldblock;              /*XXX why tainted not handled? */
1111 uschar * newblock;
1112
1113 if (len < 0 || len > newsize)
1114   log_write(0, LOG_MAIN|LOG_PANIC_DIE,
1115             "bad memory extension requested (%d -> %d bytes) at %s %d",
1116             len, newsize, func, linenumber);
1117
1118 newblock = store_get(newsize, oldblock);
1119 memcpy(newblock, oldblock, len);
1120 if (release_ok) store_release_3(oldblock, pp, func, linenumber);
1121 return (void *)newblock;
1122 }
1123
1124
1125
1126
1127 /*************************************************
1128 *                Malloc store                    *
1129 *************************************************/
1130
1131 /* Running out of store is a total disaster for exim. Some malloc functions
1132 do not run happily on very small sizes, nor do they document this fact. This
1133 function is called via the macro store_malloc().
1134
1135 Arguments:
1136   size        amount of store wanted
1137   func        function from which called
1138   line        line number in source file
1139
1140 Returns:      pointer to gotten store (panic on failure)
1141 */
1142
1143 static void *
1144 internal_store_malloc(size_t size, const char *func, int line)
1145 {
1146 void * yield;
1147
1148 /* Check specifically for a possibly result of conversion from
1149 a negative int, to the (unsigned, wider) size_t */
1150
1151 if (size >= INT_MAX/2)
1152   log_write(0, LOG_MAIN|LOG_PANIC_DIE,
1153     "bad internal_store_malloc request (" SIZE_T_FMT " bytes) from %s %d",
1154     size, func, line);
1155
1156 size += sizeof(size_t); /* space to store the size, used under debug */
1157 if (size < 16) size = 16;
1158
1159 if (!(yield = malloc(size)))
1160   log_write(0, LOG_MAIN|LOG_PANIC_DIE, "failed to malloc " SIZE_T_FMT " bytes of memory: "
1161     "called from line %d in %s", size, line, func);
1162
1163 #ifndef COMPILE_UTILITY
1164 DEBUG(D_any) *(size_t *)yield = size;
1165 #endif
1166 yield = US yield + sizeof(size_t);
1167
1168 if ((nonpool_malloc += size) > max_nonpool_malloc)
1169   max_nonpool_malloc = nonpool_malloc;
1170
1171 /* Cut out the debugging stuff for utilities, but stop picky compilers from
1172 giving warnings. */
1173
1174 #ifndef COMPILE_UTILITY
1175 /* If running in test harness, spend time making sure all the new store
1176 is not filled with zeros so as to catch problems. */
1177
1178 if (f.running_in_test_harness)
1179   memset(yield, 0xF0, size - sizeof(size_t));
1180 DEBUG(D_memory) debug_printf("--Malloc %6p %5lu bytes\t%-20s %4d\tpool %5d  nonpool %5d\n",
1181   yield, size, func, line, pool_malloc, nonpool_malloc);
1182 #endif  /* COMPILE_UTILITY */
1183
1184 return yield;
1185 }
1186
1187 void *
1188 store_malloc_3(size_t size, const char *func, int linenumber)
1189 {
1190 if (n_nonpool_blocks++ > max_nonpool_blocks)
1191   max_nonpool_blocks = n_nonpool_blocks;
1192 return internal_store_malloc(size, func, linenumber);
1193 }
1194
1195
1196 /************************************************
1197 *             Free store                        *
1198 ************************************************/
1199
1200 /* This function is called by the macro store_free().
1201
1202 Arguments:
1203   block       block of store to free
1204   func        function from which called
1205   linenumber  line number in source file
1206
1207 Returns:      nothing
1208 */
1209
1210 static void
1211 internal_store_free(void * block, const char * func, int linenumber)
1212 {
1213 uschar * p = US block - sizeof(size_t);
1214 #ifndef COMPILE_UTILITY
1215 DEBUG(D_any) nonpool_malloc -= *(size_t *)p;
1216 DEBUG(D_memory) debug_printf("----Free %6p %5ld bytes\t%-20s %4d\n",
1217                     block, *(size_t *)p, func, linenumber);
1218 #endif
1219 free(p);
1220 }
1221
1222 void
1223 store_free_3(void * block, const char * func, int linenumber)
1224 {
1225 n_nonpool_blocks--;
1226 internal_store_free(block, func, linenumber);
1227 }
1228
1229 /******************************************************************************/
1230 /* Stats output on process exit */
1231 void
1232 store_exit(void)
1233 {
1234 #ifndef COMPILE_UTILITY
1235 DEBUG(D_memory)
1236  {
1237  int i;
1238  debug_printf("----Exit nonpool max: %3d kB in %d blocks\n",
1239   (max_nonpool_malloc+1023)/1024, max_nonpool_blocks);
1240  debug_printf("----Exit npools  max: %3d kB\n", max_pool_malloc/1024);
1241
1242  for (i = 0; i < N_PAIRED_POOLS; i++)
1243    {
1244    pooldesc * pp = paired_pools + i;
1245    debug_printf("----Exit  pool %2d max: %3d kB in %d blocks at order %u\t%s %s\n",
1246     i, (pp->maxbytes+1023)/1024, pp->maxblocks, pp->maxorder,
1247     poolclass[i], pooluse[i]);
1248    }
1249  i = 0;
1250  for (quoted_pooldesc * qp = quoted_pools; qp; i++, qp = qp->next)
1251    {
1252    pooldesc * pp = &qp->pool;
1253    debug_printf("----Exit  pool Q%d max: %3d kB in %d blocks at order %u\ttainted quoted:%s\n",
1254     i, (pp->maxbytes+1023)/1024, pp->maxblocks, pp->maxorder, lookup_list[qp->quoter]->name);
1255    }
1256  }
1257 #endif
1258 }
1259
1260
1261 /******************************************************************************/
1262 /* Per-message pool management */
1263
1264 static rmark   message_reset_point    = NULL;
1265
1266 void
1267 message_start(void)
1268 {
1269 int oldpool = store_pool;
1270 store_pool = POOL_MESSAGE;
1271 if (!message_reset_point) message_reset_point = store_mark();
1272 store_pool = oldpool;
1273 }
1274
1275 void
1276 message_tidyup(void)
1277 {
1278 int oldpool;
1279 if (!message_reset_point) return;
1280 oldpool = store_pool;
1281 store_pool = POOL_MESSAGE;
1282 message_reset_point = store_reset(message_reset_point);
1283 store_pool = oldpool;
1284 }
1285
1286 /******************************************************************************/
1287 /* Debug analysis of address */
1288
1289 #ifndef COMPILE_UTILITY
1290 void
1291 debug_print_taint(const void * p)
1292 {
1293 int q = quoter_for_address(p);
1294 if (!is_tainted(p)) return;
1295 debug_printf("(tainted");
1296 if (is_real_quoter(q)) debug_printf(", quoted:%s", lookup_list[q]->name);
1297 debug_printf(")\n");
1298 }
1299 #endif
1300
1301 /* End of store.c */