1 /**
2 * @file
3 * Dynamic memory manager
4 *
5 * This is a lightweight replacement for the standard C library malloc().
6 *
7 * If you want to use the standard C library malloc() instead, define
8 * MEM_LIBC_MALLOC to 1 in your lwipopts.h
9 *
10 * To let mem_malloc() use pools (prevents fragmentation and is much faster than
11 * a heap but might waste some memory), define MEM_USE_POOLS to 1, define
12 * MEMP_USE_CUSTOM_POOLS to 1 and create a file "lwippools.h" that includes a list
13 * of pools like this (more pools can be added between _START and _END):
14 *
15 * Define three pools with sizes 256, 512, and 1512 bytes
16 * LWIP_MALLOC_MEMPOOL_START
17 * LWIP_MALLOC_MEMPOOL(20, 256)
18 * LWIP_MALLOC_MEMPOOL(10, 512)
19 * LWIP_MALLOC_MEMPOOL(5, 1512)
20 * LWIP_MALLOC_MEMPOOL_END
21 */
22
23 /*
24 * Copyright (c) 2001-2004 Swedish Institute of Computer Science.
25 * All rights reserved.
26 *
27 * Redistribution and use in source and binary forms, with or without modification,
28 * are permitted provided that the following conditions are met:
29 *
30 * 1. Redistributions of source code must retain the above copyright notice,
31 * this list of conditions and the following disclaimer.
32 * 2. Redistributions in binary form must reproduce the above copyright notice,
33 * this list of conditions and the following disclaimer in the documentation
34 * and/or other materials provided with the distribution.
35 * 3. The name of the author may not be used to endorse or promote products
36 * derived from this software without specific prior written permission.
37 *
38 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
39 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
40 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
41 * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
42 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
43 * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
44 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
45 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
46 * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
47 * OF SUCH DAMAGE.
48 *
49 * This file is part of the lwIP TCP/IP stack.
50 *
51 * Author: Adam Dunkels <adam@sics.se>
52 * Simon Goldschmidt
53 *
54 */
55
56 #include "lwip/opt.h"
57 #include "lwip/mem.h"
58 #include "lwip/def.h"
59 #include "lwip/sys.h"
60 #include "lwip/stats.h"
61 #include "lwip/err.h"
62
63 #include <stdio.h> /* snprintf */
64 #include <string.h>
65
66 #if MEM_LIBC_MALLOC
67 #include <stdlib.h> /* for malloc()/free() */
68 #endif
69
70 /* This is overridable for tests only... */
71 #ifndef LWIP_MEM_ILLEGAL_FREE
72 #define LWIP_MEM_ILLEGAL_FREE(msg) LWIP_ASSERT(msg, 0)
73 #endif
74
75 #define MEM_STATS_INC_LOCKED(x) SYS_ARCH_LOCKED(MEM_STATS_INC(x))
76 #define MEM_STATS_INC_USED_LOCKED(x, y) SYS_ARCH_LOCKED(MEM_STATS_INC_USED(x, y))
77 #define MEM_STATS_DEC_USED_LOCKED(x, y) SYS_ARCH_LOCKED(MEM_STATS_DEC_USED(x, y))
78
79 #if MEM_OVERFLOW_CHECK
80 #define MEM_SANITY_OFFSET MEM_SANITY_REGION_BEFORE_ALIGNED
81 #define MEM_SANITY_OVERHEAD (MEM_SANITY_REGION_BEFORE_ALIGNED + MEM_SANITY_REGION_AFTER_ALIGNED)
82 #else
83 #define MEM_SANITY_OFFSET 0
84 #define MEM_SANITY_OVERHEAD 0
85 #endif
86
87 #if MEM_OVERFLOW_CHECK || MEMP_OVERFLOW_CHECK
88 /**
89 * Check if a mep element was victim of an overflow or underflow
90 * (e.g. the restricted area after/before it has been altered)
91 *
92 * @param p the mem element to check
93 * @param size allocated size of the element
94 * @param descr1 description of the element source shown on error
95 * @param descr2 description of the element source shown on error
96 */
97 void
mem_overflow_check_raw(void * p,size_t size,const char * descr1,const char * descr2)98 mem_overflow_check_raw(void *p, size_t size, const char *descr1, const char *descr2)
99 {
100 #if MEM_SANITY_REGION_AFTER_ALIGNED || MEM_SANITY_REGION_BEFORE_ALIGNED
101 u16_t k;
102 u8_t *m;
103
104 #if MEM_SANITY_REGION_AFTER_ALIGNED > 0
105 m = (u8_t *)p + size;
106 for (k = 0; k < MEM_SANITY_REGION_AFTER_ALIGNED; k++) {
107 if (m[k] != 0xcd) {
108 char errstr[128];
109 snprintf(errstr, sizeof(errstr), "detected mem overflow in %s%s", descr1, descr2);
110 LWIP_ASSERT(errstr, 0);
111 }
112 }
113 #endif /* MEM_SANITY_REGION_AFTER_ALIGNED > 0 */
114
115 #if MEM_SANITY_REGION_BEFORE_ALIGNED > 0
116 m = (u8_t *)p - MEM_SANITY_REGION_BEFORE_ALIGNED;
117 for (k = 0; k < MEM_SANITY_REGION_BEFORE_ALIGNED; k++) {
118 if (m[k] != 0xcd) {
119 char errstr[128];
120 snprintf(errstr, sizeof(errstr), "detected mem underflow in %s%s", descr1, descr2);
121 LWIP_ASSERT(errstr, 0);
122 }
123 }
124 #endif /* MEM_SANITY_REGION_BEFORE_ALIGNED > 0 */
125 #else
126 LWIP_UNUSED_ARG(p);
127 LWIP_UNUSED_ARG(desc);
128 LWIP_UNUSED_ARG(descr);
129 #endif
130 }
131
132 /**
133 * Initialize the restricted area of a mem element.
134 */
135 void
mem_overflow_init_raw(void * p,size_t size)136 mem_overflow_init_raw(void *p, size_t size)
137 {
138 #if MEM_SANITY_REGION_BEFORE_ALIGNED > 0 || MEM_SANITY_REGION_AFTER_ALIGNED > 0
139 u8_t *m;
140 #if MEM_SANITY_REGION_BEFORE_ALIGNED > 0
141 m = (u8_t *)p - MEM_SANITY_REGION_BEFORE_ALIGNED;
142 memset(m, 0xcd, MEM_SANITY_REGION_BEFORE_ALIGNED);
143 #endif
144 #if MEM_SANITY_REGION_AFTER_ALIGNED > 0
145 m = (u8_t *)p + size;
146 memset(m, 0xcd, MEM_SANITY_REGION_AFTER_ALIGNED);
147 #endif
148 #else /* MEM_SANITY_REGION_BEFORE_ALIGNED > 0 || MEM_SANITY_REGION_AFTER_ALIGNED > 0 */
149 LWIP_UNUSED_ARG(p);
150 LWIP_UNUSED_ARG(desc);
151 #endif /* MEM_SANITY_REGION_BEFORE_ALIGNED > 0 || MEM_SANITY_REGION_AFTER_ALIGNED > 0 */
152 }
153 #endif /* MEM_OVERFLOW_CHECK || MEMP_OVERFLOW_CHECK */
154
155 #if MEM_CUSTOM_ALLOCATOR || MEM_USE_POOLS
156
157 /** mem_init is not used when using pools instead of a heap or using
158 * C library malloc().
159 */
160 void
mem_init(void)161 mem_init(void)
162 {
163 }
164
165 /** mem_trim is not used when using pools instead of a heap or using
166 * C library malloc(): we can't free part of a pool element and the stack
167 * support mem_trim() to return a different pointer
168 */
169 void *
mem_trim(void * mem,mem_size_t size)170 mem_trim(void *mem, mem_size_t size)
171 {
172 LWIP_UNUSED_ARG(size);
173 return mem;
174 }
175 #endif /* MEM_CUSTOM_ALLOCATOR || MEM_USE_POOLS */
176
177 #if MEM_CUSTOM_ALLOCATOR
178
179 #if LWIP_STATS && MEM_STATS
180 #define MEM_LIBC_STATSHELPER_SIZE LWIP_MEM_ALIGN_SIZE(sizeof(mem_size_t))
181 #else
182 #define MEM_LIBC_STATSHELPER_SIZE 0
183 #endif
184
185 /**
186 * Allocate a block of memory with a minimum of 'size' bytes.
187 *
188 * @param size is the minimum size of the requested block in bytes.
189 * @return pointer to allocated memory or NULL if no free memory was found.
190 *
191 * Note that the returned value must always be aligned (as defined by MEM_ALIGNMENT).
192 */
193 void *
mem_malloc(mem_size_t size)194 mem_malloc(mem_size_t size)
195 {
196 void *ret = MEM_CUSTOM_MALLOC(size + MEM_LIBC_STATSHELPER_SIZE);
197 if (ret == NULL) {
198 MEM_STATS_INC_LOCKED(err);
199 } else {
200 LWIP_ASSERT("malloc() must return aligned memory", LWIP_MEM_ALIGN(ret) == ret);
201 #if LWIP_STATS && MEM_STATS
202 *(mem_size_t *)ret = size;
203 ret = (u8_t *)ret + MEM_LIBC_STATSHELPER_SIZE;
204 MEM_STATS_INC_USED_LOCKED(used, size);
205 #endif
206 }
207 return ret;
208 }
209
210 /** Put memory back on the heap
211 *
212 * @param rmem is the pointer as returned by a previous call to mem_malloc()
213 */
214 void
mem_free(void * rmem)215 mem_free(void *rmem)
216 {
217 LWIP_ASSERT("rmem != NULL", (rmem != NULL));
218 LWIP_ASSERT("rmem == MEM_ALIGN(rmem)", (rmem == LWIP_MEM_ALIGN(rmem)));
219 #if LWIP_STATS && MEM_STATS
220 rmem = (u8_t *)rmem - MEM_LIBC_STATSHELPER_SIZE;
221 MEM_STATS_DEC_USED_LOCKED(used, *(mem_size_t *)rmem);
222 #endif
223 MEM_CUSTOM_FREE(rmem);
224 }
225
226 #elif MEM_USE_POOLS
227
228 /* lwIP heap implemented with different sized pools */
229
230 /**
231 * Allocate memory: determine the smallest pool that is big enough
232 * to contain an element of 'size' and get an element from that pool.
233 *
234 * @param size the size in bytes of the memory needed
235 * @return a pointer to the allocated memory or NULL if the pool is empty
236 */
237 void *
mem_malloc(mem_size_t size)238 mem_malloc(mem_size_t size)
239 {
240 void *ret;
241 struct memp_malloc_helper *element = NULL;
242 memp_t poolnr;
243 mem_size_t required_size = size + LWIP_MEM_ALIGN_SIZE(sizeof(struct memp_malloc_helper));
244
245 for (poolnr = MEMP_POOL_FIRST; poolnr <= MEMP_POOL_LAST; poolnr = (memp_t)(poolnr + 1)) {
246 /* is this pool big enough to hold an element of the required size
247 plus a struct memp_malloc_helper that saves the pool this element came from? */
248 if (required_size <= memp_pools[poolnr]->size) {
249 element = (struct memp_malloc_helper *)memp_malloc(poolnr);
250 if (element == NULL) {
251 /* No need to DEBUGF or ASSERT: This error is already taken care of in memp.c */
252 #if MEM_USE_POOLS_TRY_BIGGER_POOL
253 /** Try a bigger pool if this one is empty! */
254 if (poolnr < MEMP_POOL_LAST) {
255 continue;
256 }
257 #endif /* MEM_USE_POOLS_TRY_BIGGER_POOL */
258 MEM_STATS_INC_LOCKED(err);
259 return NULL;
260 }
261 break;
262 }
263 }
264 if (poolnr > MEMP_POOL_LAST) {
265 LWIP_ASSERT("mem_malloc(): no pool is that big!", 0);
266 MEM_STATS_INC_LOCKED(err);
267 return NULL;
268 }
269
270 /* save the pool number this element came from */
271 element->poolnr = poolnr;
272 /* and return a pointer to the memory directly after the struct memp_malloc_helper */
273 ret = (u8_t *)element + LWIP_MEM_ALIGN_SIZE(sizeof(struct memp_malloc_helper));
274
275 #if MEMP_OVERFLOW_CHECK || (LWIP_STATS && MEM_STATS)
276 /* truncating to u16_t is safe because struct memp_desc::size is u16_t */
277 element->size = (u16_t)size;
278 MEM_STATS_INC_USED_LOCKED(used, element->size);
279 #endif /* MEMP_OVERFLOW_CHECK || (LWIP_STATS && MEM_STATS) */
280 #if MEMP_OVERFLOW_CHECK
281 /* initialize unused memory (diff between requested size and selected pool's size) */
282 memset((u8_t *)ret + size, 0xcd, memp_pools[poolnr]->size - size);
283 #endif /* MEMP_OVERFLOW_CHECK */
284 return ret;
285 }
286
287 /**
288 * Free memory previously allocated by mem_malloc. Loads the pool number
289 * and calls memp_free with that pool number to put the element back into
290 * its pool
291 *
292 * @param rmem the memory element to free
293 */
294 void
mem_free(void * rmem)295 mem_free(void *rmem)
296 {
297 struct memp_malloc_helper *hmem;
298
299 LWIP_ASSERT("rmem != NULL", (rmem != NULL));
300 LWIP_ASSERT("rmem == MEM_ALIGN(rmem)", (rmem == LWIP_MEM_ALIGN(rmem)));
301
302 /* get the original struct memp_malloc_helper */
303 /* cast through void* to get rid of alignment warnings */
304 hmem = (struct memp_malloc_helper *)(void *)((u8_t *)rmem - LWIP_MEM_ALIGN_SIZE(sizeof(struct memp_malloc_helper)));
305
306 LWIP_ASSERT("hmem != NULL", (hmem != NULL));
307 LWIP_ASSERT("hmem == MEM_ALIGN(hmem)", (hmem == LWIP_MEM_ALIGN(hmem)));
308 LWIP_ASSERT("hmem->poolnr < MEMP_MAX", (hmem->poolnr < MEMP_MAX));
309
310 MEM_STATS_DEC_USED_LOCKED(used, hmem->size);
311 #if MEMP_OVERFLOW_CHECK
312 {
313 u16_t i;
314 LWIP_ASSERT("MEM_USE_POOLS: invalid chunk size",
315 hmem->size <= memp_pools[hmem->poolnr]->size);
316 /* check that unused memory remained untouched (diff between requested size and selected pool's size) */
317 for (i = hmem->size; i < memp_pools[hmem->poolnr]->size; i++) {
318 u8_t data = *((u8_t *)rmem + i);
319 LWIP_ASSERT("MEM_USE_POOLS: mem overflow detected", data == 0xcd);
320 }
321 }
322 #endif /* MEMP_OVERFLOW_CHECK */
323
324 /* and put it in the pool we saved earlier */
325 memp_free(hmem->poolnr, hmem);
326 }
327
328 #else /* MEM_USE_POOLS */
329 /* lwIP replacement for your libc malloc() */
330
331 /**
332 * The heap is made up as a list of structs of this type.
333 * This does not have to be aligned since for getting its size,
334 * we only use the macro SIZEOF_STRUCT_MEM, which automatically aligns.
335 */
336 struct mem {
337 /** index (-> ram[next]) of the next struct */
338 mem_size_t next;
339 /** index (-> ram[prev]) of the previous struct */
340 mem_size_t prev;
341 /** 1: this area is used; 0: this area is unused */
342 u8_t used;
343 #if MEM_OVERFLOW_CHECK
344 /** this keeps track of the user allocation size for guard checks */
345 mem_size_t user_size;
346 #endif
347 };
348
349 /** All allocated blocks will be MIN_SIZE bytes big, at least!
350 * MIN_SIZE can be overridden to suit your needs. Smaller values save space,
351 * larger values could prevent too small blocks to fragment the RAM too much. */
352 #ifndef MIN_SIZE
353 #define MIN_SIZE 12
354 #endif /* MIN_SIZE */
355 /* some alignment macros: we define them here for better source code layout */
356 #define MIN_SIZE_ALIGNED LWIP_MEM_ALIGN_SIZE(MIN_SIZE)
357 #define SIZEOF_STRUCT_MEM LWIP_MEM_ALIGN_SIZE(sizeof(struct mem))
358 #define MEM_SIZE_ALIGNED LWIP_MEM_ALIGN_SIZE(MEM_SIZE)
359
360 /** If you want to relocate the heap to external memory, simply define
361 * LWIP_RAM_HEAP_POINTER as a void-pointer to that location.
362 * If so, make sure the memory at that location is big enough (see below on
363 * how that space is calculated). */
364 #ifndef LWIP_RAM_HEAP_POINTER
365 /** the heap. we need one struct mem at the end and some room for alignment */
366 LWIP_DECLARE_MEMORY_ALIGNED(ram_heap, MEM_SIZE_ALIGNED + (2U * SIZEOF_STRUCT_MEM));
367 #define LWIP_RAM_HEAP_POINTER ram_heap
368 #endif /* LWIP_RAM_HEAP_POINTER */
369
370 /** pointer to the heap (ram_heap): for alignment, ram is now a pointer instead of an array */
371 static u8_t *ram;
372 /** the last entry, always unused! */
373 static struct mem *ram_end;
374
375 /** concurrent access protection */
376 #if !NO_SYS
377 static sys_mutex_t mem_mutex;
378 #endif
379
380 #if LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT
381
382 static volatile u8_t mem_free_count;
383
384 /* Allow mem_free from other (e.g. interrupt) context */
385 #define LWIP_MEM_FREE_DECL_PROTECT() SYS_ARCH_DECL_PROTECT(lev_free)
386 #define LWIP_MEM_FREE_PROTECT() SYS_ARCH_PROTECT(lev_free)
387 #define LWIP_MEM_FREE_UNPROTECT() SYS_ARCH_UNPROTECT(lev_free)
388 #define LWIP_MEM_ALLOC_DECL_PROTECT() SYS_ARCH_DECL_PROTECT(lev_alloc)
389 #define LWIP_MEM_ALLOC_PROTECT() SYS_ARCH_PROTECT(lev_alloc)
390 #define LWIP_MEM_ALLOC_UNPROTECT() SYS_ARCH_UNPROTECT(lev_alloc)
391 #define LWIP_MEM_LFREE_VOLATILE volatile
392
393 #else /* LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT */
394
395 /* Protect the heap only by using a mutex */
396 #define LWIP_MEM_FREE_DECL_PROTECT()
397 #define LWIP_MEM_FREE_PROTECT() sys_mutex_lock(&mem_mutex)
398 #define LWIP_MEM_FREE_UNPROTECT() sys_mutex_unlock(&mem_mutex)
399 /* mem_malloc is protected using mutex AND LWIP_MEM_ALLOC_PROTECT */
400 #define LWIP_MEM_ALLOC_DECL_PROTECT()
401 #define LWIP_MEM_ALLOC_PROTECT()
402 #define LWIP_MEM_ALLOC_UNPROTECT()
403 #define LWIP_MEM_LFREE_VOLATILE
404
405 #endif /* LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT */
406
407 /** pointer to the lowest free block, this is used for faster search */
408 static struct mem * LWIP_MEM_LFREE_VOLATILE lfree;
409
410 #if MEM_SANITY_CHECK
411 static void mem_sanity(void);
412 #define MEM_SANITY() mem_sanity()
413 #else
414 #define MEM_SANITY()
415 #endif
416
417 #if MEM_OVERFLOW_CHECK
418 static void
mem_overflow_init_element(struct mem * mem,mem_size_t user_size)419 mem_overflow_init_element(struct mem *mem, mem_size_t user_size)
420 {
421 void *p = (u8_t *)mem + SIZEOF_STRUCT_MEM + MEM_SANITY_OFFSET;
422 mem->user_size = user_size;
423 mem_overflow_init_raw(p, user_size);
424 }
425
426 static void
mem_overflow_check_element(struct mem * mem)427 mem_overflow_check_element(struct mem *mem)
428 {
429 void *p = (u8_t *)mem + SIZEOF_STRUCT_MEM + MEM_SANITY_OFFSET;
430 mem_overflow_check_raw(p, mem->user_size, "heap", "");
431 }
432 #else /* MEM_OVERFLOW_CHECK */
433 #define mem_overflow_init_element(mem, size)
434 #define mem_overflow_check_element(mem)
435 #endif /* MEM_OVERFLOW_CHECK */
436
437 static struct mem *
ptr_to_mem(mem_size_t ptr)438 ptr_to_mem(mem_size_t ptr)
439 {
440 return (struct mem *)(void *)&ram[ptr];
441 }
442
443 static mem_size_t
mem_to_ptr(void * mem)444 mem_to_ptr(void *mem)
445 {
446 return (mem_size_t)((u8_t *)mem - ram);
447 }
448
449 /**
450 * "Plug holes" by combining adjacent empty struct mems.
451 * After this function is through, there should not exist
452 * one empty struct mem pointing to another empty struct mem.
453 *
454 * @param mem this points to a struct mem which just has been freed
455 * @internal this function is only called by mem_free() and mem_trim()
456 *
457 * This assumes access to the heap is protected by the calling function
458 * already.
459 */
460 static void
plug_holes(struct mem * mem)461 plug_holes(struct mem *mem)
462 {
463 struct mem *nmem;
464 struct mem *pmem;
465
466 LWIP_ASSERT("plug_holes: mem >= ram", (u8_t *)mem >= ram);
467 LWIP_ASSERT("plug_holes: mem < ram_end", (u8_t *)mem < (u8_t *)ram_end);
468 LWIP_ASSERT("plug_holes: mem->used == 0", mem->used == 0);
469
470 /* plug hole forward */
471 LWIP_ASSERT("plug_holes: mem->next <= MEM_SIZE_ALIGNED", mem->next <= MEM_SIZE_ALIGNED);
472
473 nmem = ptr_to_mem(mem->next);
474 if (mem != nmem && nmem->used == 0 && (u8_t *)nmem != (u8_t *)ram_end) {
475 /* if mem->next is unused and not end of ram, combine mem and mem->next */
476 if (lfree == nmem) {
477 lfree = mem;
478 }
479 mem->next = nmem->next;
480 if (nmem->next != MEM_SIZE_ALIGNED) {
481 ptr_to_mem(nmem->next)->prev = mem_to_ptr(mem);
482 }
483 }
484
485 /* plug hole backward */
486 pmem = ptr_to_mem(mem->prev);
487 if (pmem != mem && pmem->used == 0) {
488 /* if mem->prev is unused, combine mem and mem->prev */
489 if (lfree == mem) {
490 lfree = pmem;
491 }
492 pmem->next = mem->next;
493 if (mem->next != MEM_SIZE_ALIGNED) {
494 ptr_to_mem(mem->next)->prev = mem_to_ptr(pmem);
495 }
496 }
497 }
498
499 /**
500 * Zero the heap and initialize start, end and lowest-free
501 */
502 void
mem_init(void)503 mem_init(void)
504 {
505 struct mem *mem;
506
507 LWIP_ASSERT("Sanity check alignment",
508 (SIZEOF_STRUCT_MEM & (MEM_ALIGNMENT - 1)) == 0);
509
510 /* align the heap */
511 ram = (u8_t *)LWIP_MEM_ALIGN(LWIP_RAM_HEAP_POINTER);
512 /* initialize the start of the heap */
513 mem = (struct mem *)(void *)ram;
514 mem->next = MEM_SIZE_ALIGNED;
515 mem->prev = 0;
516 mem->used = 0;
517 /* initialize the end of the heap */
518 ram_end = ptr_to_mem(MEM_SIZE_ALIGNED);
519 ram_end->used = 1;
520 ram_end->next = MEM_SIZE_ALIGNED;
521 ram_end->prev = MEM_SIZE_ALIGNED;
522 MEM_SANITY();
523
524 /* initialize the lowest-free pointer to the start of the heap */
525 lfree = (struct mem *)(void *)ram;
526
527 MEM_STATS_AVAIL(avail, MEM_SIZE_ALIGNED);
528
529 if (sys_mutex_new(&mem_mutex) != ERR_OK) {
530 LWIP_ASSERT("failed to create mem_mutex", 0);
531 }
532 }
533
534 /* Check if a struct mem is correctly linked.
535 * If not, double-free is a possible reason.
536 */
537 static int
mem_link_valid(struct mem * mem)538 mem_link_valid(struct mem *mem)
539 {
540 struct mem *nmem, *pmem;
541 mem_size_t rmem_idx;
542 rmem_idx = mem_to_ptr(mem);
543 nmem = ptr_to_mem(mem->next);
544 pmem = ptr_to_mem(mem->prev);
545 if ((mem->next > MEM_SIZE_ALIGNED) || (mem->prev > MEM_SIZE_ALIGNED) ||
546 ((mem->prev != rmem_idx) && (pmem->next != rmem_idx)) ||
547 ((nmem != ram_end) && (nmem->prev != rmem_idx))) {
548 return 0;
549 }
550 return 1;
551 }
552
553 #if MEM_SANITY_CHECK
554 static void
mem_sanity(void)555 mem_sanity(void)
556 {
557 struct mem *mem;
558 u8_t last_used;
559
560 /* begin with first element here */
561 mem = (struct mem *)ram;
562 LWIP_ASSERT("heap element used valid", (mem->used == 0) || (mem->used == 1));
563 last_used = mem->used;
564 LWIP_ASSERT("heap element prev ptr valid", mem->prev == 0);
565 LWIP_ASSERT("heap element next ptr valid", mem->next <= MEM_SIZE_ALIGNED);
566 LWIP_ASSERT("heap element next ptr aligned", LWIP_MEM_ALIGN(ptr_to_mem(mem->next) == ptr_to_mem(mem->next)));
567
568 /* check all elements before the end of the heap */
569 for (mem = ptr_to_mem(mem->next);
570 ((u8_t *)mem > ram) && (mem < ram_end);
571 mem = ptr_to_mem(mem->next)) {
572 LWIP_ASSERT("heap element aligned", LWIP_MEM_ALIGN(mem) == mem);
573 LWIP_ASSERT("heap element prev ptr valid", mem->prev <= MEM_SIZE_ALIGNED);
574 LWIP_ASSERT("heap element next ptr valid", mem->next <= MEM_SIZE_ALIGNED);
575 LWIP_ASSERT("heap element prev ptr aligned", LWIP_MEM_ALIGN(ptr_to_mem(mem->prev) == ptr_to_mem(mem->prev)));
576 LWIP_ASSERT("heap element next ptr aligned", LWIP_MEM_ALIGN(ptr_to_mem(mem->next) == ptr_to_mem(mem->next)));
577
578 if (last_used == 0) {
579 /* 2 unused elements in a row? */
580 LWIP_ASSERT("heap element unused?", mem->used == 1);
581 } else {
582 LWIP_ASSERT("heap element unused member", (mem->used == 0) || (mem->used == 1));
583 }
584
585 LWIP_ASSERT("heap element link valid", mem_link_valid(mem));
586
587 /* used/unused altering */
588 last_used = mem->used;
589 }
590 LWIP_ASSERT("heap end ptr sanity", mem == ptr_to_mem(MEM_SIZE_ALIGNED));
591 LWIP_ASSERT("heap element used valid", mem->used == 1);
592 LWIP_ASSERT("heap element prev ptr valid", mem->prev == MEM_SIZE_ALIGNED);
593 LWIP_ASSERT("heap element next ptr valid", mem->next == MEM_SIZE_ALIGNED);
594 }
595 #endif /* MEM_SANITY_CHECK */
596
597 /**
598 * Put a struct mem back on the heap
599 *
600 * @param rmem is the data portion of a struct mem as returned by a previous
601 * call to mem_malloc()
602 */
603 void
mem_free(void * rmem)604 mem_free(void *rmem)
605 {
606 struct mem *mem;
607 LWIP_MEM_FREE_DECL_PROTECT();
608
609 if (rmem == NULL) {
610 LWIP_DEBUGF(MEM_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_LEVEL_SERIOUS, ("mem_free(p == NULL) was called.\n"));
611 return;
612 }
613 if ((((mem_ptr_t)rmem) & (MEM_ALIGNMENT - 1)) != 0) {
614 LWIP_MEM_ILLEGAL_FREE("mem_free: sanity check alignment");
615 LWIP_DEBUGF(MEM_DEBUG | LWIP_DBG_LEVEL_SEVERE, ("mem_free: sanity check alignment\n"));
616 /* protect mem stats from concurrent access */
617 MEM_STATS_INC_LOCKED(illegal);
618 return;
619 }
620
621 /* Get the corresponding struct mem: */
622 /* cast through void* to get rid of alignment warnings */
623 mem = (struct mem *)(void *)((u8_t *)rmem - (SIZEOF_STRUCT_MEM + MEM_SANITY_OFFSET));
624
625 if ((u8_t *)mem < ram || (u8_t *)rmem + MIN_SIZE_ALIGNED > (u8_t *)ram_end) {
626 LWIP_MEM_ILLEGAL_FREE("mem_free: illegal memory");
627 LWIP_DEBUGF(MEM_DEBUG | LWIP_DBG_LEVEL_SEVERE, ("mem_free: illegal memory\n"));
628 /* protect mem stats from concurrent access */
629 MEM_STATS_INC_LOCKED(illegal);
630 return;
631 }
632 #if MEM_OVERFLOW_CHECK
633 mem_overflow_check_element(mem);
634 #endif
635 /* protect the heap from concurrent access */
636 LWIP_MEM_FREE_PROTECT();
637 /* mem has to be in a used state */
638 if (!mem->used) {
639 LWIP_MEM_ILLEGAL_FREE("mem_free: illegal memory: double free");
640 LWIP_MEM_FREE_UNPROTECT();
641 LWIP_DEBUGF(MEM_DEBUG | LWIP_DBG_LEVEL_SEVERE, ("mem_free: illegal memory: double free?\n"));
642 /* protect mem stats from concurrent access */
643 MEM_STATS_INC_LOCKED(illegal);
644 return;
645 }
646
647 if (!mem_link_valid(mem)) {
648 LWIP_MEM_ILLEGAL_FREE("mem_free: illegal memory: non-linked: double free");
649 LWIP_MEM_FREE_UNPROTECT();
650 LWIP_DEBUGF(MEM_DEBUG | LWIP_DBG_LEVEL_SEVERE, ("mem_free: illegal memory: non-linked: double free?\n"));
651 /* protect mem stats from concurrent access */
652 MEM_STATS_INC_LOCKED(illegal);
653 return;
654 }
655
656 /* mem is now unused. */
657 mem->used = 0;
658
659 if (mem < lfree) {
660 /* the newly freed struct is now the lowest */
661 lfree = mem;
662 }
663
664 MEM_STATS_DEC_USED(used, mem->next - (mem_size_t)(((u8_t *)mem - ram)));
665
666 /* finally, see if prev or next are free also */
667 plug_holes(mem);
668 MEM_SANITY();
669 #if LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT
670 mem_free_count = 1;
671 #endif /* LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT */
672 LWIP_MEM_FREE_UNPROTECT();
673 }
674
675 /**
676 * Shrink memory returned by mem_malloc().
677 *
678 * @param rmem pointer to memory allocated by mem_malloc the is to be shrunk
679 * @param new_size required size after shrinking (needs to be smaller than or
680 * equal to the previous size)
681 * @return for compatibility reasons: is always == rmem, at the moment
682 * or NULL if newsize is > old size, in which case rmem is NOT touched
683 * or freed!
684 */
685 void *
mem_trim(void * rmem,mem_size_t new_size)686 mem_trim(void *rmem, mem_size_t new_size)
687 {
688 mem_size_t size, newsize;
689 mem_size_t ptr, ptr2;
690 struct mem *mem, *mem2;
691 /* use the FREE_PROTECT here: it protects with sem OR SYS_ARCH_PROTECT */
692 LWIP_MEM_FREE_DECL_PROTECT();
693
694 /* Expand the size of the allocated memory region so that we can
695 adjust for alignment. */
696 newsize = (mem_size_t)LWIP_MEM_ALIGN_SIZE(new_size);
697 if (newsize < MIN_SIZE_ALIGNED) {
698 /* every data block must be at least MIN_SIZE_ALIGNED long */
699 newsize = MIN_SIZE_ALIGNED;
700 }
701 #if MEM_OVERFLOW_CHECK
702 newsize += MEM_SANITY_REGION_BEFORE_ALIGNED + MEM_SANITY_REGION_AFTER_ALIGNED;
703 #endif
704 if ((newsize > MEM_SIZE_ALIGNED) || (newsize < new_size)) {
705 return NULL;
706 }
707
708 LWIP_ASSERT("mem_trim: legal memory", (u8_t *)rmem >= (u8_t *)ram &&
709 (u8_t *)rmem < (u8_t *)ram_end);
710
711 if ((u8_t *)rmem < (u8_t *)ram || (u8_t *)rmem >= (u8_t *)ram_end) {
712 LWIP_DEBUGF(MEM_DEBUG | LWIP_DBG_LEVEL_SEVERE, ("mem_trim: illegal memory\n"));
713 /* protect mem stats from concurrent access */
714 MEM_STATS_INC_LOCKED(illegal);
715 return rmem;
716 }
717 /* Get the corresponding struct mem ... */
718 /* cast through void* to get rid of alignment warnings */
719 mem = (struct mem *)(void *)((u8_t *)rmem - (SIZEOF_STRUCT_MEM + MEM_SANITY_OFFSET));
720 #if MEM_OVERFLOW_CHECK
721 mem_overflow_check_element(mem);
722 #endif
723 /* ... and its offset pointer */
724 ptr = mem_to_ptr(mem);
725
726 size = (mem_size_t)((mem_size_t)(mem->next - ptr) - (SIZEOF_STRUCT_MEM + MEM_SANITY_OVERHEAD));
727 LWIP_ASSERT("mem_trim can only shrink memory", newsize <= size);
728 if (newsize > size) {
729 /* not supported */
730 return NULL;
731 }
732 if (newsize == size) {
733 /* No change in size, simply return */
734 return rmem;
735 }
736
737 /* protect the heap from concurrent access */
738 LWIP_MEM_FREE_PROTECT();
739
740 mem2 = ptr_to_mem(mem->next);
741 if (mem2->used == 0) {
742 /* The next struct is unused, we can simply move it at little */
743 mem_size_t next;
744 LWIP_ASSERT("invalid next ptr", mem->next != MEM_SIZE_ALIGNED);
745 /* remember the old next pointer */
746 next = mem2->next;
747 /* create new struct mem which is moved directly after the shrunk mem */
748 ptr2 = (mem_size_t)(ptr + SIZEOF_STRUCT_MEM + newsize);
749 if (lfree == mem2) {
750 lfree = ptr_to_mem(ptr2);
751 }
752 mem2 = ptr_to_mem(ptr2);
753 mem2->used = 0;
754 /* restore the next pointer */
755 mem2->next = next;
756 /* link it back to mem */
757 mem2->prev = ptr;
758 /* link mem to it */
759 mem->next = ptr2;
760 /* last thing to restore linked list: as we have moved mem2,
761 * let 'mem2->next->prev' point to mem2 again. but only if mem2->next is not
762 * the end of the heap */
763 if (mem2->next != MEM_SIZE_ALIGNED) {
764 ptr_to_mem(mem2->next)->prev = ptr2;
765 }
766 MEM_STATS_DEC_USED(used, (size - newsize));
767 /* no need to plug holes, we've already done that */
768 } else if (newsize + SIZEOF_STRUCT_MEM + MIN_SIZE_ALIGNED <= size) {
769 /* Next struct is used but there's room for another struct mem with
770 * at least MIN_SIZE_ALIGNED of data.
771 * Old size ('size') must be big enough to contain at least 'newsize' plus a struct mem
772 * ('SIZEOF_STRUCT_MEM') with some data ('MIN_SIZE_ALIGNED').
773 * @todo we could leave out MIN_SIZE_ALIGNED. We would create an empty
774 * region that couldn't hold data, but when mem->next gets freed,
775 * the 2 regions would be combined, resulting in more free memory */
776 ptr2 = (mem_size_t)(ptr + SIZEOF_STRUCT_MEM + newsize);
777 LWIP_ASSERT("invalid next ptr", mem->next != MEM_SIZE_ALIGNED);
778 mem2 = ptr_to_mem(ptr2);
779 if (mem2 < lfree) {
780 lfree = mem2;
781 }
782 mem2->used = 0;
783 mem2->next = mem->next;
784 mem2->prev = ptr;
785 mem->next = ptr2;
786 if (mem2->next != MEM_SIZE_ALIGNED) {
787 ptr_to_mem(mem2->next)->prev = ptr2;
788 }
789 MEM_STATS_DEC_USED(used, (size - newsize));
790 /* the original mem->next is used, so no need to plug holes! */
791 }
792 /* else {
793 next struct mem is used but size between mem and mem2 is not big enough
794 to create another struct mem
795 -> don't do anything.
796 -> the remaining space stays unused since it is too small
797 } */
798 #if MEM_OVERFLOW_CHECK
799 mem_overflow_init_element(mem, new_size);
800 #endif
801 MEM_SANITY();
802 #if LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT
803 mem_free_count = 1;
804 #endif /* LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT */
805 LWIP_MEM_FREE_UNPROTECT();
806 return rmem;
807 }
808
809 /**
810 * Allocate a block of memory with a minimum of 'size' bytes.
811 *
812 * @param size_in is the minimum size of the requested block in bytes.
813 * @return pointer to allocated memory or NULL if no free memory was found.
814 *
815 * Note that the returned value will always be aligned (as defined by MEM_ALIGNMENT).
816 */
817 void *
mem_malloc(mem_size_t size_in)818 mem_malloc(mem_size_t size_in)
819 {
820 mem_size_t ptr, ptr2, size;
821 struct mem *mem, *mem2;
822 #if LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT
823 u8_t local_mem_free_count = 0;
824 #endif /* LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT */
825 LWIP_MEM_ALLOC_DECL_PROTECT();
826
827 if (size_in == 0) {
828 return NULL;
829 }
830
831 /* Expand the size of the allocated memory region so that we can
832 adjust for alignment. */
833 size = (mem_size_t)LWIP_MEM_ALIGN_SIZE(size_in);
834 if (size < MIN_SIZE_ALIGNED) {
835 /* every data block must be at least MIN_SIZE_ALIGNED long */
836 size = MIN_SIZE_ALIGNED;
837 }
838 #if MEM_OVERFLOW_CHECK
839 size += MEM_SANITY_REGION_BEFORE_ALIGNED + MEM_SANITY_REGION_AFTER_ALIGNED;
840 #endif
841 if ((size > MEM_SIZE_ALIGNED) || (size < size_in)) {
842 return NULL;
843 }
844
845 /* protect the heap from concurrent access */
846 sys_mutex_lock(&mem_mutex);
847 LWIP_MEM_ALLOC_PROTECT();
848 #if LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT
849 /* run as long as a mem_free disturbed mem_malloc or mem_trim */
850 do {
851 local_mem_free_count = 0;
852 #endif /* LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT */
853
854 /* Scan through the heap searching for a free block that is big enough,
855 * beginning with the lowest free block.
856 */
857 for (ptr = mem_to_ptr(lfree); ptr < MEM_SIZE_ALIGNED - size;
858 ptr = ptr_to_mem(ptr)->next) {
859 mem = ptr_to_mem(ptr);
860 #if LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT
861 mem_free_count = 0;
862 LWIP_MEM_ALLOC_UNPROTECT();
863 /* allow mem_free or mem_trim to run */
864 LWIP_MEM_ALLOC_PROTECT();
865 if (mem_free_count != 0) {
866 /* If mem_free or mem_trim have run, we have to restart since they
867 could have altered our current struct mem. */
868 local_mem_free_count = 1;
869 break;
870 }
871 #endif /* LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT */
872
873 if ((!mem->used) &&
874 (mem->next - (ptr + SIZEOF_STRUCT_MEM)) >= size) {
875 /* mem is not used and at least perfect fit is possible:
876 * mem->next - (ptr + SIZEOF_STRUCT_MEM) gives us the 'user data size' of mem */
877
878 if (mem->next - (ptr + SIZEOF_STRUCT_MEM) >= (size + SIZEOF_STRUCT_MEM + MIN_SIZE_ALIGNED)) {
879 /* (in addition to the above, we test if another struct mem (SIZEOF_STRUCT_MEM) containing
880 * at least MIN_SIZE_ALIGNED of data also fits in the 'user data space' of 'mem')
881 * -> split large block, create empty remainder,
882 * remainder must be large enough to contain MIN_SIZE_ALIGNED data: if
883 * mem->next - (ptr + (2*SIZEOF_STRUCT_MEM)) == size,
884 * struct mem would fit in but no data between mem2 and mem2->next
885 * @todo we could leave out MIN_SIZE_ALIGNED. We would create an empty
886 * region that couldn't hold data, but when mem->next gets freed,
887 * the 2 regions would be combined, resulting in more free memory
888 */
889 ptr2 = (mem_size_t)(ptr + SIZEOF_STRUCT_MEM + size);
890 LWIP_ASSERT("invalid next ptr",ptr2 != MEM_SIZE_ALIGNED);
891 /* create mem2 struct */
892 mem2 = ptr_to_mem(ptr2);
893 mem2->used = 0;
894 mem2->next = mem->next;
895 mem2->prev = ptr;
896 /* and insert it between mem and mem->next */
897 mem->next = ptr2;
898 mem->used = 1;
899
900 if (mem2->next != MEM_SIZE_ALIGNED) {
901 ptr_to_mem(mem2->next)->prev = ptr2;
902 }
903 MEM_STATS_INC_USED(used, (size + SIZEOF_STRUCT_MEM));
904 } else {
905 /* (a mem2 struct does no fit into the user data space of mem and mem->next will always
906 * be used at this point: if not we have 2 unused structs in a row, plug_holes should have
907 * take care of this).
908 * -> near fit or exact fit: do not split, no mem2 creation
909 * also can't move mem->next directly behind mem, since mem->next
910 * will always be used at this point!
911 */
912 mem->used = 1;
913 MEM_STATS_INC_USED(used, mem->next - mem_to_ptr(mem));
914 }
915 #if LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT
916 mem_malloc_adjust_lfree:
917 #endif /* LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT */
918 if (mem == lfree) {
919 struct mem *cur = lfree;
920 /* Find next free block after mem and update lowest free pointer */
921 while (cur->used && cur != ram_end) {
922 #if LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT
923 mem_free_count = 0;
924 LWIP_MEM_ALLOC_UNPROTECT();
925 /* prevent high interrupt latency... */
926 LWIP_MEM_ALLOC_PROTECT();
927 if (mem_free_count != 0) {
928 /* If mem_free or mem_trim have run, we have to restart since they
929 could have altered our current struct mem or lfree. */
930 goto mem_malloc_adjust_lfree;
931 }
932 #endif /* LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT */
933 cur = ptr_to_mem(cur->next);
934 }
935 lfree = cur;
936 LWIP_ASSERT("mem_malloc: !lfree->used", ((lfree == ram_end) || (!lfree->used)));
937 }
938 LWIP_MEM_ALLOC_UNPROTECT();
939 sys_mutex_unlock(&mem_mutex);
940 LWIP_ASSERT("mem_malloc: allocated memory not above ram_end.",
941 (mem_ptr_t)mem + SIZEOF_STRUCT_MEM + size <= (mem_ptr_t)ram_end);
942 LWIP_ASSERT("mem_malloc: allocated memory properly aligned.",
943 ((mem_ptr_t)mem + SIZEOF_STRUCT_MEM) % MEM_ALIGNMENT == 0);
944 LWIP_ASSERT("mem_malloc: sanity check alignment",
945 (((mem_ptr_t)mem) & (MEM_ALIGNMENT - 1)) == 0);
946
947 #if MEM_OVERFLOW_CHECK
948 mem_overflow_init_element(mem, size_in);
949 #endif
950 MEM_SANITY();
951 return (u8_t *)mem + SIZEOF_STRUCT_MEM + MEM_SANITY_OFFSET;
952 }
953 }
954 #if LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT
955 /* if we got interrupted by a mem_free, try again */
956 } while (local_mem_free_count != 0);
957 #endif /* LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT */
958 MEM_STATS_INC(err);
959 LWIP_MEM_ALLOC_UNPROTECT();
960 sys_mutex_unlock(&mem_mutex);
961 LWIP_DEBUGF(MEM_DEBUG | LWIP_DBG_LEVEL_SERIOUS, ("mem_malloc: could not allocate %"S16_F" bytes\n", (s16_t)size));
962 return NULL;
963 }
964
965 #endif /* MEM_USE_POOLS */
966
967 #if MEM_CUSTOM_ALLOCATOR && (!LWIP_STATS || !MEM_STATS)
968 void *
mem_calloc(mem_size_t count,mem_size_t size)969 mem_calloc(mem_size_t count, mem_size_t size)
970 {
971 return MEM_CUSTOM_CALLOC(count, size);
972 }
973
974 #else /* MEM_CUSTOM_ALLOCATOR && (!LWIP_STATS || !MEM_STATS) */
975 /**
976 * Contiguously allocates enough space for count objects that are size bytes
977 * of memory each and returns a pointer to the allocated memory.
978 *
979 * The allocated memory is filled with bytes of value zero.
980 *
981 * @param count number of objects to allocate
982 * @param size size of the objects to allocate
983 * @return pointer to allocated memory / NULL pointer if there is an error
984 */
985 void *
mem_calloc(mem_size_t count,mem_size_t size)986 mem_calloc(mem_size_t count, mem_size_t size)
987 {
988 void *p;
989 size_t alloc_size = (size_t)count * (size_t)size;
990
991 if ((size_t)(mem_size_t)alloc_size != alloc_size) {
992 LWIP_DEBUGF(MEM_DEBUG | LWIP_DBG_LEVEL_SERIOUS, ("mem_calloc: could not allocate %"SZT_F" bytes\n", alloc_size));
993 return NULL;
994 }
995
996 /* allocate 'count' objects of size 'size' */
997 p = mem_malloc((mem_size_t)alloc_size);
998 if (p) {
999 /* zero the memory */
1000 memset(p, 0, alloc_size);
1001 }
1002 return p;
1003 }
1004 #endif /* MEM_CUSTOM_ALLOCATOR && (!LWIP_STATS || !MEM_STATS) */
1005