]> git.saurik.com Git - apple/libc.git/blame - gen/malloc.c
Libc-391.4.3.tar.gz
[apple/libc.git] / gen / malloc.c
CommitLineData
e9ce8d39
A
1/*
2 * Copyright (c) 1999 Apple Computer, Inc. All rights reserved.
3 *
4 * @APPLE_LICENSE_HEADER_START@
5 *
734aad71
A
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
11 * file.
12 *
13 * The Original Code and all software distributed under the License are
14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
e9ce8d39
A
15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
734aad71
A
17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 * Please see the License for the specific language governing rights and
19 * limitations under the License.
e9ce8d39
A
20 *
21 * @APPLE_LICENSE_HEADER_END@
22 */
23
9385eb3d
A
24#include <pthread_internals.h>
25
e9ce8d39
A
26#import <stdlib.h>
27#import <stdio.h>
28#import <string.h>
29#import <unistd.h>
30#import <objc/zone.h>
9385eb3d
A
31#import <malloc/malloc.h>
32#import <fcntl.h>
3d9156a7
A
33#import <crt_externs.h>
34#import <errno.h>
59e0d9fe 35#import <pthread_internals.h>
e9ce8d39
A
36
37#import "scalable_malloc.h"
38#import "stack_logging.h"
39
40#define USE_SLEEP_RATHER_THAN_ABORT 0
41
e9ce8d39
A
42#define INITIAL_ZONES 8 // After this number, we reallocate for new zones
43
44typedef void (malloc_logger_t)(unsigned type, unsigned arg1, unsigned arg2, unsigned arg3, unsigned result, unsigned num_hot_frames_to_skip);
45
46static pthread_lock_t _malloc_lock;
47static malloc_zone_t *initial_malloc_zones[INITIAL_ZONES] = {0};
48
49/* The following variables are exported for the benefit of performance tools */
50unsigned malloc_num_zones = 0;
51malloc_zone_t **malloc_zones = initial_malloc_zones;
52malloc_logger_t *malloc_logger = NULL;
53
54unsigned malloc_debug_flags = 0;
55
56unsigned malloc_check_start = 0; // 0 means don't check
57unsigned malloc_check_counter = 0;
58unsigned malloc_check_each = 1000;
59
9385eb3d
A
60static int malloc_check_sleep = 100; // default 100 second sleep
61static int malloc_check_abort = 0; // default is to sleep, not abort
62
63static int malloc_free_abort = 0; // default is not to abort
64
3d9156a7 65static int malloc_debug_file;
9385eb3d 66
e9ce8d39
A
67#define MALLOC_LOCK() LOCK(_malloc_lock)
68#define MALLOC_UNLOCK() UNLOCK(_malloc_lock)
69
70#define MALLOC_LOG_TYPE_ALLOCATE stack_logging_type_alloc
71#define MALLOC_LOG_TYPE_DEALLOCATE stack_logging_type_dealloc
72#define MALLOC_LOG_TYPE_HAS_ZONE stack_logging_flag_zone
73#define MALLOC_LOG_TYPE_CLEARED stack_logging_flag_cleared
74
75/********* Utilities ************/
76
3d9156a7 77static inline malloc_zone_t * find_registered_zone(const void *, size_t *) __attribute__((always_inline));
9385eb3d
A
78static inline malloc_zone_t *
79find_registered_zone(const void *ptr, size_t *returned_size) {
e9ce8d39
A
80 // locates the proper zone
81 // if zone found fills returnedSize; else returns NULL
82 // See comment in malloc_zone_register() about clients non locking to call this function
83 // Speed is critical for this function
84 unsigned index = malloc_num_zones;
85 malloc_zone_t **zones = malloc_zones;
86 while (index--) {
87 malloc_zone_t *zone = *zones++;
88 size_t size;
89 size = zone->size(zone, ptr);
90 if (size) {
91 if (returned_size) *returned_size = size;
92 return zone;
93 }
94 }
95 return NULL;
96}
97
98/********* Creation and destruction ************/
99
9385eb3d
A
100static void
101_malloc_initialize(void) {
e9ce8d39
A
102 // guaranteed to be called only once
103 (void)malloc_create_zone(0, 0);
104 malloc_set_zone_name(malloc_zones[0], "DefaultMallocZone");
105 LOCK_INIT(_malloc_lock);
59e0d9fe
A
106 // malloc_printf("%d registered zones\n", malloc_num_zones);
107 // malloc_printf("malloc_zones is at %p; malloc_num_zones is at %p\n", (unsigned)&malloc_zones, (unsigned)&malloc_num_zones);
e9ce8d39
A
108}
109
3d9156a7 110static inline malloc_zone_t *inline_malloc_default_zone(void) __attribute__((always_inline));
9385eb3d
A
111static inline malloc_zone_t *
112inline_malloc_default_zone(void) {
e9ce8d39
A
113 if (!malloc_num_zones) _malloc_initialize();
114 // malloc_printf("In inline_malloc_default_zone with %d %d\n", malloc_num_zones, malloc_has_debug_zone);
115 return malloc_zones[0];
116}
117
9385eb3d
A
118malloc_zone_t *
119malloc_default_zone(void) {
e9ce8d39
A
120 return inline_malloc_default_zone();
121}
122
9385eb3d
A
123static void
124set_flags_from_environment(void) {
e9ce8d39 125 const char *flag;
59e0d9fe
A
126 int fd;
127
9385eb3d
A
128 flag = getenv("MallocLogFile");
129 if (flag) {
59e0d9fe 130 fd = open(flag, O_WRONLY|O_APPEND|O_CREAT, 0644);
9385eb3d 131 if (fd >= 0) {
7c78c529
A
132 malloc_debug_file = fd;
133 fcntl(fd, F_SETFD, 0); // clear close-on-exec flag XXX why?
59e0d9fe
A
134 } else {
135 malloc_printf("Could not open %s, using stderr\n", flag);
136 }
9385eb3d 137 }
e9ce8d39
A
138 if (getenv("MallocGuardEdges")) {
139 malloc_debug_flags = SCALABLE_MALLOC_ADD_GUARD_PAGES;
59e0d9fe 140 malloc_printf("protecting edges\n");
e9ce8d39
A
141 if (getenv("MallocDoNotProtectPrelude")) {
142 malloc_debug_flags |= SCALABLE_MALLOC_DONT_PROTECT_PRELUDE;
59e0d9fe 143 malloc_printf("... but not protecting prelude guard page\n");
e9ce8d39
A
144 }
145 if (getenv("MallocDoNotProtectPostlude")) {
146 malloc_debug_flags |= SCALABLE_MALLOC_DONT_PROTECT_POSTLUDE;
59e0d9fe 147 malloc_printf("... but not protecting postlude guard page\n");
e9ce8d39
A
148 }
149 }
150 flag = getenv("MallocStackLogging");
151 if (!flag) {
152 flag = getenv("MallocStackLoggingNoCompact");
153 stack_logging_dontcompact = 1;
154 }
155 if (flag) {
156 unsigned val = strtoul(flag, NULL, 0);
157 if (val == 1) val = 0;
158 if (val == -1) val = 0;
159 malloc_logger = (val) ? (void *)val : stack_logging_log_stack;
160 stack_logging_enable_logging = 1;
161 if (malloc_logger == stack_logging_log_stack) {
59e0d9fe 162 malloc_printf("recording stacks using standard recorder\n");
e9ce8d39 163 } else {
59e0d9fe 164 malloc_printf("recording stacks using recorder %p\n", malloc_logger);
e9ce8d39 165 }
59e0d9fe 166 if (stack_logging_dontcompact) malloc_printf("stack logging compaction turned off; VM can increase rapidly\n");
e9ce8d39
A
167 }
168 if (getenv("MallocScribble")) {
169 malloc_debug_flags |= SCALABLE_MALLOC_DO_SCRIBBLE;
59e0d9fe 170 malloc_printf("enabling scribbling to detect mods to free blocks\n");
e9ce8d39
A
171 }
172 flag = getenv("MallocCheckHeapStart");
173 if (flag) {
174 malloc_check_start = strtoul(flag, NULL, 0);
175 if (malloc_check_start == 0) malloc_check_start = 1;
176 if (malloc_check_start == -1) malloc_check_start = 1;
177 flag = getenv("MallocCheckHeapEach");
178 if (flag) {
179 malloc_check_each = strtoul(flag, NULL, 0);
180 if (malloc_check_each == 0) malloc_check_each = 1;
181 if (malloc_check_each == -1) malloc_check_each = 1;
182 }
59e0d9fe 183 malloc_printf("checks heap after %dth operation and each %d operations\n", malloc_check_start, malloc_check_each);
9385eb3d
A
184 flag = getenv("MallocCheckHeapAbort");
185 if (flag)
186 malloc_check_abort = strtol(flag, NULL, 0);
187 if (malloc_check_abort)
59e0d9fe 188 malloc_printf("will abort on heap corruption\n");
9385eb3d
A
189 else {
190 flag = getenv("MallocCheckHeapSleep");
191 if (flag)
192 malloc_check_sleep = strtol(flag, NULL, 0);
193 if (malloc_check_sleep > 0)
59e0d9fe 194 malloc_printf("will sleep for %d seconds on heap corruption\n", malloc_check_sleep);
9385eb3d 195 else if (malloc_check_sleep < 0)
59e0d9fe 196 malloc_printf("will sleep once for %d seconds on heap corruption\n", -malloc_check_sleep);
9385eb3d 197 else
59e0d9fe 198 malloc_printf("no sleep on heap corruption\n");
9385eb3d 199 }
e9ce8d39 200 }
9385eb3d
A
201 flag = getenv("MallocBadFreeAbort");
202 if (flag)
203 malloc_free_abort = strtol(flag, NULL, 0);
e9ce8d39
A
204 if (getenv("MallocHelp")) {
205 malloc_printf(
59e0d9fe 206 "environment variables that can be set for debug:\n"
9385eb3d 207 "- MallocLogFile <f> to create/append messages to file <f> instead of stderr\n"
e9ce8d39
A
208 "- MallocGuardEdges to add 2 guard pages for each large block\n"
209 "- MallocDoNotProtectPrelude to disable protection (when previous flag set)\n"
210 "- MallocDoNotProtectPostlude to disable protection (when previous flag set)\n"
211 "- MallocStackLogging to record all stacks. Tools like leaks can then be applied\n"
212 "- MallocStackLoggingNoCompact to record all stacks. Needed for malloc_history\n"
59e0d9fe
A
213 "- MallocScribble to detect writing on free blocks and missing initializers:\n"
214 " 0x55 is written upon free and 0xaa is written on allocation\n"
9385eb3d
A
215 "- MallocCheckHeapStart <n> to start checking the heap after <n> operations\n"
216 "- MallocCheckHeapEach <s> to repeat the checking of the heap after <s> operations\n"
217 "- MallocCheckHeapSleep <t> to sleep <t> seconds on heap corruption\n"
218 "- MallocCheckHeapAbort <b> to abort on heap corruption if <b> is non-zero\n"
219 "- MallocBadFreeAbort <b> to abort on a bad free if <b> is non-zero\n"
59e0d9fe 220 "- MallocHelp - this help!\n");
e9ce8d39
A
221 }
222}
223
9385eb3d 224malloc_zone_t *
7c78c529
A
225malloc_create_zone(vm_size_t start_size, unsigned flags)
226{
e9ce8d39 227 malloc_zone_t *zone;
7c78c529 228
e9ce8d39
A
229 if (!malloc_num_zones) {
230 char **env = * _NSGetEnviron();
231 char **p;
232 char *c;
7c78c529 233
3d9156a7 234 malloc_debug_file = STDERR_FILENO;
7c78c529
A
235
236 /*
237 * Given that all environment variables start with "Malloc" we optimize by scanning quickly
238 * first the environment, therefore avoiding repeated calls to getenv().
239 * If we are setu/gid these flags are ignored to prevent a malicious invoker from changing
240 * our behaviour.
241 */
e9ce8d39
A
242 for (p = env; (c = *p) != NULL; ++p) {
243 if (!strncmp(c, "Malloc", 6)) {
7c78c529
A
244 if (!issetugid())
245 set_flags_from_environment();
e9ce8d39
A
246 break;
247 }
248 }
e9ce8d39
A
249 }
250 zone = create_scalable_zone(start_size, malloc_debug_flags);
251 malloc_zone_register(zone);
252 return zone;
253}
254
9385eb3d
A
255void
256malloc_destroy_zone(malloc_zone_t *zone) {
e9ce8d39
A
257 malloc_zone_unregister(zone);
258 zone->destroy(zone);
259}
260
261/********* Block creation and manipulation ************/
262
9385eb3d
A
263static void
264internal_check(void) {
e9ce8d39
A
265 static vm_address_t *frames = NULL;
266 static unsigned num_frames;
267 if (malloc_zone_check(NULL)) {
268 malloc_printf("MallocCheckHeap: PASSED check at %dth operation\n", malloc_check_counter-1);
269 if (!frames) vm_allocate(mach_task_self(), (void *)&frames, vm_page_size, 1);
270 thread_stack_pcs(frames, vm_page_size/sizeof(vm_address_t) - 1, &num_frames);
271 } else {
272 malloc_printf("*** MallocCheckHeap: FAILED check at %dth operation\n", malloc_check_counter-1);
273 if (frames) {
274 unsigned index = 1;
275 malloc_printf("Stack for last operation where the malloc check succeeded: ");
9385eb3d 276 while (index < num_frames) malloc_printf("%p ", frames[index++]);
e9ce8d39
A
277 malloc_printf("\n(Use 'atos' for a symbolic stack)\n");
278 }
279 if (malloc_check_each > 1) {
280 unsigned recomm_each = (malloc_check_each > 10) ? malloc_check_each/10 : 1;
281 unsigned recomm_start = (malloc_check_counter > malloc_check_each+1) ? malloc_check_counter-1-malloc_check_each : 1;
282 malloc_printf("*** Recommend using 'setenv MallocCheckHeapStart %d; setenv MallocCheckHeapEach %d' to narrow down failure\n", recomm_start, recomm_each);
283 }
9385eb3d
A
284 if (malloc_check_abort)
285 abort();
286 if (malloc_check_sleep > 0) {
287 malloc_printf("*** Sleeping for %d seconds to leave time to attach\n",
288 malloc_check_sleep);
289 sleep(malloc_check_sleep);
290 } else if (malloc_check_sleep < 0) {
291 malloc_printf("*** Sleeping once for %d seconds to leave time to attach\n",
292 -malloc_check_sleep);
293 sleep(-malloc_check_sleep);
294 malloc_check_sleep = 0;
295 }
e9ce8d39
A
296 }
297 malloc_check_start += malloc_check_each;
298}
299
9385eb3d
A
300void *
301malloc_zone_malloc(malloc_zone_t *zone, size_t size) {
e9ce8d39 302 void *ptr;
e9ce8d39
A
303 if (malloc_check_start && (malloc_check_counter++ >= malloc_check_start)) {
304 internal_check();
305 }
306 ptr = zone->malloc(zone, size);
307 if (malloc_logger) malloc_logger(MALLOC_LOG_TYPE_ALLOCATE | MALLOC_LOG_TYPE_HAS_ZONE, (unsigned)zone, size, 0, (unsigned)ptr, 0);
308 return ptr;
309}
310
9385eb3d
A
311void *
312malloc_zone_calloc(malloc_zone_t *zone, size_t num_items, size_t size) {
e9ce8d39
A
313 void *ptr;
314 if (malloc_check_start && (malloc_check_counter++ >= malloc_check_start)) {
315 internal_check();
316 }
e9ce8d39
A
317 ptr = zone->calloc(zone, num_items, size);
318 if (malloc_logger) malloc_logger(MALLOC_LOG_TYPE_ALLOCATE | MALLOC_LOG_TYPE_HAS_ZONE | MALLOC_LOG_TYPE_CLEARED, (unsigned)zone, num_items * size, 0, (unsigned)ptr, 0);
319 return ptr;
320}
321
9385eb3d
A
322void *
323malloc_zone_valloc(malloc_zone_t *zone, size_t size) {
e9ce8d39 324 void *ptr;
e9ce8d39
A
325 if (malloc_check_start && (malloc_check_counter++ >= malloc_check_start)) {
326 internal_check();
327 }
328 ptr = zone->valloc(zone, size);
329 if (malloc_logger) malloc_logger(MALLOC_LOG_TYPE_ALLOCATE | MALLOC_LOG_TYPE_HAS_ZONE, (unsigned)zone, size, 0, (unsigned)ptr, 0);
330 return ptr;
331}
332
9385eb3d
A
333void *
334malloc_zone_realloc(malloc_zone_t *zone, void *ptr, size_t size) {
e9ce8d39
A
335 void *new_ptr;
336 if (malloc_check_start && (malloc_check_counter++ >= malloc_check_start)) {
337 internal_check();
338 }
339 new_ptr = zone->realloc(zone, ptr, size);
340 if (malloc_logger) malloc_logger(MALLOC_LOG_TYPE_ALLOCATE | MALLOC_LOG_TYPE_DEALLOCATE | MALLOC_LOG_TYPE_HAS_ZONE, (unsigned)zone, (unsigned)ptr, size, (unsigned)new_ptr, 0);
341 return new_ptr;
342}
343
9385eb3d
A
344void
345malloc_zone_free(malloc_zone_t *zone, void *ptr) {
e9ce8d39
A
346 if (malloc_logger) malloc_logger(MALLOC_LOG_TYPE_DEALLOCATE | MALLOC_LOG_TYPE_HAS_ZONE, (unsigned)zone, (unsigned)ptr, 0, 0, 0);
347 if (malloc_check_start && (malloc_check_counter++ >= malloc_check_start)) {
348 internal_check();
349 }
350 zone->free(zone, ptr);
351}
352
9385eb3d
A
353malloc_zone_t *
354malloc_zone_from_ptr(const void *ptr) {
e9ce8d39
A
355 malloc_zone_t *zone;
356 if (!ptr) return NULL;
357 zone = find_registered_zone(ptr, NULL);
358 return zone;
359}
360
361/********* Functions for zone implementors ************/
362
9385eb3d
A
363void
364malloc_zone_register(malloc_zone_t *zone) {
e9ce8d39
A
365 /* Note that given the sequencing it is always safe to first get the number of zones, then get malloc_zones without taking the lock, if all you need is to iterate through the list */
366 MALLOC_LOCK();
367 if (malloc_num_zones >= INITIAL_ZONES) {
368 malloc_zone_t **zones = malloc_zones;
369 malloc_zone_t *pzone = malloc_zones[0];
370 boolean_t copy = malloc_num_zones == INITIAL_ZONES;
371 if (copy) zones = NULL; // to avoid realloc on something not allocated
372 MALLOC_UNLOCK();
373 zones = pzone->realloc(pzone, zones, (malloc_num_zones + 1) * sizeof(malloc_zone_t *)); // we leak initial_malloc_zones, not worth tracking it
374 MALLOC_LOCK();
375 if (copy) memcpy(zones, malloc_zones, malloc_num_zones * sizeof(malloc_zone_t *));
376 malloc_zones = zones;
377 }
378 malloc_zones[malloc_num_zones] = zone;
379 malloc_num_zones++; // note that we do this after setting malloc_num_zones, so enumerations without taking the lock are safe
380 MALLOC_UNLOCK();
381 // malloc_printf("Registered %p malloc_zones at address %p is %p [%d zones]\n", zone, &malloc_zones, malloc_zones, malloc_num_zones);
382}
383
9385eb3d
A
384void
385malloc_zone_unregister(malloc_zone_t *z) {
e9ce8d39
A
386 unsigned index;
387 MALLOC_LOCK();
388 index = malloc_num_zones;
389 while (index--) {
390 malloc_zone_t *zone = malloc_zones[index];
391 if (zone == z) {
392 malloc_zones[index] = malloc_zones[--malloc_num_zones];
393 MALLOC_UNLOCK();
394 return;
395 }
396 }
397 MALLOC_UNLOCK();
59e0d9fe 398 malloc_printf("*** malloc_zone_unregister() failed for %p\n", z);
e9ce8d39
A
399}
400
9385eb3d
A
401void
402malloc_set_zone_name(malloc_zone_t *z, const char *name) {
e9ce8d39
A
403 char *newName;
404 if (z->zone_name) {
405 free((char *)z->zone_name);
406 z->zone_name = NULL;
407 }
408 newName = malloc_zone_malloc(z, strlen(name) + 1);
409 strcpy(newName, name);
410 z->zone_name = (const char *)newName;
411}
412
9385eb3d
A
413const char *
414malloc_get_zone_name(malloc_zone_t *zone) {
e9ce8d39
A
415 return zone->zone_name;
416}
417
59e0d9fe 418/*
3d9156a7
A
419 * XXX malloc_printf now uses _simple_{,v}dprintf. It only deals with a
420 * subset of printf format specifiers, but it doesn't call malloc.
59e0d9fe 421 */
3d9156a7
A
422void _simple_dprintf(int, const char *, ...);
423void _simple_vdprintf(int, const char *, va_list);
424
9385eb3d 425void
59e0d9fe
A
426malloc_printf(const char *format, ...)
427{
428 va_list ap;
429
430 if (__is_threaded) {
431 /* XXX somewhat rude 'knowing' that pthread_t is a pointer */
3d9156a7 432 _simple_dprintf(malloc_debug_file, "%s(%d,%p) malloc: ", getprogname(), getpid(), (void *)pthread_self());
59e0d9fe 433 } else {
3d9156a7 434 _simple_dprintf(malloc_debug_file, "%s(%d) malloc: ", getprogname(), getpid());
e9ce8d39 435 }
59e0d9fe 436 va_start(ap, format);
3d9156a7 437 _simple_vdprintf(malloc_debug_file, format, ap);
59e0d9fe 438 va_end(ap);
e9ce8d39
A
439}
440
441/********* Generic ANSI callouts ************/
442
9385eb3d
A
443void *
444malloc(size_t size) {
445 void *retval;
446 retval = malloc_zone_malloc(inline_malloc_default_zone(), size);
447 if (retval == NULL) {
448 errno = ENOMEM;
449 }
450 return retval;
e9ce8d39
A
451}
452
9385eb3d
A
453void *
454calloc(size_t num_items, size_t size) {
455 void *retval;
456 retval = malloc_zone_calloc(inline_malloc_default_zone(), num_items, size);
457 if (retval == NULL) {
458 errno = ENOMEM;
459 }
460 return retval;
e9ce8d39
A
461}
462
9385eb3d
A
463void
464free(void *ptr) {
e9ce8d39
A
465 malloc_zone_t *zone;
466 if (!ptr) return;
467 zone = find_registered_zone(ptr, NULL);
468 if (zone) {
469 malloc_zone_free(zone, ptr);
470 } else {
59e0d9fe
A
471 malloc_printf("*** Deallocation of a pointer not malloced: %p; "
472 "This could be a double free(), or free() called with the middle of an allocated block; "
473 "Try setting environment variable MallocHelp to see tools to help debug\n", ptr);
9385eb3d
A
474 if (malloc_free_abort)
475 abort();
e9ce8d39
A
476 }
477}
478
9385eb3d
A
479void *
480realloc(void *old_ptr, size_t new_size) {
481 void *retval;
e9ce8d39
A
482 malloc_zone_t *zone;
483 size_t old_size = 0;
9385eb3d
A
484 if (!old_ptr) {
485 retval = malloc_zone_malloc(inline_malloc_default_zone(), new_size);
486 } else {
487 zone = find_registered_zone(old_ptr, &old_size);
488 if (zone && (old_size >= new_size)) return old_ptr;
489 if (!zone) zone = inline_malloc_default_zone();
490 retval = malloc_zone_realloc(zone, old_ptr, new_size);
491 }
492 if (retval == NULL) {
493 errno = ENOMEM;
494 }
495 return retval;
e9ce8d39
A
496}
497
9385eb3d
A
498void *
499valloc(size_t size) {
500 void *retval;
e9ce8d39 501 malloc_zone_t *zone = inline_malloc_default_zone();
9385eb3d
A
502 retval = malloc_zone_valloc(zone, size);
503 if (retval == NULL) {
504 errno = ENOMEM;
505 }
506 return retval;
e9ce8d39
A
507}
508
9385eb3d
A
509extern void
510vfree(void *ptr) {
e9ce8d39
A
511 free(ptr);
512}
513
9385eb3d
A
514size_t
515malloc_size(const void *ptr) {
e9ce8d39
A
516 size_t size = 0;
517 if (!ptr) return size;
518 (void)find_registered_zone(ptr, &size);
519 return size;
520}
521
9385eb3d
A
522size_t
523malloc_good_size (size_t size) {
e9ce8d39
A
524 malloc_zone_t *zone = inline_malloc_default_zone();
525 return zone->introspect->good_size(zone, size);
526}
527
9385eb3d
A
528/********* Batch methods ************/
529
530unsigned
531malloc_zone_batch_malloc(malloc_zone_t *zone, size_t size, void **results, unsigned num_requested) {
532 unsigned (*batch_malloc)(malloc_zone_t *, size_t, void **, unsigned) = zone-> batch_malloc;
533 if (! batch_malloc) return 0;
534 if (malloc_check_start && (malloc_check_counter++ >= malloc_check_start)) {
535 internal_check();
536 }
537 unsigned batched = batch_malloc(zone, size, results, num_requested);
538 if (malloc_logger) {
539 unsigned index = 0;
540 while (index < batched) {
541 malloc_logger(MALLOC_LOG_TYPE_ALLOCATE | MALLOC_LOG_TYPE_HAS_ZONE, (unsigned)zone, size, 0, (unsigned)results[index], 0);
542 index++;
543 }
544 }
545 return batched;
546}
547
548void
549malloc_zone_batch_free(malloc_zone_t *zone, void **to_be_freed, unsigned num) {
550 if (malloc_check_start && (malloc_check_counter++ >= malloc_check_start)) {
551 internal_check();
552 }
553 if (malloc_logger) {
554 unsigned index = 0;
555 while (index < num) {
556 malloc_logger(MALLOC_LOG_TYPE_DEALLOCATE | MALLOC_LOG_TYPE_HAS_ZONE, (unsigned)zone, (unsigned)to_be_freed[index], 0, 0, 0);
557 index++;
558 }
559 }
560 void (*batch_free)(malloc_zone_t *, void **, unsigned) = zone-> batch_free;
561 if (batch_free) {
562 batch_free(zone, to_be_freed, num);
563 } else {
564 void (*free_fun)(malloc_zone_t *, void *) = zone->free;
565 while (num--) {
566 void *ptr = *to_be_freed++;
567 free_fun(zone, ptr);
568 }
569 }
570}
571
e9ce8d39
A
572/********* Functions for performance tools ************/
573
9385eb3d
A
574static kern_return_t
575_malloc_default_reader(task_t task, vm_address_t address, vm_size_t size, void **ptr) {
e9ce8d39
A
576 *ptr = (void *)address;
577 return 0;
578}
579
9385eb3d
A
580kern_return_t
581malloc_get_all_zones(task_t task, memory_reader_t reader, vm_address_t **addresses, unsigned *count) {
e9ce8d39
A
582 // Note that the 2 following addresses are not correct if the address of the target is different from your own. This notably occurs if the address of System.framework is slid (e.g. different than at B & I )
583 vm_address_t remote_malloc_zones = (vm_address_t)&malloc_zones;
584 vm_address_t remote_malloc_num_zones = (vm_address_t)&malloc_num_zones;
585 kern_return_t err;
586 vm_address_t zones_address;
587 vm_address_t *zones_address_ref;
588 unsigned num_zones;
589 unsigned *num_zones_ref;
590 if (!reader) reader = _malloc_default_reader;
591 // printf("Read malloc_zones at address %p should be %p\n", &malloc_zones, malloc_zones);
592 err = reader(task, remote_malloc_zones, sizeof(void *), (void **)&zones_address_ref);
9385eb3d 593 // printf("Read malloc_zones[%p]=%p\n", remote_malloc_zones, *zones_address_ref);
e9ce8d39 594 if (err) {
59e0d9fe 595 malloc_printf("*** malloc_get_all_zones: error reading zones_address at %p\n", (unsigned)remote_malloc_zones);
e9ce8d39
A
596 return err;
597 }
598 zones_address = *zones_address_ref;
599 // printf("Reading num_zones at address %p\n", remote_malloc_num_zones);
600 err = reader(task, remote_malloc_num_zones, sizeof(unsigned), (void **)&num_zones_ref);
601 if (err) {
59e0d9fe 602 malloc_printf("*** malloc_get_all_zones: error reading num_zones at %p\n", (unsigned)remote_malloc_num_zones);
e9ce8d39
A
603 return err;
604 }
605 num_zones = *num_zones_ref;
9385eb3d 606 // printf("Read malloc_num_zones[%p]=%d\n", remote_malloc_num_zones, num_zones);
e9ce8d39
A
607 *count = num_zones;
608 // printf("malloc_get_all_zones succesfully found %d zones\n", num_zones);
609 err = reader(task, zones_address, sizeof(malloc_zone_t *) * num_zones, (void **)addresses);
610 if (err) {
59e0d9fe 611 malloc_printf("*** malloc_get_all_zones: error reading zones at %p\n", (unsigned)&zones_address);
e9ce8d39
A
612 return err;
613 }
614 // printf("malloc_get_all_zones succesfully read %d zones\n", num_zones);
615 return err;
616}
617
618/********* Debug helpers ************/
619
9385eb3d
A
620void
621malloc_zone_print_ptr_info(void *ptr) {
e9ce8d39
A
622 malloc_zone_t *zone;
623 if (!ptr) return;
624 zone = find_registered_zone(ptr, NULL);
625 if (zone) {
626 printf("ptr %p in registered zone %p\n", ptr, zone);
627 } else {
628 printf("ptr %p not in heap\n", ptr);
629 }
630}
631
9385eb3d
A
632boolean_t
633malloc_zone_check(malloc_zone_t *zone) {
e9ce8d39
A
634 boolean_t ok = 1;
635 if (!zone) {
636 unsigned index = 0;
637 while (index < malloc_num_zones) {
638 zone = malloc_zones[index++];
639 if (!zone->introspect->check(zone)) ok = 0;
640 }
641 } else {
642 ok = zone->introspect->check(zone);
643 }
644 return ok;
645}
646
9385eb3d
A
647void
648malloc_zone_print(malloc_zone_t *zone, boolean_t verbose) {
e9ce8d39
A
649 if (!zone) {
650 unsigned index = 0;
651 while (index < malloc_num_zones) {
652 zone = malloc_zones[index++];
653 zone->introspect->print(zone, verbose);
654 }
655 } else {
656 zone->introspect->print(zone, verbose);
657 }
658}
659
9385eb3d
A
660void
661malloc_zone_statistics(malloc_zone_t *zone, malloc_statistics_t *stats) {
662 if (!zone) {
663 memset(stats, 0, sizeof(stats));
664 unsigned index = 0;
665 while (index < malloc_num_zones) {
666 zone = malloc_zones[index++];
667 malloc_statistics_t this_stats;
668 zone->introspect->statistics(zone, &this_stats);
669 stats->blocks_in_use += this_stats.blocks_in_use;
670 stats->size_in_use += this_stats.size_in_use;
671 stats->max_size_in_use += this_stats.max_size_in_use;
672 stats->size_allocated += this_stats.size_allocated;
673 }
674 } else {
675 zone->introspect->statistics(zone, stats);
676 }
677}
678
679void
680malloc_zone_log(malloc_zone_t *zone, void *address) {
e9ce8d39
A
681 if (!zone) {
682 unsigned index = 0;
683 while (index < malloc_num_zones) {
684 zone = malloc_zones[index++];
685 zone->introspect->log(zone, address);
686 }
687 } else {
688 zone->introspect->log(zone, address);
689 }
690}
691
692/********* Misc other entry points ************/
693
9385eb3d
A
694static void
695DefaultMallocError(int x) {
59e0d9fe 696 malloc_printf("*** error %d\n", x);
e9ce8d39
A
697#if USE_SLEEP_RATHER_THAN_ABORT
698 sleep(3600);
699#else
700 abort();
701#endif
702}
703
9385eb3d
A
704void (*
705malloc_error(void (*func)(int)))(int) {
e9ce8d39
A
706 return DefaultMallocError;
707}
708
9385eb3d
A
709void
710_malloc_fork_prepare() {
e9ce8d39
A
711 /* Prepare the malloc module for a fork by insuring that no thread is in a malloc critical section */
712 unsigned index = 0;
713 MALLOC_LOCK();
714 while (index < malloc_num_zones) {
715 malloc_zone_t *zone = malloc_zones[index++];
716 zone->introspect->force_lock(zone);
717 }
718}
719
9385eb3d
A
720void
721_malloc_fork_parent() {
e9ce8d39
A
722 /* Called in the parent process after a fork() to resume normal operation. */
723 unsigned index = 0;
724 MALLOC_UNLOCK();
725 while (index < malloc_num_zones) {
726 malloc_zone_t *zone = malloc_zones[index++];
727 zone->introspect->force_unlock(zone);
728 }
729}
730
9385eb3d
A
731void
732_malloc_fork_child() {
e9ce8d39
A
733 /* Called in the child process after a fork() to resume normal operation. In the MTASK case we also have to change memory inheritance so that the child does not share memory with the parent. */
734 unsigned index = 0;
735 MALLOC_UNLOCK();
736 while (index < malloc_num_zones) {
737 malloc_zone_t *zone = malloc_zones[index++];
738 zone->introspect->force_unlock(zone);
739 }
740}
741
59e0d9fe
A
742/*
743 * A Glibc-like mstats() interface.
744 *
745 * Note that this interface really isn't very good, as it doesn't understand
746 * that we may have multiple allocators running at once. We just massage
747 * the result from malloc_zone_statistics in any case.
748 */
749struct mstats
750mstats(void)
751{
752 malloc_statistics_t s;
753 struct mstats m;
754
755 malloc_zone_statistics(NULL, &s);
756 m.bytes_total = s.size_allocated;
757 m.chunks_used = s.blocks_in_use;
758 m.bytes_used = s.size_in_use;
759 m.chunks_free = 0;
760 m.bytes_free = m.bytes_total - m.bytes_used; /* isn't this somewhat obvious? */
761
762 return(m);
e9ce8d39
A
763}
764
765/***************** OBSOLETE ENTRY POINTS ********************/
766
767#if PHASE_OUT_OLD_MALLOC
768#error PHASE OUT THE FOLLOWING FUNCTIONS
769#else
770#warning PHASE OUT THE FOLLOWING FUNCTIONS
771#endif
772
9385eb3d
A
773void
774set_malloc_singlethreaded(boolean_t single) {
e9ce8d39
A
775 static boolean_t warned = 0;
776 if (!warned) {
777#if PHASE_OUT_OLD_MALLOC
59e0d9fe 778 malloc_printf("*** OBSOLETE: set_malloc_singlethreaded(%d)\n", single);
e9ce8d39
A
779#endif
780 warned = 1;
781 }
782}
783
9385eb3d
A
784void
785malloc_singlethreaded() {
e9ce8d39
A
786 static boolean_t warned = 0;
787 if (!warned) {
59e0d9fe 788 malloc_printf("*** OBSOLETE: malloc_singlethreaded()\n");
e9ce8d39
A
789 warned = 1;
790 }
791}
792
9385eb3d
A
793int
794malloc_debug(int level) {
59e0d9fe 795 malloc_printf("*** OBSOLETE: malloc_debug()\n");
e9ce8d39
A
796 return 0;
797}