]> git.saurik.com Git - apple/libc.git/blob - gen/malloc.c
e89051bb95fdd5669f3e77e8c21e68cd0ee89e53
[apple/libc.git] / gen / malloc.c
1 /*
2 * Copyright (c) 1999, 2006-2008 Apple 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 #include "magmallocProvider.h"
26
27 #import <stdlib.h>
28 #import <stdio.h>
29 #import <string.h>
30 #import <unistd.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 #import <limits.h>
37 #import <dlfcn.h>
38 #import <mach/mach_vm.h>
39 #import <mach/mach_init.h>
40 #import <sys/mman.h>
41
42 #import "scalable_malloc.h"
43 #import "stack_logging.h"
44 #import "malloc_printf.h"
45 #import "_simple.h"
46
47 /*
48 * MALLOC_ABSOLUTE_MAX_SIZE - There are many instances of addition to a
49 * user-specified size_t, which can cause overflow (and subsequent crashes)
50 * for values near SIZE_T_MAX. Rather than add extra "if" checks everywhere
51 * this occurs, it is easier to just set an absolute maximum request size,
52 * and immediately return an error if the requested size exceeds this maximum.
53 * Of course, values less than this absolute max can fail later if the value
54 * is still too large for the available memory. The largest value added
55 * seems to be PAGE_SIZE (in the macro round_page()), so to be safe, we set
56 * the maximum to be 2 * PAGE_SIZE less than SIZE_T_MAX.
57 */
58 #define MALLOC_ABSOLUTE_MAX_SIZE (SIZE_T_MAX - (2 * PAGE_SIZE))
59
60 #define USE_SLEEP_RATHER_THAN_ABORT 0
61
62 typedef void (malloc_logger_t)(uint32_t type, uintptr_t arg1, uintptr_t arg2, uintptr_t arg3, uintptr_t result, uint32_t num_hot_frames_to_skip);
63
64 __private_extern__ pthread_lock_t _malloc_lock = 0; // initialized in __libc_init
65
66 /* The following variables are exported for the benefit of performance tools
67 *
68 * It should always be safe to first read malloc_num_zones, then read
69 * malloc_zones without taking the lock, if only iteration is required
70 */
71 unsigned malloc_num_zones = 0;
72 unsigned malloc_num_zones_allocated = 0;
73 malloc_zone_t **malloc_zones = 0;
74 malloc_logger_t *malloc_logger = NULL;
75
76 unsigned malloc_debug_flags = 0;
77
78 unsigned malloc_check_start = 0; // 0 means don't check
79 unsigned malloc_check_counter = 0;
80 unsigned malloc_check_each = 1000;
81
82 /* global flag to suppress ASL logging e.g. for syslogd */
83 int _malloc_no_asl_log = 0;
84
85 static int malloc_check_sleep = 100; // default 100 second sleep
86 static int malloc_check_abort = 0; // default is to sleep, not abort
87
88 static int malloc_debug_file = STDERR_FILENO;
89 /*
90 * State indicated by malloc_def_zone_state
91 * 0 - the default zone has not yet been created
92 * 1 - a Malloc* environment variable has been set
93 * 2 - the default zone has been created and an environment variable scan done
94 * 3 - a new default zone has been created and another environment variable scan
95 */
96 __private_extern__ int malloc_def_zone_state = 0;
97 __private_extern__ malloc_zone_t *__zone0 = NULL;
98
99 static const char Malloc_Facility[] = "com.apple.Libsystem.malloc";
100
101 #define MALLOC_LOCK() LOCK(_malloc_lock)
102 #define MALLOC_UNLOCK() UNLOCK(_malloc_lock)
103
104 #define MALLOC_LOG_TYPE_ALLOCATE stack_logging_type_alloc
105 #define MALLOC_LOG_TYPE_DEALLOCATE stack_logging_type_dealloc
106 #define MALLOC_LOG_TYPE_HAS_ZONE stack_logging_flag_zone
107 #define MALLOC_LOG_TYPE_CLEARED stack_logging_flag_cleared
108
109 /********* Utilities ************/
110
111 static inline malloc_zone_t * find_registered_zone(const void *, size_t *) __attribute__((always_inline));
112 static inline malloc_zone_t *
113 find_registered_zone(const void *ptr, size_t *returned_size) {
114 // Returns a zone which contains ptr, else NULL
115 unsigned index;
116 malloc_zone_t **zones = malloc_zones;
117
118 for (index = 0; index < malloc_num_zones; ++index, ++zones) {
119 malloc_zone_t *zone = *zones;
120 size_t size = zone->size(zone, ptr);
121 if (size) { // Claimed by this zone?
122 if (returned_size) *returned_size = size;
123 return zone;
124 }
125 }
126 // Unclaimed by any zone.
127 if (returned_size) *returned_size = 0;
128 return NULL;
129 }
130
131 __private_extern__ __attribute__((noinline)) void
132 malloc_error_break(void) {
133 // Provides a non-inlined place for various malloc error procedures to call
134 // that will be called after an error message appears. It does not make
135 // sense for developers to call this function, so it is marked
136 // __private_extern__ to prevent it from becoming API.
137 MAGMALLOC_MALLOCERRORBREAK(); // DTrace USDT probe
138 }
139
140 __private_extern__ boolean_t __stack_logging_locked();
141
142 __private_extern__ __attribute__((noinline)) int
143 malloc_gdb_po_unsafe(void) {
144 // In order to implement "po" other data formatters in gdb, the debugger
145 // calls functions that call malloc. The debugger will only run one thread
146 // of the program in this case, so if another thread is holding a zone lock,
147 // gdb may deadlock in this case.
148 //
149 // Iterate over the zones in malloc_zones, and call "trylock" on the zone
150 // lock. If trylock succeeds, unlock it, otherwise return "locked". Returns
151 // 0 == safe, 1 == locked/unsafe.
152
153 if (__stack_logging_locked())
154 return 1;
155
156 malloc_zone_t **zones = malloc_zones;
157 unsigned i, e = malloc_num_zones;
158
159 for (i = 0; i != e; ++i) {
160 malloc_zone_t *zone = zones[i];
161
162 // Version must be >= 5 to look at the new introspection field.
163 if (zone->version < 5)
164 continue;
165
166 if (zone->introspect->zone_locked && zone->introspect->zone_locked(zone))
167 return 1;
168 }
169 return 0;
170 }
171
172 /********* Creation and destruction ************/
173
174 static void set_flags_from_environment(void);
175
176 static void
177 malloc_zone_register_while_locked(malloc_zone_t *zone) {
178 size_t protect_size;
179 unsigned i;
180
181 /* scan the list of zones, to see if this zone is already registered. If
182 * so, print an error message and return. */
183 for (i = 0; i != malloc_num_zones; ++i)
184 if (zone == malloc_zones[i]) {
185 _malloc_printf(ASL_LEVEL_ERR, "Attempted to register zone more than once: %p\n", zone);
186 return;
187 }
188
189 if (malloc_num_zones == malloc_num_zones_allocated) {
190 size_t malloc_zones_size = malloc_num_zones * sizeof(malloc_zone_t *);
191 size_t alloc_size = malloc_zones_size + vm_page_size;
192
193 malloc_zone_t **new_zones = mmap(0, alloc_size, PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE, VM_MAKE_TAG(VM_MEMORY_MALLOC), 0);
194
195 /* If there were previously allocated malloc zones, we need to copy them
196 * out of the previous array and into the new zones array */
197 if (malloc_zones)
198 memcpy(new_zones, malloc_zones, malloc_zones_size);
199
200 /* Update the malloc_zones pointer, which we leak if it was previously
201 * allocated, and the number of zones allocated */
202 protect_size = alloc_size;
203 malloc_zones = new_zones;
204 malloc_num_zones_allocated = alloc_size / sizeof(malloc_zone_t *);
205 } else {
206 /* If we don't need to reallocate zones, we need to briefly change the
207 * page protection the malloc zones to allow writes */
208 protect_size = malloc_num_zones_allocated * sizeof(malloc_zone_t *);
209 vm_protect(mach_task_self(), (uintptr_t)malloc_zones, protect_size, 0, VM_PROT_READ | VM_PROT_WRITE);
210 }
211 malloc_zones[malloc_num_zones++] = zone;
212
213 /* Finally, now that the zone is registered, disallow write access to the
214 * malloc_zones array */
215 vm_protect(mach_task_self(), (uintptr_t)malloc_zones, protect_size, 0, VM_PROT_READ);
216 //_malloc_printf(ASL_LEVEL_INFO, "Registered malloc_zone %p in malloc_zones %p [%u zones, %u bytes]\n", zone, malloc_zones, malloc_num_zones, protect_size);
217 }
218
219 static void
220 _malloc_initialize(void) {
221 MALLOC_LOCK();
222 if (malloc_def_zone_state < 2) {
223 unsigned n;
224 malloc_zone_t *zone;
225
226 malloc_def_zone_state += 2;
227 set_flags_from_environment(); // will only set flags up to two times
228 n = malloc_num_zones;
229 zone = create_scalable_zone(0, malloc_debug_flags);
230 malloc_zone_register_while_locked(zone);
231 malloc_set_zone_name(zone, "DefaultMallocZone");
232 if (n != 0) { // make the default first, for efficiency
233 unsigned protect_size = malloc_num_zones_allocated * sizeof(malloc_zone_t *);
234 malloc_zone_t *hold = malloc_zones[0];
235 if(hold->zone_name && strcmp(hold->zone_name, "DefaultMallocZone") == 0) {
236 free((void *)hold->zone_name);
237 hold->zone_name = NULL;
238 }
239 vm_protect(mach_task_self(), (uintptr_t)malloc_zones, protect_size, 0, VM_PROT_READ | VM_PROT_WRITE);
240 malloc_zones[0] = malloc_zones[n];
241 malloc_zones[n] = hold;
242 vm_protect(mach_task_self(), (uintptr_t)malloc_zones, protect_size, 0, VM_PROT_READ);
243 }
244 // _malloc_printf(ASL_LEVEL_INFO, "%d registered zones\n", malloc_num_zones);
245 // _malloc_printf(ASL_LEVEL_INFO, "malloc_zones is at %p; malloc_num_zones is at %p\n", (unsigned)&malloc_zones, (unsigned)&malloc_num_zones);
246 }
247 MALLOC_UNLOCK();
248 }
249
250 static inline malloc_zone_t *inline_malloc_default_zone(void) __attribute__((always_inline));
251 static inline malloc_zone_t *
252 inline_malloc_default_zone(void) {
253 if (malloc_def_zone_state < 2) _malloc_initialize();
254 // _malloc_printf(ASL_LEVEL_INFO, "In inline_malloc_default_zone with %d %d\n", malloc_num_zones, malloc_has_debug_zone);
255 return malloc_zones[0];
256 }
257
258 malloc_zone_t *
259 malloc_default_zone(void) {
260 return inline_malloc_default_zone();
261 }
262
263 malloc_zone_t *
264 malloc_default_purgeable_zone(void) {
265 static malloc_zone_t *dpz;
266
267 if (!dpz) {
268 malloc_zone_t *tmp = create_purgeable_zone(0, malloc_default_zone(), malloc_debug_flags);
269 malloc_zone_register(tmp);
270 malloc_set_zone_name(tmp, "DefaultPurgeableMallocZone");
271 if (!__sync_bool_compare_and_swap(&dpz, NULL, tmp))
272 malloc_destroy_zone(tmp);
273 }
274 return dpz;
275 }
276
277 // For debugging, allow stack logging to both memory and disk to compare their results.
278 static void
279 stack_logging_log_stack_debug(uint32_t type_flags, uintptr_t zone_ptr, uintptr_t size, uintptr_t ptr_arg, uintptr_t return_val, uint32_t num_hot_to_skip)
280 {
281 __disk_stack_logging_log_stack(type_flags, zone_ptr, size, ptr_arg, return_val, num_hot_to_skip);
282 stack_logging_log_stack(type_flags, zone_ptr, size, ptr_arg, return_val, num_hot_to_skip);
283 }
284
285 static void
286 set_flags_from_environment(void) {
287 const char *flag;
288 int fd;
289 char **env = * _NSGetEnviron();
290 char **p;
291 char *c;
292
293 if (malloc_debug_file != STDERR_FILENO) {
294 close(malloc_debug_file);
295 malloc_debug_file = STDERR_FILENO;
296 }
297 #if __LP64__
298 malloc_debug_flags = SCALABLE_MALLOC_ABORT_ON_CORRUPTION; // Set always on 64-bit processes
299 #else
300 malloc_debug_flags = 0;
301 #endif
302 stack_logging_enable_logging = 0;
303 stack_logging_dontcompact = 0;
304 malloc_logger = NULL;
305 malloc_check_start = 0;
306 malloc_check_each = 1000;
307 malloc_check_abort = 0;
308 malloc_check_sleep = 100;
309 /*
310 * Given that all environment variables start with "Malloc" we optimize by scanning quickly
311 * first the environment, therefore avoiding repeated calls to getenv().
312 * If we are setu/gid these flags are ignored to prevent a malicious invoker from changing
313 * our behaviour.
314 */
315 for (p = env; (c = *p) != NULL; ++p) {
316 if (!strncmp(c, "Malloc", 6)) {
317 if (issetugid())
318 return;
319 break;
320 }
321 }
322 if (c == NULL)
323 return;
324 flag = getenv("MallocLogFile");
325 if (flag) {
326 fd = open(flag, O_WRONLY|O_APPEND|O_CREAT, 0644);
327 if (fd >= 0) {
328 malloc_debug_file = fd;
329 fcntl(fd, F_SETFD, 0); // clear close-on-exec flag XXX why?
330 } else {
331 malloc_printf("Could not open %s, using stderr\n", flag);
332 }
333 }
334 if (getenv("MallocGuardEdges")) {
335 malloc_debug_flags = SCALABLE_MALLOC_ADD_GUARD_PAGES;
336 _malloc_printf(ASL_LEVEL_INFO, "protecting edges\n");
337 if (getenv("MallocDoNotProtectPrelude")) {
338 malloc_debug_flags |= SCALABLE_MALLOC_DONT_PROTECT_PRELUDE;
339 _malloc_printf(ASL_LEVEL_INFO, "... but not protecting prelude guard page\n");
340 }
341 if (getenv("MallocDoNotProtectPostlude")) {
342 malloc_debug_flags |= SCALABLE_MALLOC_DONT_PROTECT_POSTLUDE;
343 _malloc_printf(ASL_LEVEL_INFO, "... but not protecting postlude guard page\n");
344 }
345 }
346 flag = getenv("MallocStackLogging");
347 if (!flag) {
348 flag = getenv("MallocStackLoggingNoCompact");
349 stack_logging_dontcompact = 1;
350 }
351 // For debugging, the MallocStackLogging or MallocStackLoggingNoCompact environment variables can be set to
352 // values of "memory", "disk", or "both" to control which stack logging mechanism to use. Those strings appear
353 // in the flag variable, and the strtoul() call below will return 0, so then we can do string comparison on the
354 // value of flag. The default stack logging now is disk stack logging, since memory stack logging is not 64-bit-aware.
355 if (flag) {
356 unsigned long val = strtoul(flag, NULL, 0);
357 if (val == 1) val = 0;
358 if (val == -1) val = 0;
359 if (val) {
360 malloc_logger = (void *)val;
361 _malloc_printf(ASL_LEVEL_INFO, "recording stacks using recorder %p\n", malloc_logger);
362 } else if (strcmp(flag,"memory") == 0) {
363 malloc_logger = (malloc_logger_t *)stack_logging_log_stack;
364 _malloc_printf(ASL_LEVEL_INFO, "recording malloc stacks in memory using standard recorder\n");
365 } else if (strcmp(flag,"both") == 0) {
366 malloc_logger = stack_logging_log_stack_debug;
367 _malloc_printf(ASL_LEVEL_INFO, "recording malloc stacks to both memory and disk for comparison debugging\n");
368 } else { // the default is to log to disk
369 malloc_logger = __disk_stack_logging_log_stack;
370 _malloc_printf(ASL_LEVEL_INFO, "recording malloc stacks to disk using standard recorder\n");
371 }
372 stack_logging_enable_logging = 1;
373 if (stack_logging_dontcompact) {
374 if (malloc_logger == __disk_stack_logging_log_stack) {
375 _malloc_printf(ASL_LEVEL_INFO, "stack logging compaction turned off; size of log files on disk can increase rapidly\n");
376 } else {
377 _malloc_printf(ASL_LEVEL_INFO, "stack logging compaction turned off; VM can increase rapidly\n");
378 }
379 }
380 }
381 if (getenv("MallocScribble")) {
382 malloc_debug_flags |= SCALABLE_MALLOC_DO_SCRIBBLE;
383 _malloc_printf(ASL_LEVEL_INFO, "enabling scribbling to detect mods to free blocks\n");
384 }
385 if (getenv("MallocErrorAbort")) {
386 malloc_debug_flags |= SCALABLE_MALLOC_ABORT_ON_ERROR;
387 _malloc_printf(ASL_LEVEL_INFO, "enabling abort() on bad malloc or free\n");
388 }
389 #if __LP64__
390 /* initialization above forces SCALABLE_MALLOC_ABORT_ON_CORRUPTION of 64-bit processes */
391 #else
392 if (getenv("MallocCorruptionAbort")) { // Set from an environment variable in 32-bit processes
393 malloc_debug_flags |= SCALABLE_MALLOC_ABORT_ON_CORRUPTION;
394 }
395 #endif
396 flag = getenv("MallocCheckHeapStart");
397 if (flag) {
398 malloc_check_start = strtoul(flag, NULL, 0);
399 if (malloc_check_start == 0) malloc_check_start = 1;
400 if (malloc_check_start == -1) malloc_check_start = 1;
401 flag = getenv("MallocCheckHeapEach");
402 if (flag) {
403 malloc_check_each = strtoul(flag, NULL, 0);
404 if (malloc_check_each == 0) malloc_check_each = 1;
405 if (malloc_check_each == -1) malloc_check_each = 1;
406 }
407 _malloc_printf(ASL_LEVEL_INFO, "checks heap after %dth operation and each %d operations\n", malloc_check_start, malloc_check_each);
408 flag = getenv("MallocCheckHeapAbort");
409 if (flag)
410 malloc_check_abort = strtol(flag, NULL, 0);
411 if (malloc_check_abort)
412 _malloc_printf(ASL_LEVEL_INFO, "will abort on heap corruption\n");
413 else {
414 flag = getenv("MallocCheckHeapSleep");
415 if (flag)
416 malloc_check_sleep = strtol(flag, NULL, 0);
417 if (malloc_check_sleep > 0)
418 _malloc_printf(ASL_LEVEL_INFO, "will sleep for %d seconds on heap corruption\n", malloc_check_sleep);
419 else if (malloc_check_sleep < 0)
420 _malloc_printf(ASL_LEVEL_INFO, "will sleep once for %d seconds on heap corruption\n", -malloc_check_sleep);
421 else
422 _malloc_printf(ASL_LEVEL_INFO, "no sleep on heap corruption\n");
423 }
424 }
425 if (getenv("MallocHelp")) {
426 _malloc_printf(ASL_LEVEL_INFO,
427 "environment variables that can be set for debug:\n"
428 "- MallocLogFile <f> to create/append messages to file <f> instead of stderr\n"
429 "- MallocGuardEdges to add 2 guard pages for each large block\n"
430 "- MallocDoNotProtectPrelude to disable protection (when previous flag set)\n"
431 "- MallocDoNotProtectPostlude to disable protection (when previous flag set)\n"
432 "- MallocStackLogging to record all stacks. Tools like leaks can then be applied\n"
433 "- MallocStackLoggingNoCompact to record all stacks. Needed for malloc_history\n"
434 "- MallocStackLoggingDirectory to set location of stack logs, which can grow large; default is /tmp\n"
435 "- MallocScribble to detect writing on free blocks and missing initializers:\n"
436 " 0x55 is written upon free and 0xaa is written on allocation\n"
437 "- MallocCheckHeapStart <n> to start checking the heap after <n> operations\n"
438 "- MallocCheckHeapEach <s> to repeat the checking of the heap after <s> operations\n"
439 "- MallocCheckHeapSleep <t> to sleep <t> seconds on heap corruption\n"
440 "- MallocCheckHeapAbort <b> to abort on heap corruption if <b> is non-zero\n"
441 "- MallocCorruptionAbort to abort on malloc errors, but not on out of memory for 32-bit processes\n"
442 " MallocCorruptionAbort is always set on 64-bit processes\n"
443 "- MallocErrorAbort to abort on any malloc error, including out of memory\n"
444 "- MallocHelp - this help!\n");
445 }
446 }
447
448 malloc_zone_t *
449 malloc_create_zone(vm_size_t start_size, unsigned flags)
450 {
451 malloc_zone_t *zone;
452
453 /* start_size doesn't seemed to actually be used, but we test anyways */
454 if (start_size > MALLOC_ABSOLUTE_MAX_SIZE) {
455 return NULL;
456 }
457 if (malloc_def_zone_state < 2) _malloc_initialize();
458 zone = create_scalable_zone(start_size, flags | malloc_debug_flags);
459 malloc_zone_register(zone);
460 return zone;
461 }
462
463 /*
464 * For use by CheckFix: establish a new default zone whose behavior is, apart from
465 * the use of death-row and per-CPU magazines, that of Leopard.
466 */
467 void
468 malloc_create_legacy_default_zone(void)
469 {
470 malloc_zone_t *zone;
471 int i;
472
473 if (malloc_def_zone_state < 2) _malloc_initialize();
474 zone = create_legacy_scalable_zone(0, malloc_debug_flags);
475
476 MALLOC_LOCK();
477 malloc_zone_register_while_locked(zone);
478
479 //
480 // Establish the legacy scalable zone just created as the default zone.
481 //
482 malloc_zone_t *hold = malloc_zones[0];
483 if(hold->zone_name && strcmp(hold->zone_name, "DefaultMallocZone") == 0) {
484 free((void *)hold->zone_name);
485 hold->zone_name = NULL;
486 }
487 malloc_set_zone_name(zone, "DefaultMallocZone");
488
489 unsigned protect_size = malloc_num_zones_allocated * sizeof(malloc_zone_t *);
490 vm_protect(mach_task_self(), (uintptr_t)malloc_zones, protect_size, 0, VM_PROT_READ | VM_PROT_WRITE);
491
492 // assert(zone == malloc_zones[malloc_num_zones - 1];
493 for (i = malloc_num_zones - 1; i > 0; --i) {
494 malloc_zones[i] = malloc_zones[i - 1];
495 }
496 malloc_zones[0] = zone;
497
498 vm_protect(mach_task_self(), (uintptr_t)malloc_zones, protect_size, 0, VM_PROT_READ);
499 MALLOC_UNLOCK();
500 }
501
502 void
503 malloc_destroy_zone(malloc_zone_t *zone) {
504 malloc_zone_unregister(zone);
505 zone->destroy(zone);
506 }
507
508 /* called from the {put,set,unset}env routine */
509 __private_extern__ void
510 __malloc_check_env_name(const char *name)
511 {
512 MALLOC_LOCK();
513 if(malloc_def_zone_state == 2 && strncmp(name, "Malloc", 6) == 0)
514 malloc_def_zone_state = 1;
515 MALLOC_UNLOCK();
516 }
517
518 /********* Block creation and manipulation ************/
519
520 extern const char *__crashreporter_info__;
521
522 static void
523 internal_check(void) {
524 static vm_address_t *frames = NULL;
525 static unsigned num_frames;
526 if (malloc_zone_check(NULL)) {
527 if (!frames) vm_allocate(mach_task_self(), (void *)&frames, vm_page_size, 1);
528 thread_stack_pcs(frames, vm_page_size/sizeof(vm_address_t) - 1, &num_frames);
529 } else {
530 _SIMPLE_STRING b = _simple_salloc();
531 if (b)
532 _simple_sprintf(b, "*** MallocCheckHeap: FAILED check at %dth operation\n", malloc_check_counter-1);
533 else
534 _malloc_printf(MALLOC_PRINTF_NOLOG, "*** MallocCheckHeap: FAILED check at %dth operation\n", malloc_check_counter-1);
535 malloc_printf("*** MallocCheckHeap: FAILED check at %dth operation\n", malloc_check_counter-1);
536 if (frames) {
537 unsigned index = 1;
538 if (b) {
539 _simple_sappend(b, "Stack for last operation where the malloc check succeeded: ");
540 while (index < num_frames) _simple_sprintf(b, "%p ", frames[index++]);
541 malloc_printf("%s\n(Use 'atos' for a symbolic stack)\n", _simple_string(b));
542 } else {
543 /*
544 * Should only get here if vm_allocate() can't get a single page of
545 * memory, implying _simple_asl_log() would also fail. So we just
546 * print to the file descriptor.
547 */
548 _malloc_printf(MALLOC_PRINTF_NOLOG, "Stack for last operation where the malloc check succeeded: ");
549 while (index < num_frames) _malloc_printf(MALLOC_PRINTF_NOLOG, "%p ", frames[index++]);
550 _malloc_printf(MALLOC_PRINTF_NOLOG, "\n(Use 'atos' for a symbolic stack)\n");
551 }
552 }
553 if (malloc_check_each > 1) {
554 unsigned recomm_each = (malloc_check_each > 10) ? malloc_check_each/10 : 1;
555 unsigned recomm_start = (malloc_check_counter > malloc_check_each+1) ? malloc_check_counter-1-malloc_check_each : 1;
556 malloc_printf("*** Recommend using 'setenv MallocCheckHeapStart %d; setenv MallocCheckHeapEach %d' to narrow down failure\n", recomm_start, recomm_each);
557 }
558 if (malloc_check_abort) {
559 __crashreporter_info__ = b ? _simple_string(b) : "*** MallocCheckHeap: FAILED check";
560 abort();
561 } else if (b)
562 _simple_sfree(b);
563 if (malloc_check_sleep > 0) {
564 _malloc_printf(ASL_LEVEL_NOTICE, "*** Sleeping for %d seconds to leave time to attach\n",
565 malloc_check_sleep);
566 sleep(malloc_check_sleep);
567 } else if (malloc_check_sleep < 0) {
568 _malloc_printf(ASL_LEVEL_NOTICE, "*** Sleeping once for %d seconds to leave time to attach\n",
569 -malloc_check_sleep);
570 sleep(-malloc_check_sleep);
571 malloc_check_sleep = 0;
572 }
573 }
574 malloc_check_start += malloc_check_each;
575 }
576
577 void *
578 malloc_zone_malloc(malloc_zone_t *zone, size_t size) {
579 void *ptr;
580 if (malloc_check_start && (malloc_check_counter++ >= malloc_check_start)) {
581 internal_check();
582 }
583 if (size > MALLOC_ABSOLUTE_MAX_SIZE) {
584 return NULL;
585 }
586 ptr = zone->malloc(zone, size);
587 if (malloc_logger) malloc_logger(MALLOC_LOG_TYPE_ALLOCATE | MALLOC_LOG_TYPE_HAS_ZONE, (uintptr_t)zone, (uintptr_t)size, 0, (uintptr_t)ptr, 0);
588 return ptr;
589 }
590
591 void *
592 malloc_zone_calloc(malloc_zone_t *zone, size_t num_items, size_t size) {
593 void *ptr;
594 if (malloc_check_start && (malloc_check_counter++ >= malloc_check_start)) {
595 internal_check();
596 }
597 if (size > MALLOC_ABSOLUTE_MAX_SIZE) {
598 return NULL;
599 }
600 ptr = zone->calloc(zone, num_items, size);
601 if (malloc_logger) malloc_logger(MALLOC_LOG_TYPE_ALLOCATE | MALLOC_LOG_TYPE_HAS_ZONE | MALLOC_LOG_TYPE_CLEARED, (uintptr_t)zone, (uintptr_t)(num_items * size), 0, (uintptr_t)ptr, 0);
602 return ptr;
603 }
604
605 void *
606 malloc_zone_valloc(malloc_zone_t *zone, size_t size) {
607 void *ptr;
608 if (malloc_check_start && (malloc_check_counter++ >= malloc_check_start)) {
609 internal_check();
610 }
611 if (size > MALLOC_ABSOLUTE_MAX_SIZE) {
612 return NULL;
613 }
614 ptr = zone->valloc(zone, size);
615 if (malloc_logger) malloc_logger(MALLOC_LOG_TYPE_ALLOCATE | MALLOC_LOG_TYPE_HAS_ZONE, (uintptr_t)zone, (uintptr_t)size, 0, (uintptr_t)ptr, 0);
616 return ptr;
617 }
618
619 void *
620 malloc_zone_realloc(malloc_zone_t *zone, void *ptr, size_t size) {
621 void *new_ptr;
622 if (malloc_check_start && (malloc_check_counter++ >= malloc_check_start)) {
623 internal_check();
624 }
625 if (size > MALLOC_ABSOLUTE_MAX_SIZE) {
626 return NULL;
627 }
628 new_ptr = zone->realloc(zone, ptr, size);
629 if (malloc_logger) malloc_logger(MALLOC_LOG_TYPE_ALLOCATE | MALLOC_LOG_TYPE_DEALLOCATE | MALLOC_LOG_TYPE_HAS_ZONE, (uintptr_t)zone, (uintptr_t)ptr, (uintptr_t)size, (uintptr_t)new_ptr, 0);
630 return new_ptr;
631 }
632
633 void
634 malloc_zone_free(malloc_zone_t *zone, void *ptr) {
635 if (malloc_logger) malloc_logger(MALLOC_LOG_TYPE_DEALLOCATE | MALLOC_LOG_TYPE_HAS_ZONE, (uintptr_t)zone, (uintptr_t)ptr, 0, 0, 0);
636 if (malloc_check_start && (malloc_check_counter++ >= malloc_check_start)) {
637 internal_check();
638 }
639 zone->free(zone, ptr);
640 }
641
642 static void
643 malloc_zone_free_definite_size(malloc_zone_t *zone, void *ptr, size_t size) {
644 if (malloc_logger) malloc_logger(MALLOC_LOG_TYPE_DEALLOCATE | MALLOC_LOG_TYPE_HAS_ZONE, (uintptr_t)zone, (uintptr_t)ptr, 0, 0, 0);
645 if (malloc_check_start && (malloc_check_counter++ >= malloc_check_start)) {
646 internal_check();
647 }
648 zone->free_definite_size(zone, ptr, size);
649 }
650
651 malloc_zone_t *
652 malloc_zone_from_ptr(const void *ptr) {
653 if (!ptr)
654 return NULL;
655 else
656 return find_registered_zone(ptr, NULL);
657 }
658
659 void *
660 malloc_zone_memalign(malloc_zone_t *zone, size_t alignment, size_t size) {
661 void *ptr;
662 if (zone->version < 5) // Version must be >= 5 to look at the new memalign field.
663 return NULL;
664 if (!(zone->memalign))
665 return NULL;
666 if (malloc_check_start && (malloc_check_counter++ >= malloc_check_start)) {
667 internal_check();
668 }
669 if (size > MALLOC_ABSOLUTE_MAX_SIZE) {
670 return NULL;
671 }
672 if (alignment < sizeof( void *) || // excludes 0 == alignment
673 0 != (alignment & (alignment - 1))) { // relies on sizeof(void *) being a power of two.
674 return NULL;
675 }
676 ptr = zone->memalign(zone, alignment, size);
677 if (malloc_logger) malloc_logger(MALLOC_LOG_TYPE_ALLOCATE | MALLOC_LOG_TYPE_HAS_ZONE, (uintptr_t)zone, (uintptr_t)size, 0, (uintptr_t)ptr, 0);
678 return ptr;
679 }
680
681 /********* Functions for zone implementors ************/
682
683 void
684 malloc_zone_register(malloc_zone_t *zone) {
685 MALLOC_LOCK();
686 malloc_zone_register_while_locked(zone);
687 MALLOC_UNLOCK();
688 }
689
690 void
691 malloc_zone_unregister(malloc_zone_t *z) {
692 unsigned index;
693
694 if (malloc_num_zones == 0)
695 return;
696
697 MALLOC_LOCK();
698 for (index = 0; index < malloc_num_zones; ++index) {
699 if (z != malloc_zones[index])
700 continue;
701
702 // Modify the page to be allow write access, so that we can update the
703 // malloc_zones array.
704 size_t protect_size = malloc_num_zones_allocated * sizeof(malloc_zone_t *);
705 vm_protect(mach_task_self(), (uintptr_t)malloc_zones, protect_size, 0, VM_PROT_READ | VM_PROT_WRITE);
706
707 // If we found a match, swap it with the entry on the back of the list
708 // and null out the back of the list.
709 malloc_zones[index] = malloc_zones[malloc_num_zones - 1];
710 malloc_zones[malloc_num_zones - 1] = NULL;
711 --malloc_num_zones;
712
713 vm_protect(mach_task_self(), (uintptr_t)malloc_zones, protect_size, 0, VM_PROT_READ);
714 MALLOC_UNLOCK();
715 return;
716 }
717 MALLOC_UNLOCK();
718 malloc_printf("*** malloc_zone_unregister() failed for %p\n", z);
719 }
720
721 void
722 malloc_set_zone_name(malloc_zone_t *z, const char *name) {
723 char *newName;
724 if (z->zone_name) {
725 free((char *)z->zone_name);
726 z->zone_name = NULL;
727 }
728 newName = malloc_zone_malloc(z, strlen(name) + 1);
729 strcpy(newName, name);
730 z->zone_name = (const char *)newName;
731 }
732
733 const char *
734 malloc_get_zone_name(malloc_zone_t *zone) {
735 return zone->zone_name;
736 }
737
738 /*
739 * XXX malloc_printf now uses _simple_*printf. It only deals with a
740 * subset of printf format specifiers, but it doesn't call malloc.
741 */
742
743 __private_extern__ void
744 _malloc_vprintf(int flags, const char *format, va_list ap)
745 {
746 _SIMPLE_STRING b;
747
748 if (_malloc_no_asl_log || (flags & MALLOC_PRINTF_NOLOG) || (b = _simple_salloc()) == NULL) {
749 if (!(flags & MALLOC_PRINTF_NOPREFIX)) {
750 if (__is_threaded) {
751 /* XXX somewhat rude 'knowing' that pthread_t is a pointer */
752 _simple_dprintf(malloc_debug_file, "%s(%d,%p) malloc: ", getprogname(), getpid(), (void *)pthread_self());
753 } else {
754 _simple_dprintf(malloc_debug_file, "%s(%d) malloc: ", getprogname(), getpid());
755 }
756 }
757 _simple_vdprintf(malloc_debug_file, format, ap);
758 return;
759 }
760 if (!(flags & MALLOC_PRINTF_NOPREFIX)) {
761 if (__is_threaded) {
762 /* XXX somewhat rude 'knowing' that pthread_t is a pointer */
763 _simple_sprintf(b, "%s(%d,%p) malloc: ", getprogname(), getpid(), (void *)pthread_self());
764 } else {
765 _simple_sprintf(b, "%s(%d) malloc: ", getprogname(), getpid());
766 }
767 }
768 _simple_vsprintf(b, format, ap);
769 _simple_put(b, malloc_debug_file);
770 _simple_asl_log(flags & MALLOC_PRINTF_LEVEL_MASK, Malloc_Facility, _simple_string(b));
771 _simple_sfree(b);
772 }
773
774 __private_extern__ void
775 _malloc_printf(int flags, const char *format, ...)
776 {
777 va_list ap;
778
779 va_start(ap, format);
780 _malloc_vprintf(flags, format, ap);
781 va_end(ap);
782 }
783
784 void
785 malloc_printf(const char *format, ...)
786 {
787 va_list ap;
788
789 va_start(ap, format);
790 _malloc_vprintf(ASL_LEVEL_ERR, format, ap);
791 va_end(ap);
792 }
793
794 /********* Generic ANSI callouts ************/
795
796 void *
797 malloc(size_t size) {
798 void *retval;
799 retval = malloc_zone_malloc(inline_malloc_default_zone(), size);
800 if (retval == NULL) {
801 errno = ENOMEM;
802 }
803 return retval;
804 }
805
806 void *
807 calloc(size_t num_items, size_t size) {
808 void *retval;
809 retval = malloc_zone_calloc(inline_malloc_default_zone(), num_items, size);
810 if (retval == NULL) {
811 errno = ENOMEM;
812 }
813 return retval;
814 }
815
816 void
817 free(void *ptr) {
818 malloc_zone_t *zone;
819 size_t size;
820 if (!ptr)
821 return;
822 zone = find_registered_zone(ptr, &size);
823 if (!zone) {
824 malloc_printf("*** error for object %p: pointer being freed was not allocated\n"
825 "*** set a breakpoint in malloc_error_break to debug\n", ptr);
826 malloc_error_break();
827 if ((malloc_debug_flags & (SCALABLE_MALLOC_ABORT_ON_CORRUPTION|SCALABLE_MALLOC_ABORT_ON_ERROR)))
828 abort();
829 } else if (zone->version >= 6 && zone->free_definite_size)
830 malloc_zone_free_definite_size(zone, ptr, size);
831 else
832 malloc_zone_free(zone, ptr);
833 }
834
835 void *
836 realloc(void *in_ptr, size_t new_size) {
837 void *retval;
838 void *old_ptr;
839 malloc_zone_t *zone;
840 size_t old_size = 0;
841
842 // SUSv3: "If size is 0 and ptr is not a null pointer, the object
843 // pointed to is freed. If the space cannot be allocated, the object
844 // shall remain unchanged." Also "If size is 0, either a null pointer
845 // or a unique pointer that can be successfully passed to free() shall
846 // be returned." We choose to allocate a minimum size object by calling
847 // malloc_zone_malloc with zero size, which matches "If ptr is a null
848 // pointer, realloc() shall be equivalent to malloc() for the specified
849 // size." So we only free the original memory if the allocation succeeds.
850 old_ptr = (new_size == 0) ? NULL : in_ptr;
851 if (!old_ptr) {
852 retval = malloc_zone_malloc(inline_malloc_default_zone(), new_size);
853 } else {
854 zone = find_registered_zone(old_ptr, &old_size);
855 if (zone && old_size >= new_size)
856 return old_ptr;
857
858 if (!zone)
859 zone = inline_malloc_default_zone();
860
861 retval = malloc_zone_realloc(zone, old_ptr, new_size);
862 }
863 if (retval == NULL) {
864 errno = ENOMEM;
865 } else if (new_size == 0) {
866 free(in_ptr);
867 }
868 return retval;
869 }
870
871 void *
872 valloc(size_t size) {
873 void *retval;
874 malloc_zone_t *zone = inline_malloc_default_zone();
875 retval = malloc_zone_valloc(zone, size);
876 if (retval == NULL) {
877 errno = ENOMEM;
878 }
879 return retval;
880 }
881
882 extern void
883 vfree(void *ptr) {
884 free(ptr);
885 }
886
887 size_t
888 malloc_size(const void *ptr) {
889 size_t size = 0;
890
891 if (!ptr)
892 return size;
893
894 (void)find_registered_zone(ptr, &size);
895 return size;
896 }
897
898 size_t
899 malloc_good_size (size_t size) {
900 malloc_zone_t *zone = inline_malloc_default_zone();
901 return zone->introspect->good_size(zone, size);
902 }
903
904 /*
905 * The posix_memalign() function shall allocate size bytes aligned on a boundary specified by alignment,
906 * and shall return a pointer to the allocated memory in memptr.
907 * The value of alignment shall be a multiple of sizeof( void *), that is also a power of two.
908 * Upon successful completion, the value pointed to by memptr shall be a multiple of alignment.
909 *
910 * Upon successful completion, posix_memalign() shall return zero; otherwise,
911 * an error number shall be returned to indicate the error.
912 *
913 * The posix_memalign() function shall fail if:
914 * EINVAL
915 * The value of the alignment parameter is not a power of two multiple of sizeof( void *).
916 * ENOMEM
917 * There is insufficient memory available with the requested alignment.
918 */
919
920 int
921 posix_memalign(void **memptr, size_t alignment, size_t size)
922 {
923 void *retval;
924
925 /* POSIX is silent on NULL == memptr !?! */
926
927 retval = malloc_zone_memalign(inline_malloc_default_zone(), alignment, size);
928 if (retval == NULL) {
929 // To avoid testing the alignment constraints redundantly, we'll rely on the
930 // test made in malloc_zone_memalign to vet each request. Only if that test fails
931 // and returns NULL, do we arrive here to detect the bogus alignment and give the
932 // required EINVAL return.
933 if (alignment < sizeof( void *) || // excludes 0 == alignment
934 0 != (alignment & (alignment - 1))) { // relies on sizeof(void *) being a power of two.
935 return EINVAL;
936 }
937 return ENOMEM;
938 } else {
939 *memptr = retval; // Set iff allocation succeeded
940 return 0;
941 }
942 }
943
944 static malloc_zone_t *
945 find_registered_purgeable_zone(void *ptr) {
946 if (!ptr)
947 return NULL;
948
949 /*
950 * Look for a zone which contains ptr. If that zone does not have the purgeable malloc flag
951 * set, or the allocation is too small, do nothing. Otherwise, set the allocation volatile.
952 * FIXME: for performance reasons, we should probably keep a separate list of purgeable zones
953 * and only search those.
954 */
955 size_t size = 0;
956 malloc_zone_t *zone = find_registered_zone(ptr, &size);
957
958 /* FIXME: would really like a zone->introspect->flags->purgeable check, but haven't determined
959 * binary compatibility impact of changing the introspect struct yet. */
960 if (!zone)
961 return NULL;
962
963 /* Check to make sure pointer is page aligned and size is multiple of page size */
964 if ((size < vm_page_size) || ((size % vm_page_size) != 0))
965 return NULL;
966
967 return zone;
968 }
969
970 void
971 malloc_make_purgeable(void *ptr) {
972 malloc_zone_t *zone = find_registered_purgeable_zone(ptr);
973 if (!zone)
974 return;
975
976 int state = VM_PURGABLE_VOLATILE;
977 vm_purgable_control(mach_task_self(), (vm_address_t)ptr, VM_PURGABLE_SET_STATE, &state);
978 return;
979 }
980
981 /* Returns true if ptr is valid. Ignore the return value from vm_purgeable_control and only report
982 * state. */
983 int
984 malloc_make_nonpurgeable(void *ptr) {
985 malloc_zone_t *zone = find_registered_purgeable_zone(ptr);
986 if (!zone)
987 return 0;
988
989 int state = VM_PURGABLE_NONVOLATILE;
990 vm_purgable_control(mach_task_self(), (vm_address_t)ptr, VM_PURGABLE_SET_STATE, &state);
991
992 if (state == VM_PURGABLE_EMPTY)
993 return EFAULT;
994
995 return 0;
996 }
997
998 /********* Batch methods ************/
999
1000 unsigned
1001 malloc_zone_batch_malloc(malloc_zone_t *zone, size_t size, void **results, unsigned num_requested) {
1002 unsigned (*batch_malloc)(malloc_zone_t *, size_t, void **, unsigned) = zone-> batch_malloc;
1003 if (! batch_malloc) return 0;
1004 if (malloc_check_start && (malloc_check_counter++ >= malloc_check_start)) {
1005 internal_check();
1006 }
1007 unsigned batched = batch_malloc(zone, size, results, num_requested);
1008 if (malloc_logger) {
1009 unsigned index = 0;
1010 while (index < batched) {
1011 malloc_logger(MALLOC_LOG_TYPE_ALLOCATE | MALLOC_LOG_TYPE_HAS_ZONE, (uintptr_t)zone, (uintptr_t)size, 0, (uintptr_t)results[index], 0);
1012 index++;
1013 }
1014 }
1015 return batched;
1016 }
1017
1018 void
1019 malloc_zone_batch_free(malloc_zone_t *zone, void **to_be_freed, unsigned num) {
1020 if (malloc_check_start && (malloc_check_counter++ >= malloc_check_start)) {
1021 internal_check();
1022 }
1023 if (malloc_logger) {
1024 unsigned index = 0;
1025 while (index < num) {
1026 malloc_logger(MALLOC_LOG_TYPE_DEALLOCATE | MALLOC_LOG_TYPE_HAS_ZONE, (uintptr_t)zone, (uintptr_t)to_be_freed[index], 0, 0, 0);
1027 index++;
1028 }
1029 }
1030 void (*batch_free)(malloc_zone_t *, void **, unsigned) = zone-> batch_free;
1031 if (batch_free) {
1032 batch_free(zone, to_be_freed, num);
1033 } else {
1034 void (*free_fun)(malloc_zone_t *, void *) = zone->free;
1035 while (num--) {
1036 void *ptr = *to_be_freed++;
1037 free_fun(zone, ptr);
1038 }
1039 }
1040 }
1041
1042 /********* Functions for performance tools ************/
1043
1044 static kern_return_t
1045 _malloc_default_reader(task_t task, vm_address_t address, vm_size_t size, void **ptr) {
1046 *ptr = (void *)address;
1047 return 0;
1048 }
1049
1050 kern_return_t
1051 malloc_get_all_zones(task_t task, memory_reader_t reader, vm_address_t **addresses, unsigned *count) {
1052 // 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 )
1053 vm_address_t remote_malloc_zones = (vm_address_t)&malloc_zones;
1054 vm_address_t remote_malloc_num_zones = (vm_address_t)&malloc_num_zones;
1055 kern_return_t err;
1056 vm_address_t zones_address;
1057 vm_address_t *zones_address_ref;
1058 unsigned num_zones;
1059 unsigned *num_zones_ref;
1060 if (!reader) reader = _malloc_default_reader;
1061 // printf("Read malloc_zones at address %p should be %p\n", &malloc_zones, malloc_zones);
1062 err = reader(task, remote_malloc_zones, sizeof(void *), (void **)&zones_address_ref);
1063 // printf("Read malloc_zones[%p]=%p\n", remote_malloc_zones, *zones_address_ref);
1064 if (err) {
1065 malloc_printf("*** malloc_get_all_zones: error reading zones_address at %p\n", (unsigned)remote_malloc_zones);
1066 return err;
1067 }
1068 zones_address = *zones_address_ref;
1069 // printf("Reading num_zones at address %p\n", remote_malloc_num_zones);
1070 err = reader(task, remote_malloc_num_zones, sizeof(unsigned), (void **)&num_zones_ref);
1071 if (err) {
1072 malloc_printf("*** malloc_get_all_zones: error reading num_zones at %p\n", (unsigned)remote_malloc_num_zones);
1073 return err;
1074 }
1075 num_zones = *num_zones_ref;
1076 // printf("Read malloc_num_zones[%p]=%d\n", remote_malloc_num_zones, num_zones);
1077 *count = num_zones;
1078 // printf("malloc_get_all_zones succesfully found %d zones\n", num_zones);
1079 err = reader(task, zones_address, sizeof(malloc_zone_t *) * num_zones, (void **)addresses);
1080 if (err) {
1081 malloc_printf("*** malloc_get_all_zones: error reading zones at %p\n", &zones_address);
1082 return err;
1083 }
1084 // printf("malloc_get_all_zones succesfully read %d zones\n", num_zones);
1085 return err;
1086 }
1087
1088 /********* Debug helpers ************/
1089
1090 void
1091 malloc_zone_print_ptr_info(void *ptr) {
1092 malloc_zone_t *zone;
1093 if (!ptr) return;
1094 zone = malloc_zone_from_ptr(ptr);
1095 if (zone) {
1096 printf("ptr %p in registered zone %p\n", ptr, zone);
1097 } else {
1098 printf("ptr %p not in heap\n", ptr);
1099 }
1100 }
1101
1102 boolean_t
1103 malloc_zone_check(malloc_zone_t *zone) {
1104 boolean_t ok = 1;
1105 if (!zone) {
1106 unsigned index = 0;
1107 while (index < malloc_num_zones) {
1108 zone = malloc_zones[index++];
1109 if (!zone->introspect->check(zone)) ok = 0;
1110 }
1111 } else {
1112 ok = zone->introspect->check(zone);
1113 }
1114 return ok;
1115 }
1116
1117 void
1118 malloc_zone_print(malloc_zone_t *zone, boolean_t verbose) {
1119 if (!zone) {
1120 unsigned index = 0;
1121 while (index < malloc_num_zones) {
1122 zone = malloc_zones[index++];
1123 zone->introspect->print(zone, verbose);
1124 }
1125 } else {
1126 zone->introspect->print(zone, verbose);
1127 }
1128 }
1129
1130 void
1131 malloc_zone_statistics(malloc_zone_t *zone, malloc_statistics_t *stats) {
1132 if (!zone) {
1133 memset(stats, 0, sizeof(*stats));
1134 unsigned index = 0;
1135 while (index < malloc_num_zones) {
1136 zone = malloc_zones[index++];
1137 malloc_statistics_t this_stats;
1138 zone->introspect->statistics(zone, &this_stats);
1139 stats->blocks_in_use += this_stats.blocks_in_use;
1140 stats->size_in_use += this_stats.size_in_use;
1141 stats->max_size_in_use += this_stats.max_size_in_use;
1142 stats->size_allocated += this_stats.size_allocated;
1143 }
1144 } else {
1145 zone->introspect->statistics(zone, stats);
1146 }
1147 }
1148
1149 void
1150 malloc_zone_log(malloc_zone_t *zone, void *address) {
1151 if (!zone) {
1152 unsigned index = 0;
1153 while (index < malloc_num_zones) {
1154 zone = malloc_zones[index++];
1155 zone->introspect->log(zone, address);
1156 }
1157 } else {
1158 zone->introspect->log(zone, address);
1159 }
1160 }
1161
1162 /********* Misc other entry points ************/
1163
1164 static void
1165 DefaultMallocError(int x) {
1166 #if USE_SLEEP_RATHER_THAN_ABORT
1167 malloc_printf("*** error %d\n", x);
1168 sleep(3600);
1169 #else
1170 _SIMPLE_STRING b = _simple_salloc();
1171 if (b) {
1172 _simple_sprintf(b, "*** error %d", x);
1173 malloc_printf("%s\n", _simple_string(b));
1174 __crashreporter_info__ = _simple_string(b);
1175 } else {
1176 _malloc_printf(MALLOC_PRINTF_NOLOG, "*** error %d", x);
1177 __crashreporter_info__ = "*** DefaultMallocError called";
1178 }
1179 abort();
1180 #endif
1181 }
1182
1183 void (*
1184 malloc_error(void (*func)(int)))(int) {
1185 return DefaultMallocError;
1186 }
1187
1188 /* Stack logging fork-handling prototypes */
1189 extern void __stack_logging_fork_prepare();
1190 extern void __stack_logging_fork_parent();
1191 extern void __stack_logging_fork_child();
1192
1193 void
1194 _malloc_fork_prepare() {
1195 /* Prepare the malloc module for a fork by insuring that no thread is in a malloc critical section */
1196 unsigned index = 0;
1197 MALLOC_LOCK();
1198 while (index < malloc_num_zones) {
1199 malloc_zone_t *zone = malloc_zones[index++];
1200 zone->introspect->force_lock(zone);
1201 }
1202 __stack_logging_fork_prepare();
1203 }
1204
1205 void
1206 _malloc_fork_parent() {
1207 /* Called in the parent process after a fork() to resume normal operation. */
1208 unsigned index = 0;
1209 __stack_logging_fork_parent();
1210 MALLOC_UNLOCK();
1211 while (index < malloc_num_zones) {
1212 malloc_zone_t *zone = malloc_zones[index++];
1213 zone->introspect->force_unlock(zone);
1214 }
1215 }
1216
1217 void
1218 _malloc_fork_child() {
1219 /* 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. */
1220 unsigned index = 0;
1221 __stack_logging_fork_child();
1222 MALLOC_UNLOCK();
1223 while (index < malloc_num_zones) {
1224 malloc_zone_t *zone = malloc_zones[index++];
1225 zone->introspect->force_unlock(zone);
1226 }
1227 }
1228
1229 /*
1230 * A Glibc-like mstats() interface.
1231 *
1232 * Note that this interface really isn't very good, as it doesn't understand
1233 * that we may have multiple allocators running at once. We just massage
1234 * the result from malloc_zone_statistics in any case.
1235 */
1236 struct mstats
1237 mstats(void)
1238 {
1239 malloc_statistics_t s;
1240 struct mstats m;
1241
1242 malloc_zone_statistics(NULL, &s);
1243 m.bytes_total = s.size_allocated;
1244 m.chunks_used = s.blocks_in_use;
1245 m.bytes_used = s.size_in_use;
1246 m.chunks_free = 0;
1247 m.bytes_free = m.bytes_total - m.bytes_used; /* isn't this somewhat obvious? */
1248
1249 return(m);
1250 }
1251
1252 /***************** OBSOLETE ENTRY POINTS ********************/
1253
1254 #if PHASE_OUT_OLD_MALLOC
1255 #error PHASE OUT THE FOLLOWING FUNCTIONS
1256 #else
1257 #warning PHASE OUT THE FOLLOWING FUNCTIONS
1258 #endif
1259
1260 void
1261 set_malloc_singlethreaded(boolean_t single) {
1262 static boolean_t warned = 0;
1263 if (!warned) {
1264 #if PHASE_OUT_OLD_MALLOC
1265 malloc_printf("*** OBSOLETE: set_malloc_singlethreaded(%d)\n", single);
1266 #endif
1267 warned = 1;
1268 }
1269 }
1270
1271 void
1272 malloc_singlethreaded() {
1273 static boolean_t warned = 0;
1274 if (!warned) {
1275 malloc_printf("*** OBSOLETE: malloc_singlethreaded()\n");
1276 warned = 1;
1277 }
1278 }
1279
1280 int
1281 malloc_debug(int level) {
1282 malloc_printf("*** OBSOLETE: malloc_debug()\n");
1283 return 0;
1284 }