1 //===-- wrappers_c_test.cpp -------------------------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "scudo/interface.h"
10 #include "tests/scudo_unit_test.h"
11 
12 #include <errno.h>
13 #include <limits.h>
14 #include <malloc.h>
15 #include <stdlib.h>
16 #include <unistd.h>
17 
18 extern "C" {
19 void malloc_enable(void);
20 void malloc_disable(void);
21 int malloc_iterate(uintptr_t base, size_t size,
22                    void (*callback)(uintptr_t base, size_t size, void *arg),
23                    void *arg);
24 void *valloc(size_t size);
25 void *pvalloc(size_t size);
26 }
27 
28 // Note that every C allocation function in the test binary will be fulfilled
29 // by Scudo (this includes the gtest APIs, etc.), which is a test by itself.
30 // But this might also lead to unexpected side-effects, since the allocation and
31 // deallocation operations in the TEST functions will coexist with others (see
32 // the EXPECT_DEATH comment below).
33 
34 // We have to use a small quarantine to make sure that our double-free tests
35 // trigger. Otherwise EXPECT_DEATH ends up reallocating the chunk that was just
36 // freed (this depends on the size obviously) and the following free succeeds.
37 
38 static const size_t Size = 100U;
39 
40 TEST(ScudoWrappersCTest, Malloc) {
41   void *P = malloc(Size);
42   EXPECT_NE(P, nullptr);
43   EXPECT_LE(Size, malloc_usable_size(P));
44   EXPECT_EQ(reinterpret_cast<uintptr_t>(P) % FIRST_32_SECOND_64(8U, 16U), 0U);
45 
46   // An update to this warning in Clang now triggers in this line, but it's ok
47   // because the check is expecting a bad pointer and should fail.
48 #if defined(__has_warning) && __has_warning("-Wfree-nonheap-object")
49 #pragma GCC diagnostic push
50 #pragma GCC diagnostic ignored "-Wfree-nonheap-object"
51 #endif
52   EXPECT_DEATH(
53       free(reinterpret_cast<void *>(reinterpret_cast<uintptr_t>(P) | 1U)), "");
54 #if defined(__has_warning) && __has_warning("-Wfree-nonheap-object")
55 #pragma GCC diagnostic pop
56 #endif
57 
58   free(P);
59   EXPECT_DEATH(free(P), "");
60 
61   P = malloc(0U);
62   EXPECT_NE(P, nullptr);
63   free(P);
64 
65   errno = 0;
66   EXPECT_EQ(malloc(SIZE_MAX), nullptr);
67   EXPECT_EQ(errno, ENOMEM);
68 }
69 
70 TEST(ScudoWrappersCTest, Calloc) {
71   void *P = calloc(1U, Size);
72   EXPECT_NE(P, nullptr);
73   EXPECT_LE(Size, malloc_usable_size(P));
74   for (size_t I = 0; I < Size; I++)
75     EXPECT_EQ((reinterpret_cast<uint8_t *>(P))[I], 0U);
76   free(P);
77 
78   P = calloc(1U, 0U);
79   EXPECT_NE(P, nullptr);
80   free(P);
81   P = calloc(0U, 1U);
82   EXPECT_NE(P, nullptr);
83   free(P);
84 
85   errno = 0;
86   EXPECT_EQ(calloc(SIZE_MAX, 1U), nullptr);
87   EXPECT_EQ(errno, ENOMEM);
88   errno = 0;
89   EXPECT_EQ(calloc(static_cast<size_t>(LONG_MAX) + 1U, 2U), nullptr);
90   if (SCUDO_ANDROID)
91     EXPECT_EQ(errno, ENOMEM);
92   errno = 0;
93   EXPECT_EQ(calloc(SIZE_MAX, SIZE_MAX), nullptr);
94   EXPECT_EQ(errno, ENOMEM);
95 }
96 
97 TEST(ScudoWrappersCTest, Memalign) {
98   void *P;
99   for (size_t I = FIRST_32_SECOND_64(2U, 3U); I <= 18U; I++) {
100     const size_t Alignment = 1U << I;
101 
102     P = memalign(Alignment, Size);
103     EXPECT_NE(P, nullptr);
104     EXPECT_LE(Size, malloc_usable_size(P));
105     EXPECT_EQ(reinterpret_cast<uintptr_t>(P) % Alignment, 0U);
106     free(P);
107 
108     P = nullptr;
109     EXPECT_EQ(posix_memalign(&P, Alignment, Size), 0);
110     EXPECT_NE(P, nullptr);
111     EXPECT_LE(Size, malloc_usable_size(P));
112     EXPECT_EQ(reinterpret_cast<uintptr_t>(P) % Alignment, 0U);
113     free(P);
114   }
115 
116   EXPECT_EQ(memalign(4096U, SIZE_MAX), nullptr);
117   EXPECT_EQ(posix_memalign(&P, 15U, Size), EINVAL);
118   EXPECT_EQ(posix_memalign(&P, 4096U, SIZE_MAX), ENOMEM);
119 
120   // Android's memalign accepts non power-of-2 alignments, and 0.
121   if (SCUDO_ANDROID) {
122     for (size_t Alignment = 0U; Alignment <= 128U; Alignment++) {
123       P = memalign(Alignment, 1024U);
124       EXPECT_NE(P, nullptr);
125       free(P);
126     }
127   }
128 }
129 
130 TEST(ScudoWrappersCTest, AlignedAlloc) {
131   const size_t Alignment = 4096U;
132   void *P = aligned_alloc(Alignment, Alignment * 4U);
133   EXPECT_NE(P, nullptr);
134   EXPECT_LE(Alignment * 4U, malloc_usable_size(P));
135   EXPECT_EQ(reinterpret_cast<uintptr_t>(P) % Alignment, 0U);
136   free(P);
137 
138   errno = 0;
139   P = aligned_alloc(Alignment, Size);
140   EXPECT_EQ(P, nullptr);
141   EXPECT_EQ(errno, EINVAL);
142 }
143 
144 TEST(ScudoWrappersCTest, Realloc) {
145   // realloc(nullptr, N) is malloc(N)
146   void *P = realloc(nullptr, 0U);
147   EXPECT_NE(P, nullptr);
148   free(P);
149 
150   P = malloc(Size);
151   EXPECT_NE(P, nullptr);
152   // realloc(P, 0U) is free(P) and returns nullptr
153   EXPECT_EQ(realloc(P, 0U), nullptr);
154 
155   P = malloc(Size);
156   EXPECT_NE(P, nullptr);
157   EXPECT_LE(Size, malloc_usable_size(P));
158   memset(P, 0x42, Size);
159 
160   P = realloc(P, Size * 2U);
161   EXPECT_NE(P, nullptr);
162   EXPECT_LE(Size * 2U, malloc_usable_size(P));
163   for (size_t I = 0; I < Size; I++)
164     EXPECT_EQ(0x42, (reinterpret_cast<uint8_t *>(P))[I]);
165 
166   P = realloc(P, Size / 2U);
167   EXPECT_NE(P, nullptr);
168   EXPECT_LE(Size / 2U, malloc_usable_size(P));
169   for (size_t I = 0; I < Size / 2U; I++)
170     EXPECT_EQ(0x42, (reinterpret_cast<uint8_t *>(P))[I]);
171   free(P);
172 
173   EXPECT_DEATH(P = realloc(P, Size), "");
174 
175   errno = 0;
176   EXPECT_EQ(realloc(nullptr, SIZE_MAX), nullptr);
177   EXPECT_EQ(errno, ENOMEM);
178   P = malloc(Size);
179   EXPECT_NE(P, nullptr);
180   errno = 0;
181   EXPECT_EQ(realloc(P, SIZE_MAX), nullptr);
182   EXPECT_EQ(errno, ENOMEM);
183   free(P);
184 
185   // Android allows realloc of memalign pointers.
186   if (SCUDO_ANDROID) {
187     const size_t Alignment = 1024U;
188     P = memalign(Alignment, Size);
189     EXPECT_NE(P, nullptr);
190     EXPECT_LE(Size, malloc_usable_size(P));
191     EXPECT_EQ(reinterpret_cast<uintptr_t>(P) % Alignment, 0U);
192     memset(P, 0x42, Size);
193 
194     P = realloc(P, Size * 2U);
195     EXPECT_NE(P, nullptr);
196     EXPECT_LE(Size * 2U, malloc_usable_size(P));
197     for (size_t I = 0; I < Size; I++)
198       EXPECT_EQ(0x42, (reinterpret_cast<uint8_t *>(P))[I]);
199     free(P);
200   }
201 }
202 
203 #if !SCUDO_FUCHSIA
204 TEST(ScudoWrappersCTest, MallOpt) {
205   errno = 0;
206   EXPECT_EQ(mallopt(-1000, 1), 0);
207   // mallopt doesn't set errno.
208   EXPECT_EQ(errno, 0);
209 
210   EXPECT_EQ(mallopt(M_PURGE, 0), 1);
211 
212   EXPECT_EQ(mallopt(M_DECAY_TIME, 1), 1);
213   EXPECT_EQ(mallopt(M_DECAY_TIME, 0), 1);
214   EXPECT_EQ(mallopt(M_DECAY_TIME, 1), 1);
215   EXPECT_EQ(mallopt(M_DECAY_TIME, 0), 1);
216 
217   if (SCUDO_ANDROID) {
218     EXPECT_EQ(mallopt(M_CACHE_COUNT_MAX, 100), 1);
219     EXPECT_EQ(mallopt(M_CACHE_SIZE_MAX, 1024 * 1024 * 2), 1);
220     EXPECT_EQ(mallopt(M_TSDS_COUNT_MAX, 10), 1);
221   }
222 }
223 #endif
224 
225 TEST(ScudoWrappersCTest, OtherAlloc) {
226 #if !SCUDO_FUCHSIA
227   const size_t PageSize = sysconf(_SC_PAGESIZE);
228 
229   void *P = pvalloc(Size);
230   EXPECT_NE(P, nullptr);
231   EXPECT_EQ(reinterpret_cast<uintptr_t>(P) & (PageSize - 1), 0U);
232   EXPECT_LE(PageSize, malloc_usable_size(P));
233   free(P);
234 
235   EXPECT_EQ(pvalloc(SIZE_MAX), nullptr);
236 
237   P = pvalloc(Size);
238   EXPECT_NE(P, nullptr);
239   EXPECT_EQ(reinterpret_cast<uintptr_t>(P) & (PageSize - 1), 0U);
240   free(P);
241 #endif
242 
243   EXPECT_EQ(valloc(SIZE_MAX), nullptr);
244 }
245 
246 #if !SCUDO_FUCHSIA
247 TEST(ScudoWrappersCTest, MallInfo) {
248   const size_t BypassQuarantineSize = 1024U;
249 
250   struct mallinfo MI = mallinfo();
251   size_t Allocated = MI.uordblks;
252   void *P = malloc(BypassQuarantineSize);
253   EXPECT_NE(P, nullptr);
254   MI = mallinfo();
255   EXPECT_GE(static_cast<size_t>(MI.uordblks), Allocated + BypassQuarantineSize);
256   EXPECT_GT(static_cast<size_t>(MI.hblkhd), 0U);
257   size_t Free = MI.fordblks;
258   free(P);
259   MI = mallinfo();
260   EXPECT_GE(static_cast<size_t>(MI.fordblks), Free + BypassQuarantineSize);
261 }
262 #endif
263 
264 static uintptr_t BoundaryP;
265 static size_t Count;
266 
267 static void callback(uintptr_t Base, size_t Size, void *Arg) {
268   if (Base == BoundaryP)
269     Count++;
270 }
271 
272 // Verify that a block located on an iteration boundary is not mis-accounted.
273 // To achieve this, we allocate a chunk for which the backing block will be
274 // aligned on a page, then run the malloc_iterate on both the pages that the
275 // block is a boundary for. It must only be seen once by the callback function.
276 TEST(ScudoWrappersCTest, MallocIterateBoundary) {
277   const size_t PageSize = sysconf(_SC_PAGESIZE);
278   const size_t BlockDelta = FIRST_32_SECOND_64(8U, 16U);
279   const size_t SpecialSize = PageSize - BlockDelta;
280 
281   // We aren't guaranteed that any size class is exactly a page wide. So we need
282   // to keep making allocations until we succeed.
283   //
284   // With a 16-byte block alignment and 4096-byte page size, each allocation has
285   // a probability of (1 - (16/4096)) of failing to meet the alignment
286   // requirements, and the probability of failing 65536 times is
287   // (1 - (16/4096))^65536 < 10^-112. So if we still haven't succeeded after
288   // 65536 tries, give up.
289   uintptr_t Block;
290   void *P = nullptr;
291   for (unsigned I = 0; I != 65536; ++I) {
292     void *PrevP = P;
293     P = malloc(SpecialSize);
294     EXPECT_NE(P, nullptr);
295     *reinterpret_cast<void **>(P) = PrevP;
296     BoundaryP = reinterpret_cast<uintptr_t>(P);
297     Block = BoundaryP - BlockDelta;
298     if ((Block & (PageSize - 1)) == 0U)
299       break;
300   }
301   EXPECT_EQ((Block & (PageSize - 1)), 0U);
302 
303   Count = 0U;
304   malloc_disable();
305   malloc_iterate(Block - PageSize, PageSize, callback, nullptr);
306   malloc_iterate(Block, PageSize, callback, nullptr);
307   malloc_enable();
308   EXPECT_EQ(Count, 1U);
309 
310   while (P) {
311     void *NextP = *reinterpret_cast<void **>(P);
312     free(P);
313     P = NextP;
314   }
315 }
316 
317 // Fuchsia doesn't have alarm, fork or malloc_info.
318 #if !SCUDO_FUCHSIA
319 TEST(ScudoWrappersCTest, MallocDisableDeadlock) {
320   // We expect heap operations within a disable/enable scope to deadlock.
321   EXPECT_DEATH(
322       {
323         void *P = malloc(Size);
324         EXPECT_NE(P, nullptr);
325         free(P);
326         malloc_disable();
327         alarm(1);
328         P = malloc(Size);
329         malloc_enable();
330       },
331       "");
332 }
333 
334 TEST(ScudoWrappersCTest, MallocInfo) {
335   // Use volatile so that the allocations don't get optimized away.
336   void *volatile P1 = malloc(1234);
337   void *volatile P2 = malloc(4321);
338 
339   char Buffer[16384];
340   FILE *F = fmemopen(Buffer, sizeof(Buffer), "w+");
341   EXPECT_NE(F, nullptr);
342   errno = 0;
343   EXPECT_EQ(malloc_info(0, F), 0);
344   EXPECT_EQ(errno, 0);
345   fclose(F);
346   EXPECT_EQ(strncmp(Buffer, "<malloc version=\"scudo-", 23), 0);
347   EXPECT_NE(nullptr, strstr(Buffer, "<alloc size=\"1234\" count=\""));
348   EXPECT_NE(nullptr, strstr(Buffer, "<alloc size=\"4321\" count=\""));
349 
350   free(P1);
351   free(P2);
352 }
353 
354 TEST(ScudoWrappersCTest, Fork) {
355   void *P;
356   pid_t Pid = fork();
357   EXPECT_GE(Pid, 0);
358   if (Pid == 0) {
359     P = malloc(Size);
360     EXPECT_NE(P, nullptr);
361     memset(P, 0x42, Size);
362     free(P);
363     _exit(0);
364   }
365   waitpid(Pid, nullptr, 0);
366   P = malloc(Size);
367   EXPECT_NE(P, nullptr);
368   memset(P, 0x42, Size);
369   free(P);
370 
371   // fork should stall if the allocator has been disabled.
372   EXPECT_DEATH(
373       {
374         malloc_disable();
375         alarm(1);
376         Pid = fork();
377         EXPECT_GE(Pid, 0);
378       },
379       "");
380 }
381 
382 static pthread_mutex_t Mutex;
383 static pthread_cond_t Conditional = PTHREAD_COND_INITIALIZER;
384 static bool Ready;
385 
386 static void *enableMalloc(void *Unused) {
387   // Initialize the allocator for this thread.
388   void *P = malloc(Size);
389   EXPECT_NE(P, nullptr);
390   memset(P, 0x42, Size);
391   free(P);
392 
393   // Signal the main thread we are ready.
394   pthread_mutex_lock(&Mutex);
395   Ready = true;
396   pthread_cond_signal(&Conditional);
397   pthread_mutex_unlock(&Mutex);
398 
399   // Wait for the malloc_disable & fork, then enable the allocator again.
400   sleep(1);
401   malloc_enable();
402 
403   return nullptr;
404 }
405 
406 TEST(ScudoWrappersCTest, DisableForkEnable) {
407   pthread_t ThreadId;
408   Ready = false;
409   EXPECT_EQ(pthread_create(&ThreadId, nullptr, &enableMalloc, nullptr), 0);
410 
411   // Wait for the thread to be warmed up.
412   pthread_mutex_lock(&Mutex);
413   while (!Ready)
414     pthread_cond_wait(&Conditional, &Mutex);
415   pthread_mutex_unlock(&Mutex);
416 
417   // Disable the allocator and fork. fork should succeed after malloc_enable.
418   malloc_disable();
419   pid_t Pid = fork();
420   EXPECT_GE(Pid, 0);
421   if (Pid == 0) {
422     void *P = malloc(Size);
423     EXPECT_NE(P, nullptr);
424     memset(P, 0x42, Size);
425     free(P);
426     _exit(0);
427   }
428   waitpid(Pid, nullptr, 0);
429   EXPECT_EQ(pthread_join(ThreadId, 0), 0);
430 }
431 
432 #endif // SCUDO_FUCHSIA
433