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