xref: /openbsd-src/regress/lib/libc/malloc/malloc_general/malloc_general.c (revision ae3cb403620ab940fbaabb3055fac045a63d56b7)
1 /*	$OpenBSD	*/
2 /*
3  * Copyright (c) 2017 Otto Moerbeek <otto@drijf.net>
4  *
5  * Permission to use, copy, modify, and distribute this software for any
6  * purpose with or without fee is hereby granted, provided that the above
7  * copyright notice and this permission notice appear in all copies.
8  *
9  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16  */
17 
18 #include <err.h>
19 #include <stdio.h>
20 #include <stdlib.h>
21 #include <string.h>
22 
23 /* $define VERBOSE */
24 
25 #define N 1000
26 
27 size_t
28 size(void)
29 {
30 	int p = arc4random_uniform(13) + 3;
31 	return arc4random_uniform(1 << p);
32 }
33 
34 struct { void *p; size_t sz; } a[N];
35 
36 extern char *malloc_options;
37 
38 void
39 fill(u_char *p, size_t sz)
40 {
41 	size_t i;
42 
43 	for (i = 0; i < sz; i++)
44 		p[i] = i % 256;
45 }
46 
47 void
48 check(u_char *p, size_t sz)
49 {
50 	size_t i;
51 
52 	for (i = 0; i < sz; i++)
53 		if (p[i] != i % 256)
54 			errx(1, "check");
55 }
56 
57 int
58 main(int argc, char *argv[])
59 {
60 	int count, p, i;
61 	void * q;
62 	size_t sz;
63 
64 	if (argc == 1)
65 		errx(1, "usage: malloc_options");
66 
67 	malloc_options = argv[1];
68 
69 	for (count = 0; count < 800000; count++) {
70 		if (count % 10000 == 0) {
71 			printf(".");
72 			fflush(stdout);
73 		}
74 		p = arc4random_uniform(2);
75 		i = arc4random_uniform(N);
76 		switch (p) {
77 		case 0:
78 			if (a[i].p) {
79 #ifdef VERBOSE
80 				printf("F %p\n", a[i].p);
81 #endif
82 				if (a[i].p)
83 					check(a[i].p, a[i].sz);
84 				free(a[i].p);
85 				a[i].p = NULL;
86 			}
87 			sz = size();
88 #ifdef VERBOSE
89 			printf("M %zu=", sz);
90 #endif
91 			a[i].p = malloc(sz);
92 			a[i].sz = sz;
93 #ifdef VERBOSE
94 			printf("%p\n", a[i].p);
95 #endif
96 			if (a[i].p)
97 				fill(a[i].p, sz);
98 			break;
99 		case 1:
100 			sz = size();
101 #ifdef VERBOSE
102 			printf("R %p %zu=", a[i].p, sz);
103 #endif
104 			q = realloc(a[i].p, sz);
105 #ifdef VERBOSE
106 			printf("%p\n", q);
107 #endif
108 			if (a[i].p && q)
109 				check(q, a[i].sz < sz ? a[i].sz : sz);
110 			if (q) {
111 				a[i].p = q;
112 				a[i].sz = sz;
113 				fill(a[i].p, sz);
114 			}
115 			break;
116 		}
117 	}
118 	for (i = 0; i < N; i++) {
119 		if (a[i].p)
120 			check(a[i].p, a[i].sz);
121 		free(a[i].p);
122 	}
123 	printf("\n");
124 	return 0;
125 }
126