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