Builtin macros for sha3-hash and ed25519-signing support
[exim.git] / src / src / store.c
CommitLineData
059ec3d9
PH
1/*************************************************
2* Exim - an Internet mail transport agent *
3*************************************************/
4
9242a7e8 5/* Copyright (c) University of Cambridge 1995 - 2017 */
059ec3d9
PH
6/* See the file NOTICE for conditions of use and distribution. */
7
8/* Exim gets and frees all its store through these functions. In the original
9implementation there was a lot of mallocing and freeing of small bits of store.
10The philosophy has now changed to a scheme which includes the concept of
11"stacking pools" of store. For the short-lived processes, there isn't any real
12need to do any garbage collection, but the stack concept allows quick resetting
13in places where this seems sensible.
14
15Obviously the long-running processes (the daemon, the queue runner, and eximon)
16must take care not to eat store.
17
18The following different types of store are recognized:
19
20. Long-lived, large blocks: This is implemented by retaining the original
21 malloc/free functions, and it used for permanent working buffers and for
22 getting blocks to cut up for the other types.
23
24. Long-lived, small blocks: This is used for blocks that have to survive until
25 the process exits. It is implemented as a stacking pool (POOL_PERM). This is
26 functionally the same as store_malloc(), except that the store can't be
27 freed, but I expect it to be more efficient for handling small blocks.
28
29. Short-lived, short blocks: Most of the dynamic store falls into this
30 category. It is implemented as a stacking pool (POOL_MAIN) which is reset
31 after accepting a message when multiple messages are received by a single
32 process. Resetting happens at some other times as well, usually fairly
33 locally after some specific processing that needs working store.
34
35. There is a separate pool (POOL_SEARCH) that is used only for lookup storage.
36 This means it can be freed when search_tidyup() is called to close down all
37 the lookup caching.
38*/
39
40
41#include "exim.h"
438257ba
PP
42/* keep config.h before memcheck.h, for NVALGRIND */
43#include "config.h"
44
7f36d675 45#include "memcheck.h"
059ec3d9
PH
46
47
48/* We need to know how to align blocks of data for general use. I'm not sure
49how to get an alignment factor in general. In the current world, a value of 8
50is probably right, and this is sizeof(double) on some systems and sizeof(void
51*) on others, so take the larger of those. Since everything in this expression
52is a constant, the compiler should optimize it to a simple constant wherever it
53appears (I checked that gcc does do this). */
54
55#define alignment \
56 ((sizeof(void *) > sizeof(double))? sizeof(void *) : sizeof(double))
57
58/* Size of block to get from malloc to carve up into smaller ones. This
59must be a multiple of the alignment. We assume that 8192 is going to be
60suitably aligned. */
61
62#define STORE_BLOCK_SIZE 8192
63
64/* store_reset() will not free the following block if the last used block has
65less than this much left in it. */
66
67#define STOREPOOL_MIN_SIZE 256
68
69/* Structure describing the beginning of each big block. */
70
71typedef struct storeblock {
72 struct storeblock *next;
73 size_t length;
74} storeblock;
75
76/* Just in case we find ourselves on a system where the structure above has a
77length that is not a multiple of the alignment, set up a macro for the padded
78length. */
79
80#define ALIGNED_SIZEOF_STOREBLOCK \
81 (((sizeof(storeblock) + alignment - 1) / alignment) * alignment)
82
83/* Variables holding data for the local pools of store. The current pool number
84is held in store_pool, which is global so that it can be changed from outside.
85Setting the initial length values to -1 forces a malloc for the first call,
86even if the length is zero (which is used for getting a point to reset to). */
87
88int store_pool = POOL_PERM;
89
90static storeblock *chainbase[3] = { NULL, NULL, NULL };
91static storeblock *current_block[3] = { NULL, NULL, NULL };
92static void *next_yield[3] = { NULL, NULL, NULL };
93static int yield_length[3] = { -1, -1, -1 };
94
95/* pool_malloc holds the amount of memory used by the store pools; this goes up
96and down as store is reset or released. nonpool_malloc is the total got by
97malloc from other calls; this doesn't go down because it is just freed by
98pointer. */
99
100static int pool_malloc = 0;
101static int nonpool_malloc = 0;
102
103/* This variable is set by store_get() to its yield, and by store_reset() to
104NULL. This enables string_cat() to optimize its store handling for very long
105strings. That's why the variable is global. */
106
107void *store_last_get[3] = { NULL, NULL, NULL };
108
109
110
111/*************************************************
112* Get a block from the current pool *
113*************************************************/
114
115/* Running out of store is a total disaster. This function is called via the
116macro store_get(). It passes back a block of store within the current big
117block, getting a new one if necessary. The address is saved in
118store_last_was_get.
119
120Arguments:
121 size amount wanted
122 filename source file from which called
123 linenumber line number in source file.
124
125Returns: pointer to store (panic on malloc failure)
126*/
127
128void *
129store_get_3(int size, const char *filename, int linenumber)
130{
131/* Round up the size to a multiple of the alignment. Although this looks a
132messy statement, because "alignment" is a constant expression, the compiler can
133do a reasonable job of optimizing, especially if the value of "alignment" is a
134power of two. I checked this with -O2, and gcc did very well, compiling it to 4
135instructions on a Sparc (alignment = 8). */
136
137if (size % alignment != 0) size += alignment - (size % alignment);
138
139/* If there isn't room in the current block, get a new one. The minimum
140size is STORE_BLOCK_SIZE, and we would expect this to be the norm, since
141these functions are mostly called for small amounts of store. */
142
143if (size > yield_length[store_pool])
144 {
145 int length = (size <= STORE_BLOCK_SIZE)? STORE_BLOCK_SIZE : size;
146 int mlength = length + ALIGNED_SIZEOF_STOREBLOCK;
64073d9c 147 storeblock * newblock = NULL;
059ec3d9
PH
148
149 /* Sometimes store_reset() may leave a block for us; check if we can use it */
150
64073d9c
JH
151 if ( (newblock = current_block[store_pool])
152 && (newblock = newblock->next)
153 && newblock->length < length
154 )
059ec3d9 155 {
64073d9c
JH
156 /* Give up on this block, because it's too small */
157 store_free(newblock);
158 newblock = NULL;
059ec3d9
PH
159 }
160
161 /* If there was no free block, get a new one */
162
64073d9c 163 if (!newblock)
059ec3d9
PH
164 {
165 pool_malloc += mlength; /* Used in pools */
166 nonpool_malloc -= mlength; /* Exclude from overall total */
167 newblock = store_malloc(mlength);
168 newblock->next = NULL;
169 newblock->length = length;
64073d9c
JH
170 if (!chainbase[store_pool])
171 chainbase[store_pool] = newblock;
172 else
173 current_block[store_pool]->next = newblock;
059ec3d9
PH
174 }
175
176 current_block[store_pool] = newblock;
177 yield_length[store_pool] = newblock->length;
178 next_yield[store_pool] =
64073d9c 179 (void *)(CS current_block[store_pool] + ALIGNED_SIZEOF_STOREBLOCK);
4d8bb202 180 (void) VALGRIND_MAKE_MEM_NOACCESS(next_yield[store_pool], yield_length[store_pool]);
059ec3d9
PH
181 }
182
183/* There's (now) enough room in the current block; the yield is the next
184pointer. */
185
186store_last_get[store_pool] = next_yield[store_pool];
187
188/* Cut out the debugging stuff for utilities, but stop picky compilers from
189giving warnings. */
190
191#ifdef COMPILE_UTILITY
192filename = filename;
193linenumber = linenumber;
194#else
195DEBUG(D_memory)
196 {
197 if (running_in_test_harness)
198 debug_printf("---%d Get %5d\n", store_pool, size);
199 else
200 debug_printf("---%d Get %6p %5d %-14s %4d\n", store_pool,
201 store_last_get[store_pool], size, filename, linenumber);
202 }
203#endif /* COMPILE_UTILITY */
204
4d8bb202 205(void) VALGRIND_MAKE_MEM_UNDEFINED(store_last_get[store_pool], size);
059ec3d9
PH
206/* Update next pointer and number of bytes left in the current block. */
207
5903c6ff 208next_yield[store_pool] = (void *)(CS next_yield[store_pool] + size);
059ec3d9
PH
209yield_length[store_pool] -= size;
210
211return store_last_get[store_pool];
212}
213
214
215
216/*************************************************
217* Get a block from the PERM pool *
218*************************************************/
219
220/* This is just a convenience function, useful when just a single block is to
221be obtained.
222
223Arguments:
224 size amount wanted
225 filename source file from which called
226 linenumber line number in source file.
227
228Returns: pointer to store (panic on malloc failure)
229*/
230
231void *
232store_get_perm_3(int size, const char *filename, int linenumber)
233{
234void *yield;
235int old_pool = store_pool;
236store_pool = POOL_PERM;
237yield = store_get_3(size, filename, linenumber);
238store_pool = old_pool;
239return yield;
240}
241
242
243
244/*************************************************
245* Extend a block if it is at the top *
246*************************************************/
247
248/* While reading strings of unknown length, it is often the case that the
249string is being read into the block at the top of the stack. If it needs to be
250extended, it is more efficient just to extend the top block rather than
251allocate a new block and then have to copy the data. This function is provided
252for the use of string_cat(), but of course can be used elsewhere too.
253
254Arguments:
255 ptr pointer to store block
256 oldsize current size of the block, as requested by user
257 newsize new size required
258 filename source file from which called
259 linenumber line number in source file
260
261Returns: TRUE if the block is at the top of the stack and has been
262 extended; FALSE if it isn't at the top of the stack, or cannot
263 be extended
264*/
265
266BOOL
267store_extend_3(void *ptr, int oldsize, int newsize, const char *filename,
268 int linenumber)
269{
270int inc = newsize - oldsize;
271int rounded_oldsize = oldsize;
272
273if (rounded_oldsize % alignment != 0)
274 rounded_oldsize += alignment - (rounded_oldsize % alignment);
275
5903c6ff 276if (CS ptr + rounded_oldsize != CS (next_yield[store_pool]) ||
059ec3d9
PH
277 inc > yield_length[store_pool] + rounded_oldsize - oldsize)
278 return FALSE;
279
280/* Cut out the debugging stuff for utilities, but stop picky compilers from
281giving warnings. */
282
283#ifdef COMPILE_UTILITY
284filename = filename;
285linenumber = linenumber;
286#else
287DEBUG(D_memory)
288 {
289 if (running_in_test_harness)
290 debug_printf("---%d Ext %5d\n", store_pool, newsize);
291 else
292 debug_printf("---%d Ext %6p %5d %-14s %4d\n", store_pool, ptr, newsize,
293 filename, linenumber);
294 }
295#endif /* COMPILE_UTILITY */
296
297if (newsize % alignment != 0) newsize += alignment - (newsize % alignment);
5903c6ff 298next_yield[store_pool] = CS ptr + newsize;
059ec3d9 299yield_length[store_pool] -= newsize - rounded_oldsize;
4d8bb202 300(void) VALGRIND_MAKE_MEM_UNDEFINED(ptr + oldsize, inc);
059ec3d9
PH
301return TRUE;
302}
303
304
305
306
307/*************************************************
308* Back up to a previous point on the stack *
309*************************************************/
310
311/* This function resets the next pointer, freeing any subsequent whole blocks
312that are now unused. Normally it is given a pointer that was the yield of a
313call to store_get, and is therefore aligned, but it may be given an offset
314after such a pointer in order to release the end of a block and anything that
315follows.
316
317Arguments:
318 ptr place to back up to
319 filename source file from which called
320 linenumber line number in source file
321
322Returns: nothing
323*/
324
325void
326store_reset_3(void *ptr, const char *filename, int linenumber)
327{
cf0812d5
JH
328storeblock * bb;
329storeblock * b = current_block[store_pool];
330char * bc = CS b + ALIGNED_SIZEOF_STOREBLOCK;
059ec3d9
PH
331int newlength;
332
333/* Last store operation was not a get */
334
335store_last_get[store_pool] = NULL;
336
337/* See if the place is in the current block - as it often will be. Otherwise,
338search for the block in which it lies. */
339
cf0812d5 340if (CS ptr < bc || CS ptr > bc + b->length)
059ec3d9 341 {
cf0812d5 342 for (b = chainbase[store_pool]; b; b = b->next)
059ec3d9 343 {
cf0812d5
JH
344 bc = CS b + ALIGNED_SIZEOF_STOREBLOCK;
345 if (CS ptr >= bc && CS ptr <= bc + b->length) break;
059ec3d9 346 }
cf0812d5 347 if (!b)
438257ba 348 log_write(0, LOG_MAIN|LOG_PANIC_DIE, "internal error: store_reset(%p) "
059ec3d9
PH
349 "failed: pool=%d %-14s %4d", ptr, store_pool, filename, linenumber);
350 }
351
352/* Back up, rounding to the alignment if necessary. When testing, flatten
353the released memory. */
354
cf0812d5 355newlength = bc + b->length - CS ptr;
059ec3d9 356#ifndef COMPILE_UTILITY
64073d9c 357if (running_in_test_harness || debug_store)
2c9f7ff8 358 {
cf0812d5 359 assert_no_variables(ptr, newlength, filename, linenumber);
64073d9c
JH
360 if (running_in_test_harness)
361 {
362 (void) VALGRIND_MAKE_MEM_DEFINED(ptr, newlength);
363 memset(ptr, 0xF0, newlength);
364 }
2c9f7ff8 365 }
059ec3d9 366#endif
4d8bb202 367(void) VALGRIND_MAKE_MEM_NOACCESS(ptr, newlength);
059ec3d9 368yield_length[store_pool] = newlength - (newlength % alignment);
cf0812d5 369next_yield[store_pool] = CS ptr + (newlength % alignment);
059ec3d9
PH
370current_block[store_pool] = b;
371
372/* Free any subsequent block. Do NOT free the first successor, if our
373current block has less than 256 bytes left. This should prevent us from
374flapping memory. However, keep this block only when it has the default size. */
375
376if (yield_length[store_pool] < STOREPOOL_MIN_SIZE &&
cf0812d5 377 b->next &&
059ec3d9 378 b->next->length == STORE_BLOCK_SIZE)
7f36d675 379 {
059ec3d9 380 b = b->next;
cf0812d5 381#ifndef COMPILE_UTILITY
64073d9c 382 if (running_in_test_harness || debug_store)
cf0812d5
JH
383 assert_no_variables(b, b->length + ALIGNED_SIZEOF_STOREBLOCK,
384 filename, linenumber);
385#endif
386 (void) VALGRIND_MAKE_MEM_NOACCESS(CS b + ALIGNED_SIZEOF_STOREBLOCK,
4d8bb202 387 b->length - ALIGNED_SIZEOF_STOREBLOCK);
7f36d675 388 }
059ec3d9
PH
389
390bb = b->next;
391b->next = NULL;
392
cf0812d5 393while ((b = bb))
059ec3d9 394 {
cf0812d5 395#ifndef COMPILE_UTILITY
64073d9c 396 if (running_in_test_harness || debug_store)
cf0812d5
JH
397 assert_no_variables(b, b->length + ALIGNED_SIZEOF_STOREBLOCK,
398 filename, linenumber);
399#endif
059ec3d9
PH
400 bb = bb->next;
401 pool_malloc -= b->length + ALIGNED_SIZEOF_STOREBLOCK;
402 store_free_3(b, filename, linenumber);
403 }
404
405/* Cut out the debugging stuff for utilities, but stop picky compilers from
406giving warnings. */
407
408#ifdef COMPILE_UTILITY
409filename = filename;
410linenumber = linenumber;
411#else
412DEBUG(D_memory)
413 {
414 if (running_in_test_harness)
415 debug_printf("---%d Rst ** %d\n", store_pool, pool_malloc);
416 else
417 debug_printf("---%d Rst %6p ** %-14s %4d %d\n", store_pool, ptr,
418 filename, linenumber, pool_malloc);
419 }
420#endif /* COMPILE_UTILITY */
421}
422
423
424
425
426
427/************************************************
428* Release store *
429************************************************/
430
459fca58
JH
431/* This function checks that the pointer it is given is the first thing in a
432block, and if so, releases that block.
059ec3d9
PH
433
434Arguments:
435 block block of store to consider
436 filename source file from which called
437 linenumber line number in source file
438
439Returns: nothing
440*/
441
459fca58
JH
442static void
443store_release_3(void * block, const char * filename, int linenumber)
059ec3d9 444{
459fca58 445storeblock * b;
059ec3d9
PH
446
447/* It will never be the first block, so no need to check that. */
448
459fca58 449for (b = chainbase[store_pool]; b; b = b->next)
059ec3d9 450 {
459fca58
JH
451 storeblock * bb = b->next;
452 if (bb && CS block == CS bb + ALIGNED_SIZEOF_STOREBLOCK)
059ec3d9
PH
453 {
454 b->next = bb->next;
455 pool_malloc -= bb->length + ALIGNED_SIZEOF_STOREBLOCK;
456
457 /* Cut out the debugging stuff for utilities, but stop picky compilers
458 from giving warnings. */
459
459fca58 460#ifdef COMPILE_UTILITY
059ec3d9
PH
461 filename = filename;
462 linenumber = linenumber;
459fca58 463#else
059ec3d9 464 DEBUG(D_memory)
059ec3d9
PH
465 if (running_in_test_harness)
466 debug_printf("-Release %d\n", pool_malloc);
467 else
468 debug_printf("-Release %6p %-20s %4d %d\n", (void *)bb, filename,
469 linenumber, pool_malloc);
459fca58 470
059ec3d9
PH
471 if (running_in_test_harness)
472 memset(bb, 0xF0, bb->length+ALIGNED_SIZEOF_STOREBLOCK);
459fca58 473#endif /* COMPILE_UTILITY */
059ec3d9
PH
474
475 free(bb);
476 return;
477 }
478 }
479}
480
481
459fca58
JH
482/************************************************
483* Move store *
484************************************************/
485
486/* Allocate a new block big enough to expend to the given size and
487copy the current data into it. Free the old one if possible.
488
489This function is specifically provided for use when reading very
490long strings, e.g. header lines. When the string gets longer than a
491complete block, it gets copied to a new block. It is helpful to free
492the old block iff the previous copy of the string is at its start,
493and therefore the only thing in it. Otherwise, for very long strings,
494dead store can pile up somewhat disastrously. This function checks that
495the pointer it is given is the first thing in a block, and that nothing
496has been allocated since. If so, releases that block.
497
498Arguments:
499 block
500 newsize
501 len
502
503Returns: new location of data
504*/
505
506void *
507store_newblock_3(void * block, int newsize, int len,
508 const char * filename, int linenumber)
509{
510BOOL release_ok = store_last_get[store_pool] == block;
511uschar * newtext = store_get(newsize);
512
513memcpy(newtext, block, len);
514if (release_ok) store_release_3(block, filename, linenumber);
515return (void *)newtext;
516}
517
518
059ec3d9
PH
519
520
521/*************************************************
522* Malloc store *
523*************************************************/
524
525/* Running out of store is a total disaster for exim. Some malloc functions
526do not run happily on very small sizes, nor do they document this fact. This
527function is called via the macro store_malloc().
528
529Arguments:
530 size amount of store wanted
531 filename source file from which called
532 linenumber line number in source file
533
534Returns: pointer to gotten store (panic on failure)
535*/
536
537void *
538store_malloc_3(int size, const char *filename, int linenumber)
539{
540void *yield;
541
542if (size < 16) size = 16;
059ec3d9 543
40c90bca 544if (!(yield = malloc((size_t)size)))
059ec3d9
PH
545 log_write(0, LOG_MAIN|LOG_PANIC_DIE, "failed to malloc %d bytes of memory: "
546 "called from line %d of %s", size, linenumber, filename);
547
548nonpool_malloc += size;
549
550/* Cut out the debugging stuff for utilities, but stop picky compilers from
551giving warnings. */
552
553#ifdef COMPILE_UTILITY
554filename = filename;
555linenumber = linenumber;
556#else
557
558/* If running in test harness, spend time making sure all the new store
559is not filled with zeros so as to catch problems. */
560
561if (running_in_test_harness)
562 {
563 memset(yield, 0xF0, (size_t)size);
564 DEBUG(D_memory) debug_printf("--Malloc %5d %d %d\n", size, pool_malloc,
565 nonpool_malloc);
566 }
567else
568 {
569 DEBUG(D_memory) debug_printf("--Malloc %6p %5d %-14s %4d %d %d\n", yield,
570 size, filename, linenumber, pool_malloc, nonpool_malloc);
571 }
572#endif /* COMPILE_UTILITY */
573
574return yield;
575}
576
577
578/************************************************
579* Free store *
580************************************************/
581
582/* This function is called by the macro store_free().
583
584Arguments:
585 block block of store to free
586 filename source file from which called
587 linenumber line number in source file
588
589Returns: nothing
590*/
591
592void
593store_free_3(void *block, const char *filename, int linenumber)
594{
595#ifdef COMPILE_UTILITY
596filename = filename;
597linenumber = linenumber;
598#else
599DEBUG(D_memory)
600 {
601 if (running_in_test_harness)
602 debug_printf("----Free\n");
603 else
604 debug_printf("----Free %6p %-20s %4d\n", block, filename, linenumber);
605 }
606#endif /* COMPILE_UTILITY */
607free(block);
608}
609
610/* End of store.c */