summaryrefslogtreecommitdiff
path: root/src/microhttpd/memorypool.c
blob: 4a890967529c325a501bc1c1d0370174612e3f63 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
/*
     This file is part of libmicrohttpd
     Copyright (C) 2007--2019 Daniel Pittman, Christian Grothoff and
     Karlson2k (Evgeny Grin)

     This library is free software; you can redistribute it and/or
     modify it under the terms of the GNU Lesser General Public
     License as published by the Free Software Foundation; either
     version 2.1 of the License, or (at your option) any later version.

     This library is distributed in the hope that it will be useful,
     but WITHOUT ANY WARRANTY; without even the implied warranty of
     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
     Lesser General Public License for more details.

     You should have received a copy of the GNU Lesser General Public
     License along with this library; if not, write to the Free Software
     Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
*/

/**
 * @file memorypool.c
 * @brief memory pool
 * @author Christian Grothoff
 * @author Karlson2k (Evgeny Grin)
 */
#include "memorypool.h"
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include "mhd_assert.h"
#if HAVE_SYS_MMAN_H
#include <sys/mman.h>
#endif
#ifdef _WIN32
#include <memoryapi.h>
#endif

/* define MAP_ANONYMOUS for Mac OS X */
#if defined(MAP_ANON) && !defined(MAP_ANONYMOUS)
#define MAP_ANONYMOUS MAP_ANON
#endif
#if defined(_WIN32)
#define MAP_FAILED NULL
#elif ! defined(MAP_FAILED)
#define MAP_FAILED ((void*)-1)
#endif

/**
 * Align to 2x word size (as GNU libc does).
 */
#define ALIGN_SIZE (2 * sizeof(void*))

/**
 * Round up 'n' to a multiple of ALIGN_SIZE.
 */
#define ROUND_TO_ALIGN(n) (((n)+(ALIGN_SIZE-1)) & (~(ALIGN_SIZE-1)))


/**
 * Handle for a memory pool.  Pools are not reentrant and must not be
 * used by multiple threads.
 */
struct MemoryPool
{

  /**
   * Pointer to the pool's memory
   */
  uint8_t *memory;

  /**
   * Size of the pool.
   */
  size_t size;

  /**
   * Offset of the first unallocated byte.
   */
  size_t pos;

  /**
   * Offset of the byte after the last unallocated byte.
   */
  size_t end;

  /**
   * 'false' if pool was malloc'ed, 'true' if mmapped (VirtualAlloc'ed for W32).
   */
  bool is_mmap;
};


/**
 * Create a memory pool.
 *
 * @param max maximum size of the pool
 * @return NULL on error
 */
struct MemoryPool *
MHD_pool_create (size_t max)
{
  struct MemoryPool *pool;

  max = ROUND_TO_ALIGN(max);
  pool = malloc (sizeof (struct MemoryPool));
  if (NULL == pool)
    return NULL;
#if defined(MAP_ANONYMOUS) || defined(_WIN32)
  if (max <= 32 * 1024)
    pool->memory = MAP_FAILED;
  else
#if defined(MAP_ANONYMOUS) && !defined(_WIN32)
    pool->memory = mmap (NULL,
                         max,
                         PROT_READ | PROT_WRITE,
			 MAP_PRIVATE | MAP_ANONYMOUS,
                         -1,
                         0);
#elif defined(_WIN32)
    pool->memory = VirtualAlloc (NULL,
                                 max,
                                 MEM_COMMIT | MEM_RESERVE,
                                 PAGE_READWRITE);
#endif
#else
  pool->memory = MAP_FAILED;
#endif
  if ( (MAP_FAILED == pool->memory) ||
       (NULL == pool->memory))
    {
      pool->memory = malloc (max);
      if (NULL == pool->memory)
        {
          free (pool);
          return NULL;
        }
      pool->is_mmap = false;
    }
  else
    {
      pool->is_mmap = true;
    }
  pool->pos = 0;
  pool->end = max;
  pool->size = max;
  return pool;
}


/**
 * Destroy a memory pool.
 *
 * @param pool memory pool to destroy
 */
void
MHD_pool_destroy (struct MemoryPool *pool)
{
  if (NULL == pool)
    return;

  mhd_assert (pool->end >= pool->pos);
  mhd_assert (pool->size >= pool->end - pool->pos);
  if (!pool->is_mmap)
    free (pool->memory);
  else
#if defined(MAP_ANONYMOUS) && !defined(_WIN32)
    munmap (pool->memory,
            pool->size);
#elif defined(_WIN32)
    VirtualFree (pool->memory,
                 0,
                 MEM_RELEASE);
#else
    abort ();
#endif
  free (pool);
}


/**
 * Check how much memory is left in the @a pool
 *
 * @param pool pool to check
 * @return number of bytes still available in @a pool
 */
size_t
MHD_pool_get_free (struct MemoryPool *pool)
{
  mhd_assert (pool->end >= pool->pos);
  mhd_assert (pool->size >= pool->end - pool->pos);
  return (pool->end - pool->pos);
}


/**
 * Allocate size bytes from the pool.
 *
 * @param pool memory pool to use for the operation
 * @param size number of bytes to allocate
 * @param from_end allocate from end of pool (set to 'true');
 *        use this for small, persistent allocations that
 *        will never be reallocated
 * @return NULL if the pool cannot support size more
 *         bytes
 */
void *
MHD_pool_allocate (struct MemoryPool *pool,
		   size_t size,
                   bool from_end)
{
  void *ret;
  size_t asize;

  mhd_assert (pool->end >= pool->pos);
  mhd_assert (pool->size >= pool->end - pool->pos);
  asize = ROUND_TO_ALIGN (size);
  if ( (0 == asize) && (0 != size) )
    return NULL; /* size too close to SIZE_MAX */
  if ( (pool->pos + asize > pool->end) ||
       (pool->pos + asize < pool->pos))
    return NULL;
  if (from_end)
    {
      ret = &pool->memory[pool->end - asize];
      pool->end -= asize;
    }
  else
    {
      ret = &pool->memory[pool->pos];
      pool->pos += asize;
    }
  return ret;
}


/**
 * Reallocate a block of memory obtained from the pool.
 * This is particularly efficient when growing or
 * shrinking the block that was last (re)allocated.
 * If the given block is not the most recently
 * (re)allocated block, the memory of the previous
 * allocation may be leaked until the pool is
 * destroyed or reset.
 *
 * @param pool memory pool to use for the operation
 * @param old the existing block
 * @param old_size the size of the existing block
 * @param new_size the new size of the block
 * @return new address of the block, or
 *         NULL if the pool cannot support @a new_size
 *         bytes (old continues to be valid for @a old_size)
 */
void *
MHD_pool_reallocate (struct MemoryPool *pool,
                     void *old,
		     size_t old_size,
		     size_t new_size)
{
  size_t asize;
  uint8_t *new_blc;

  mhd_assert (pool->end >= pool->pos);
  mhd_assert (pool->size >= pool->end - pool->pos);
  mhd_assert (old != NULL || old_size == 0);
  mhd_assert (old == NULL || pool->memory <= (uint8_t*)old);
  mhd_assert (old == NULL || pool->memory + pool->size >= (uint8_t*)old + old_size);
  /* Blocks "from the end" must not be reallocated */
  mhd_assert (old == NULL || pool->memory + pool->pos > (uint8_t*)old);

  if (pool->memory + new_size + 2 * ALIGN_SIZE< pool->memory)
    return NULL; /* Value wrap, too large new_size. */

  if (0 != old_size)
    { /* Need to relocate data */
      const size_t old_offset = (uint8_t*)old - pool->memory;

      if (pool->pos == ROUND_TO_ALIGN (old_offset + old_size))
        { /* "old" block is the last allocated block */
          const size_t new_apos = ROUND_TO_ALIGN (old_offset + new_size);
          if (new_apos > pool->end)
            return NULL; /* No space */

          pool->pos = new_apos;
          /* Zero-out unused part if shrinking */
          if (old_size > new_size)
            memset (old + new_size, 0, old_size - new_size);
          return old;
        }
    }
  /* Need to allocate new block */
  asize = ROUND_TO_ALIGN (new_size);
  if (asize > pool->end - pool->pos)
    return NULL; /* No space */

  new_blc = pool->memory + pool->pos;
  pool->pos += asize;

  if (0 != old_size)
    {
      /* Move data no new block, old block remains allocated */
      memcpy (new_blc, old, old_size);
      /* Zero-out old block */
      memset (old, 0, old_size);
    }
  return new_blc;
}


/**
 * Clear all entries from the memory pool except
 * for @a keep of the given @a size. The pointer
 * returned should be a buffer of @a new_size where
 * the first @a copy_bytes are from @a keep.
 *
 * @param pool memory pool to use for the operation
 * @param keep pointer to the entry to keep (maybe NULL)
 * @param copy_bytes how many bytes need to be kept at this address
 * @param new_size how many bytes should the allocation we return have?
 *                 (should be larger or equal to @a copy_bytes)
 * @return addr new address of @a keep (if it had to change)
 */
void *
MHD_pool_reset (struct MemoryPool *pool,
		void *keep,
		size_t copy_bytes,
                size_t new_size)
{
  mhd_assert (pool->end >= pool->pos);
  mhd_assert (pool->size >= pool->end - pool->pos);
  mhd_assert (keep != NULL || copy_bytes == 0);
  mhd_assert (keep == NULL || pool->memory <= (uint8_t*)keep);
  mhd_assert (keep == NULL || pool->memory + pool->size >= (uint8_t*)keep + copy_bytes);
  if ( (NULL != keep) &&
       (keep != pool->memory) )
    {
      if (0 != copy_bytes)
        memmove (pool->memory,
                 keep,
                 copy_bytes);
      keep = pool->memory;
    }
  pool->end = pool->size;
  /* technically not needed, but safer to zero out */
  if (pool->size > copy_bytes)
    memset (&pool->memory[copy_bytes],
            0,
            pool->size - copy_bytes);
  if (NULL != keep)
    pool->pos = ROUND_TO_ALIGN (new_size);
  return keep;
}


/* end of memorypool.c */