1 #include "test_mem.h"
2 
3 #include "lwip/mem.h"
4 #include "lwip/stats.h"
5 
6 #if !LWIP_STATS || !MEM_STATS
7 #error "This tests needs MEM-statistics enabled"
8 #endif
9 #if LWIP_DNS
10 #error "This test needs DNS turned off (as it mallocs on init)"
11 #endif
12 
13 /* Setups/teardown functions */
14 
15 static void
16 mem_setup(void)
17 {
18 }
19 
20 static void
21 mem_teardown(void)
22 {
23 }
24 
25 
26 /* Test functions */
27 
28 /** Call mem_malloc, mem_free and mem_trim and check stats */
29 START_TEST(test_mem_one)
30 {
31 #define SIZE1   16
32 #define SIZE1_2 12
33 #define SIZE2   16
34   void *p1, *p2;
35   mem_size_t s1, s2;
36   LWIP_UNUSED_ARG(_i);
37 
38   fail_unless(lwip_stats.mem.used == 0);
39 
40   p1 = mem_malloc(SIZE1);
41   fail_unless(p1 != NULL);
42   fail_unless(lwip_stats.mem.used >= SIZE1);
43   s1 = lwip_stats.mem.used;
44 
45   p2 = mem_malloc(SIZE2);
46   fail_unless(p2 != NULL);
47   fail_unless(lwip_stats.mem.used >= SIZE2 + s1);
48   s2 = lwip_stats.mem.used;
49 
50   mem_trim(p1, SIZE1_2);
51 
52   mem_free(p2);
53   fail_unless(lwip_stats.mem.used <= s2 - SIZE2);
54 
55   mem_free(p1);
56   fail_unless(lwip_stats.mem.used == 0);
57 }
58 END_TEST
59 
60 static void malloc_keep_x(int x, int num, int size, int freestep)
61 {
62    int i;
63    void* p[16];
64    LWIP_ASSERT("invalid size", size >= 0 && size < (mem_size_t)-1);
65    memset(p, 0, sizeof(p));
66    for(i = 0; i < num && i < 16; i++) {
67       p[i] = mem_malloc((mem_size_t)size);
68       fail_unless(p[i] != NULL);
69    }
70    for(i = 0; i < num && i < 16; i += freestep) {
71       if (i == x) {
72          continue;
73       }
74       mem_free(p[i]);
75       p[i] = NULL;
76    }
77    for(i = 0; i < num && i < 16; i++) {
78       if (i == x) {
79          continue;
80       }
81       if (p[i] != NULL) {
82          mem_free(p[i]);
83          p[i] = NULL;
84       }
85    }
86    fail_unless(p[x] != NULL);
87    mem_free(p[x]);
88 }
89 
90 START_TEST(test_mem_random)
91 {
92   const int num = 16;
93   int x;
94   int size;
95   int freestep;
96   LWIP_UNUSED_ARG(_i);
97 
98   fail_unless(lwip_stats.mem.used == 0);
99 
100   for (x = 0; x < num; x++) {
101      for (size = 1; size < 32; size++) {
102         for (freestep = 1; freestep <= 3; freestep++) {
103           fail_unless(lwip_stats.mem.used == 0);
104           malloc_keep_x(x, num, size, freestep);
105           fail_unless(lwip_stats.mem.used == 0);
106         }
107      }
108   }
109 }
110 END_TEST
111 
112 /** Create the suite including all tests for this module */
113 Suite *
114 mem_suite(void)
115 {
116   testfunc tests[] = {
117     TESTFUNC(test_mem_one),
118     TESTFUNC(test_mem_random)
119   };
120   return create_suite("MEM", tests, sizeof(tests)/sizeof(testfunc), mem_setup, mem_teardown);
121 }
122