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