1 // This is a program that leaks memory, used for memory leak detector testing.
2
3 #include <fcntl.h>
4 #include <malloc.h>
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <string.h>
8 #include <sys/stat.h>
9 #include <sys/types.h>
10 #include <unistd.h>
11
generate_leak(const char * kind,int amount)12 static void generate_leak(const char *kind, int amount) {
13 void *ptr = NULL;
14
15 if (strcmp(kind, "malloc") == 0) {
16 printf("leaking via malloc, %p\n", malloc(amount));
17 return;
18 }
19
20 if (strcmp(kind, "calloc") == 0) {
21 printf("leaking via calloc, %p\n", calloc(amount, 1));
22 return;
23 }
24
25 if (strcmp(kind, "realloc") == 0) {
26 printf("leaking via realloc, %p\n", realloc(malloc(10), amount));
27 return;
28 }
29
30 if (strcmp(kind, "posix_memalign") == 0) {
31 posix_memalign(&ptr, 512, amount);
32 printf("leaking via posix_memalign, %p\n", ptr);
33 return;
34 }
35
36 if (strcmp(kind, "valloc") == 0) {
37 printf("leaking via valloc, %p\n", valloc(amount));
38 return;
39 }
40
41 if (strcmp(kind, "memalign") == 0) {
42 printf("leaking via memalign, %p\n", memalign(512, amount));
43 return;
44 }
45
46 if (strcmp(kind, "pvalloc") == 0) {
47 printf("leaking via pvalloc, %p\n", pvalloc(amount));
48 return;
49 }
50
51 if (strcmp(kind, "aligned_alloc") == 0) {
52 printf("leaking via aligned_alloc, %p\n", aligned_alloc(512, amount));
53 return;
54 }
55
56 if (strcmp(kind, "no_leak") == 0) {
57 void *ptr = malloc(amount);
58 printf("ptr = %p\n", ptr);
59 free(ptr);
60 return;
61 }
62
63 printf("unknown leak type '%s'\n", kind);
64 }
65
main(int argc,char * argv[])66 int main(int argc, char *argv[]) {
67 if (argc < 2) {
68 printf("usage: leak-userspace <kind-of-leak> [amount]\n");
69 return EXIT_SUCCESS;
70 }
71
72 const char *kind = argv[1];
73
74 int amount = 30;
75 if (argc > 2) {
76 amount = atoi(argv[2]);
77 if (amount < 1)
78 amount = 1;
79 }
80
81 // Wait for something in stdin to give external detector time to attach.
82 char c;
83 read(0, &c, sizeof(c));
84
85 // Do the work.
86 generate_leak(kind, amount);
87 return EXIT_SUCCESS;
88 }
89