2 * Copyright (c) 1999, 2006-2008 Apple Inc. All rights reserved.
4 * @APPLE_LICENSE_HEADER_START@
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
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.
21 * @APPLE_LICENSE_HEADER_END@
24 #include <pthread_internals.h>
25 #include "magmallocProvider.h"
26 #include <mach-o/dyld.h> /* for NSVersionOfLinkTimeLibrary() */
32 #import <malloc/malloc.h>
34 #import <crt_externs.h>
36 #import <pthread_internals.h>
39 #import <mach/mach_vm.h>
40 #import <mach/mach_init.h>
43 #import "scalable_malloc.h"
44 #import "stack_logging.h"
45 #import "malloc_printf.h"
47 #import "CrashReporterClient.h"
50 * MALLOC_ABSOLUTE_MAX_SIZE - There are many instances of addition to a
51 * user-specified size_t, which can cause overflow (and subsequent crashes)
52 * for values near SIZE_T_MAX. Rather than add extra "if" checks everywhere
53 * this occurs, it is easier to just set an absolute maximum request size,
54 * and immediately return an error if the requested size exceeds this maximum.
55 * Of course, values less than this absolute max can fail later if the value
56 * is still too large for the available memory. The largest value added
57 * seems to be PAGE_SIZE (in the macro round_page()), so to be safe, we set
58 * the maximum to be 2 * PAGE_SIZE less than SIZE_T_MAX.
60 #define MALLOC_ABSOLUTE_MAX_SIZE (SIZE_T_MAX - (2 * PAGE_SIZE))
62 #define USE_SLEEP_RATHER_THAN_ABORT 0
64 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
);
66 __private_extern__ pthread_lock_t _malloc_lock
= 0; // initialized in __libc_init
68 /* The following variables are exported for the benefit of performance tools
70 * It should always be safe to first read malloc_num_zones, then read
71 * malloc_zones without taking the lock, if only iteration is required and
72 * provided that when malloc_destroy_zone is called all prior operations on that
73 * zone are complete and no further calls referencing that zone can be made.
75 unsigned malloc_num_zones
= 0;
76 unsigned malloc_num_zones_allocated
= 0;
77 malloc_zone_t
**malloc_zones
= 0;
78 malloc_logger_t
*malloc_logger
= NULL
;
80 unsigned malloc_debug_flags
= 0;
82 unsigned malloc_check_start
= 0; // 0 means don't check
83 unsigned malloc_check_counter
= 0;
84 unsigned malloc_check_each
= 1000;
86 /* global flag to suppress ASL logging e.g. for syslogd */
87 int _malloc_no_asl_log
= 0;
89 static int malloc_check_sleep
= 100; // default 100 second sleep
90 static int malloc_check_abort
= 0; // default is to sleep, not abort
92 static int malloc_debug_file
= STDERR_FILENO
;
94 * State indicated by malloc_def_zone_state
95 * 0 - the default zone has not yet been created
96 * 1 - a Malloc* environment variable has been set
97 * 2 - the default zone has been created and an environment variable scan done
98 * 3 - a new default zone has been created and another environment variable scan
100 __private_extern__
int malloc_def_zone_state
= 0;
102 static const char Malloc_Facility
[] = "com.apple.Libsystem.malloc";
104 #define MALLOC_LOCK() LOCK(_malloc_lock)
105 #define MALLOC_UNLOCK() UNLOCK(_malloc_lock)
108 * Counters that coordinate zone destruction (in malloc_zone_unregister) with
109 * find_registered_zone (here abbreviated as FRZ).
111 static int counterAlice
= 0, counterBob
= 0;
112 static int *pFRZCounterLive
= &counterAlice
, *pFRZCounterDrain
= &counterBob
;
114 #define MALLOC_LOG_TYPE_ALLOCATE stack_logging_type_alloc
115 #define MALLOC_LOG_TYPE_DEALLOCATE stack_logging_type_dealloc
116 #define MALLOC_LOG_TYPE_HAS_ZONE stack_logging_flag_zone
117 #define MALLOC_LOG_TYPE_CLEARED stack_logging_flag_cleared
119 /********* Utilities ************/
120 __private_extern__
uint64_t malloc_entropy
[2] = {0, 0};
122 void __malloc_entropy_setup(const char *apple
[]) __attribute__ ((visibility ("hidden")));
125 __entropy_from_kernel(const char *str
)
127 unsigned long long val
;
131 /* Skip over key to the first value */
132 str
= strchr(str
, '=');
137 while (str
&& idx
< sizeof(malloc_entropy
)/sizeof(malloc_entropy
[0])) {
138 strlcpy(tmp
, str
, 20);
139 p
= strchr(tmp
, ',');
141 val
= strtoull(tmp
, NULL
, 0);
142 malloc_entropy
[idx
] = (uint64_t)val
;
144 if ((str
= strchr(str
, ',')) != NULL
)
151 __malloc_entropy_setup(const char *apple
[])
154 for (p
= apple
; p
&& *p
; p
++) {
155 if (strstr(*p
, "malloc_entropy") == *p
) {
156 if (sizeof(malloc_entropy
)/sizeof(malloc_entropy
[0]) == __entropy_from_kernel(*p
))
163 malloc_entropy
[0] = ((uint64_t)arc4random()) << 32 | ((uint64_t)arc4random());
164 malloc_entropy
[1] = ((uint64_t)arc4random()) << 32 | ((uint64_t)arc4random());
168 static inline malloc_zone_t
* find_registered_zone(const void *, size_t *) __attribute__((always_inline
));
169 static inline malloc_zone_t
*
170 find_registered_zone(const void *ptr
, size_t *returned_size
) {
171 // Returns a zone which contains ptr, else NULL
173 if (0 == malloc_num_zones
) {
174 if (returned_size
) *returned_size
= 0;
178 // The default zone is registered in malloc_zones[0]. There's no danger that it will ever be unregistered.
179 // So don't advance the FRZ counter yet.
180 malloc_zone_t
*zone
= malloc_zones
[0];
181 size_t size
= zone
->size(zone
, ptr
);
182 if (size
) { // Claimed by this zone?
183 if (returned_size
) *returned_size
= size
;
187 int *pFRZCounter
= pFRZCounterLive
; // Capture pointer to the counter of the moment
188 __sync_fetch_and_add(pFRZCounter
, 1); // Advance this counter -- our thread is in FRZ
191 unsigned limit
= malloc_num_zones
;
192 malloc_zone_t
**zones
= &malloc_zones
[1];
194 for (index
= 1; index
< limit
; ++index
, ++zones
) {
196 size
= zone
->size(zone
, ptr
);
197 if (size
) { // Claimed by this zone?
198 if (returned_size
) *returned_size
= size
;
199 __sync_fetch_and_sub(pFRZCounter
, 1); // our thread is leaving FRZ
203 // Unclaimed by any zone.
204 if (returned_size
) *returned_size
= 0;
205 __sync_fetch_and_sub(pFRZCounter
, 1); // our thread is leaving FRZ
209 __private_extern__
__attribute__((noinline
)) void
210 malloc_error_break(void) {
211 // Provides a non-inlined place for various malloc error procedures to call
212 // that will be called after an error message appears. It does not make
213 // sense for developers to call this function, so it is marked
214 // __private_extern__ to prevent it from becoming API.
215 MAGMALLOC_MALLOCERRORBREAK(); // DTrace USDT probe
218 __private_extern__ boolean_t
__stack_logging_locked();
220 __private_extern__
__attribute__((noinline
)) __attribute__((used
)) int
221 malloc_gdb_po_unsafe(void) {
222 // In order to implement "po" other data formatters in gdb, the debugger
223 // calls functions that call malloc. The debugger will only run one thread
224 // of the program in this case, so if another thread is holding a zone lock,
225 // gdb may deadlock in this case.
227 // Iterate over the zones in malloc_zones, and call "trylock" on the zone
228 // lock. If trylock succeeds, unlock it, otherwise return "locked". Returns
229 // 0 == safe, 1 == locked/unsafe.
231 if (__stack_logging_locked())
234 malloc_zone_t
**zones
= malloc_zones
;
235 unsigned i
, e
= malloc_num_zones
;
237 for (i
= 0; i
!= e
; ++i
) {
238 malloc_zone_t
*zone
= zones
[i
];
240 // Version must be >= 5 to look at the new introspection field.
241 if (zone
->version
< 5)
244 if (zone
->introspect
->zone_locked
&& zone
->introspect
->zone_locked(zone
))
250 /********* Creation and destruction ************/
252 static void set_flags_from_environment(void);
255 malloc_zone_register_while_locked(malloc_zone_t
*zone
) {
259 /* scan the list of zones, to see if this zone is already registered. If
260 * so, print an error message and return. */
261 for (i
= 0; i
!= malloc_num_zones
; ++i
)
262 if (zone
== malloc_zones
[i
]) {
263 _malloc_printf(ASL_LEVEL_ERR
, "Attempted to register zone more than once: %p\n", zone
);
267 if (malloc_num_zones
== malloc_num_zones_allocated
) {
268 size_t malloc_zones_size
= malloc_num_zones
* sizeof(malloc_zone_t
*);
269 size_t alloc_size
= malloc_zones_size
+ vm_page_size
;
271 malloc_zone_t
**new_zones
= mmap(0, alloc_size
, PROT_READ
| PROT_WRITE
, MAP_ANON
| MAP_PRIVATE
, VM_MAKE_TAG(VM_MEMORY_MALLOC
), 0);
273 /* If there were previously allocated malloc zones, we need to copy them
274 * out of the previous array and into the new zones array */
276 memcpy(new_zones
, malloc_zones
, malloc_zones_size
);
278 /* Update the malloc_zones pointer, which we leak if it was previously
279 * allocated, and the number of zones allocated */
280 protect_size
= alloc_size
;
281 malloc_zones
= new_zones
;
282 malloc_num_zones_allocated
= alloc_size
/ sizeof(malloc_zone_t
*);
284 /* If we don't need to reallocate zones, we need to briefly change the
285 * page protection the malloc zones to allow writes */
286 protect_size
= malloc_num_zones_allocated
* sizeof(malloc_zone_t
*);
287 mprotect(malloc_zones
, protect_size
, PROT_READ
| PROT_WRITE
);
289 malloc_zones
[malloc_num_zones
++] = zone
;
291 /* Finally, now that the zone is registered, disallow write access to the
292 * malloc_zones array */
293 mprotect(malloc_zones
, protect_size
, PROT_READ
);
294 //_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);
298 _malloc_initialize(void) {
300 if (malloc_def_zone_state
< 2) {
304 malloc_def_zone_state
+= 2;
305 set_flags_from_environment(); // will only set flags up to two times
306 n
= malloc_num_zones
;
307 zone
= create_scalable_zone(0, malloc_debug_flags
);
308 malloc_zone_register_while_locked(zone
);
309 malloc_set_zone_name(zone
, "DefaultMallocZone");
310 if (n
!= 0) { // make the default first, for efficiency
311 unsigned protect_size
= malloc_num_zones_allocated
* sizeof(malloc_zone_t
*);
312 malloc_zone_t
*hold
= malloc_zones
[0];
314 if(hold
->zone_name
&& strcmp(hold
->zone_name
, "DefaultMallocZone") == 0) {
315 malloc_set_zone_name(hold
, NULL
);
318 mprotect(malloc_zones
, protect_size
, PROT_READ
| PROT_WRITE
);
319 malloc_zones
[0] = malloc_zones
[n
];
320 malloc_zones
[n
] = hold
;
321 mprotect(malloc_zones
, protect_size
, PROT_READ
);
323 // _malloc_printf(ASL_LEVEL_INFO, "%d registered zones\n", malloc_num_zones);
324 // _malloc_printf(ASL_LEVEL_INFO, "malloc_zones is at %p; malloc_num_zones is at %p\n", (unsigned)&malloc_zones, (unsigned)&malloc_num_zones);
329 static inline malloc_zone_t
*inline_malloc_default_zone(void) __attribute__((always_inline
));
330 static inline malloc_zone_t
*
331 inline_malloc_default_zone(void) {
332 if (malloc_def_zone_state
< 2) _malloc_initialize();
333 // _malloc_printf(ASL_LEVEL_INFO, "In inline_malloc_default_zone with %d %d\n", malloc_num_zones, malloc_has_debug_zone);
334 return malloc_zones
[0];
338 malloc_default_zone(void) {
339 return inline_malloc_default_zone();
342 static inline malloc_zone_t
*inline_malloc_default_scalable_zone(void) __attribute__((always_inline
));
343 static inline malloc_zone_t
*
344 inline_malloc_default_scalable_zone(void) {
347 if (malloc_def_zone_state
< 2) _malloc_initialize();
348 // _malloc_printf(ASL_LEVEL_INFO, "In inline_malloc_default_scalable_zone with %d %d\n", malloc_num_zones, malloc_has_debug_zone);
351 for (index
= 0; index
< malloc_num_zones
; ++index
) {
352 malloc_zone_t
*z
= malloc_zones
[index
];
354 if(z
->zone_name
&& strcmp(z
->zone_name
, "DefaultMallocZone") == 0) {
361 malloc_printf("*** malloc_default_scalable_zone() failed to find 'DefaultMallocZone'\n");
362 return NULL
; // FIXME: abort() instead?
366 malloc_default_purgeable_zone(void) {
367 static malloc_zone_t
*dpz
;
371 // PR_7288598: Must pass a *scalable* zone (szone) as the helper for create_purgeable_zone().
372 // Take care that the zone so obtained is not subject to interposing.
374 malloc_zone_t
*tmp
= create_purgeable_zone(0, inline_malloc_default_scalable_zone(), malloc_debug_flags
);
375 malloc_zone_register(tmp
);
376 malloc_set_zone_name(tmp
, "DefaultPurgeableMallocZone");
377 if (!__sync_bool_compare_and_swap(&dpz
, NULL
, tmp
))
378 malloc_destroy_zone(tmp
);
383 // For debugging, allow stack logging to both memory and disk to compare their results.
385 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
)
387 __disk_stack_logging_log_stack(type_flags
, zone_ptr
, size
, ptr_arg
, return_val
, num_hot_to_skip
);
388 stack_logging_log_stack(type_flags
, zone_ptr
, size
, ptr_arg
, return_val
, num_hot_to_skip
);
392 set_flags_from_environment(void) {
395 char **env
= * _NSGetEnviron();
399 if (malloc_debug_file
!= STDERR_FILENO
) {
400 close(malloc_debug_file
);
401 malloc_debug_file
= STDERR_FILENO
;
404 malloc_debug_flags
= SCALABLE_MALLOC_ABORT_ON_CORRUPTION
; // Set always on 64-bit processes
406 int libSystemVersion
= NSVersionOfLinkTimeLibrary("System");
407 if ((-1 != libSystemVersion
) && ((libSystemVersion
>> 16) < 126) /* Lion or greater */)
408 malloc_debug_flags
= 0;
410 malloc_debug_flags
= SCALABLE_MALLOC_ABORT_ON_CORRUPTION
;
412 stack_logging_enable_logging
= 0;
413 stack_logging_dontcompact
= 0;
414 malloc_logger
= NULL
;
415 malloc_check_start
= 0;
416 malloc_check_each
= 1000;
417 malloc_check_abort
= 0;
418 malloc_check_sleep
= 100;
420 * Given that all environment variables start with "Malloc" we optimize by scanning quickly
421 * first the environment, therefore avoiding repeated calls to getenv().
422 * If we are setu/gid these flags are ignored to prevent a malicious invoker from changing
425 for (p
= env
; (c
= *p
) != NULL
; ++p
) {
426 if (!strncmp(c
, "Malloc", 6)) {
434 flag
= getenv("MallocLogFile");
436 fd
= open(flag
, O_WRONLY
|O_APPEND
|O_CREAT
, 0644);
438 malloc_debug_file
= fd
;
439 fcntl(fd
, F_SETFD
, 0); // clear close-on-exec flag XXX why?
441 malloc_printf("Could not open %s, using stderr\n", flag
);
444 if (getenv("MallocGuardEdges")) {
445 malloc_debug_flags
|= SCALABLE_MALLOC_ADD_GUARD_PAGES
;
446 _malloc_printf(ASL_LEVEL_INFO
, "protecting edges\n");
447 if (getenv("MallocDoNotProtectPrelude")) {
448 malloc_debug_flags
|= SCALABLE_MALLOC_DONT_PROTECT_PRELUDE
;
449 _malloc_printf(ASL_LEVEL_INFO
, "... but not protecting prelude guard page\n");
451 if (getenv("MallocDoNotProtectPostlude")) {
452 malloc_debug_flags
|= SCALABLE_MALLOC_DONT_PROTECT_POSTLUDE
;
453 _malloc_printf(ASL_LEVEL_INFO
, "... but not protecting postlude guard page\n");
456 flag
= getenv("MallocStackLogging");
458 flag
= getenv("MallocStackLoggingNoCompact");
459 stack_logging_dontcompact
= 1;
461 // For debugging, the MallocStackLogging or MallocStackLoggingNoCompact environment variables can be set to
462 // values of "memory", "disk", or "both" to control which stack logging mechanism to use. Those strings appear
463 // in the flag variable, and the strtoul() call below will return 0, so then we can do string comparison on the
464 // value of flag. The default stack logging now is disk stack logging, since memory stack logging is not 64-bit-aware.
466 unsigned long val
= strtoul(flag
, NULL
, 0);
467 if (val
== 1) val
= 0;
468 if (val
== -1) val
= 0;
470 malloc_logger
= (void *)val
;
471 _malloc_printf(ASL_LEVEL_INFO
, "recording stacks using recorder %p\n", malloc_logger
);
472 } else if (strcmp(flag
,"memory") == 0) {
473 malloc_logger
= (malloc_logger_t
*)stack_logging_log_stack
;
474 _malloc_printf(ASL_LEVEL_INFO
, "recording malloc stacks in memory using standard recorder\n");
475 } else if (strcmp(flag
,"both") == 0) {
476 malloc_logger
= stack_logging_log_stack_debug
;
477 _malloc_printf(ASL_LEVEL_INFO
, "recording malloc stacks to both memory and disk for comparison debugging\n");
478 } else { // the default is to log to disk
479 malloc_logger
= __disk_stack_logging_log_stack
;
480 _malloc_printf(ASL_LEVEL_INFO
, "recording malloc stacks to disk using standard recorder\n");
482 stack_logging_enable_logging
= 1;
483 if (stack_logging_dontcompact
) {
484 if (malloc_logger
== __disk_stack_logging_log_stack
) {
485 _malloc_printf(ASL_LEVEL_INFO
, "stack logging compaction turned off; size of log files on disk can increase rapidly\n");
487 _malloc_printf(ASL_LEVEL_INFO
, "stack logging compaction turned off; VM can increase rapidly\n");
491 if (getenv("MallocScribble")) {
492 malloc_debug_flags
|= SCALABLE_MALLOC_DO_SCRIBBLE
;
493 _malloc_printf(ASL_LEVEL_INFO
, "enabling scribbling to detect mods to free blocks\n");
495 if (getenv("MallocErrorAbort")) {
496 malloc_debug_flags
|= SCALABLE_MALLOC_ABORT_ON_ERROR
;
497 _malloc_printf(ASL_LEVEL_INFO
, "enabling abort() on bad malloc or free\n");
500 /* initialization above forces SCALABLE_MALLOC_ABORT_ON_CORRUPTION of 64-bit processes */
502 flag
= getenv("MallocCorruptionAbort");
503 if (flag
&& (flag
[0] == '0')) { // Set from an environment variable in 32-bit processes
504 malloc_debug_flags
&= ~SCALABLE_MALLOC_ABORT_ON_CORRUPTION
;
506 malloc_debug_flags
|= SCALABLE_MALLOC_ABORT_ON_CORRUPTION
;
509 flag
= getenv("MallocCheckHeapStart");
511 malloc_check_start
= strtoul(flag
, NULL
, 0);
512 if (malloc_check_start
== 0) malloc_check_start
= 1;
513 if (malloc_check_start
== -1) malloc_check_start
= 1;
514 flag
= getenv("MallocCheckHeapEach");
516 malloc_check_each
= strtoul(flag
, NULL
, 0);
517 if (malloc_check_each
== 0) malloc_check_each
= 1;
518 if (malloc_check_each
== -1) malloc_check_each
= 1;
520 _malloc_printf(ASL_LEVEL_INFO
, "checks heap after %dth operation and each %d operations\n", malloc_check_start
, malloc_check_each
);
521 flag
= getenv("MallocCheckHeapAbort");
523 malloc_check_abort
= strtol(flag
, NULL
, 0);
524 if (malloc_check_abort
)
525 _malloc_printf(ASL_LEVEL_INFO
, "will abort on heap corruption\n");
527 flag
= getenv("MallocCheckHeapSleep");
529 malloc_check_sleep
= strtol(flag
, NULL
, 0);
530 if (malloc_check_sleep
> 0)
531 _malloc_printf(ASL_LEVEL_INFO
, "will sleep for %d seconds on heap corruption\n", malloc_check_sleep
);
532 else if (malloc_check_sleep
< 0)
533 _malloc_printf(ASL_LEVEL_INFO
, "will sleep once for %d seconds on heap corruption\n", -malloc_check_sleep
);
535 _malloc_printf(ASL_LEVEL_INFO
, "no sleep on heap corruption\n");
538 if (getenv("MallocHelp")) {
539 _malloc_printf(ASL_LEVEL_INFO
,
540 "environment variables that can be set for debug:\n"
541 "- MallocLogFile <f> to create/append messages to file <f> instead of stderr\n"
542 "- MallocGuardEdges to add 2 guard pages for each large block\n"
543 "- MallocDoNotProtectPrelude to disable protection (when previous flag set)\n"
544 "- MallocDoNotProtectPostlude to disable protection (when previous flag set)\n"
545 "- MallocStackLogging to record all stacks. Tools like leaks can then be applied\n"
546 "- MallocStackLoggingNoCompact to record all stacks. Needed for malloc_history\n"
547 "- MallocStackLoggingDirectory to set location of stack logs, which can grow large; default is /tmp\n"
548 "- MallocScribble to detect writing on free blocks and missing initializers:\n"
549 " 0x55 is written upon free and 0xaa is written on allocation\n"
550 "- MallocCheckHeapStart <n> to start checking the heap after <n> operations\n"
551 "- MallocCheckHeapEach <s> to repeat the checking of the heap after <s> operations\n"
552 "- MallocCheckHeapSleep <t> to sleep <t> seconds on heap corruption\n"
553 "- MallocCheckHeapAbort <b> to abort on heap corruption if <b> is non-zero\n"
554 "- MallocCorruptionAbort to abort on malloc errors, but not on out of memory for 32-bit processes\n"
555 " MallocCorruptionAbort is always set on 64-bit processes\n"
556 "- MallocErrorAbort to abort on any malloc error, including out of memory\n"
557 "- MallocHelp - this help!\n");
562 malloc_create_zone(vm_size_t start_size
, unsigned flags
)
566 /* start_size doesn't seemed to actually be used, but we test anyways */
567 if (start_size
> MALLOC_ABSOLUTE_MAX_SIZE
) {
570 if (malloc_def_zone_state
< 2) _malloc_initialize();
571 zone
= create_scalable_zone(start_size
, flags
| malloc_debug_flags
);
572 malloc_zone_register(zone
);
577 * For use by CheckFix: establish a new default zone whose behavior is, apart from
578 * the use of death-row and per-CPU magazines, that of Leopard.
581 malloc_create_legacy_default_zone(void)
586 if (malloc_def_zone_state
< 2) _malloc_initialize();
587 zone
= create_legacy_scalable_zone(0, malloc_debug_flags
);
590 malloc_zone_register_while_locked(zone
);
593 // Establish the legacy scalable zone just created as the default zone.
595 malloc_zone_t
*hold
= malloc_zones
[0];
596 if(hold
->zone_name
&& strcmp(hold
->zone_name
, "DefaultMallocZone") == 0) {
597 malloc_set_zone_name(hold
, NULL
);
599 malloc_set_zone_name(zone
, "DefaultMallocZone");
601 unsigned protect_size
= malloc_num_zones_allocated
* sizeof(malloc_zone_t
*);
602 mprotect(malloc_zones
, protect_size
, PROT_READ
| PROT_WRITE
);
604 // assert(zone == malloc_zones[malloc_num_zones - 1];
605 for (i
= malloc_num_zones
- 1; i
> 0; --i
) {
606 malloc_zones
[i
] = malloc_zones
[i
- 1];
608 malloc_zones
[0] = zone
;
610 mprotect(malloc_zones
, protect_size
, PROT_READ
);
615 malloc_destroy_zone(malloc_zone_t
*zone
) {
616 malloc_set_zone_name(zone
, NULL
); // Deallocate zone name wherever it may reside PR_7701095
617 malloc_zone_unregister(zone
);
621 /********* Block creation and manipulation ************/
624 internal_check(void) {
625 static vm_address_t
*frames
= NULL
;
626 static unsigned num_frames
;
627 if (malloc_zone_check(NULL
)) {
628 if (!frames
) vm_allocate(mach_task_self(), (void *)&frames
, vm_page_size
, 1);
629 thread_stack_pcs(frames
, vm_page_size
/sizeof(vm_address_t
) - 1, &num_frames
);
631 _SIMPLE_STRING b
= _simple_salloc();
633 _simple_sprintf(b
, "*** MallocCheckHeap: FAILED check at %dth operation\n", malloc_check_counter
-1);
635 _malloc_printf(MALLOC_PRINTF_NOLOG
, "*** MallocCheckHeap: FAILED check at %dth operation\n", malloc_check_counter
-1);
636 malloc_printf("*** MallocCheckHeap: FAILED check at %dth operation\n", malloc_check_counter
-1);
640 _simple_sappend(b
, "Stack for last operation where the malloc check succeeded: ");
641 while (index
< num_frames
) _simple_sprintf(b
, "%p ", frames
[index
++]);
642 malloc_printf("%s\n(Use 'atos' for a symbolic stack)\n", _simple_string(b
));
645 * Should only get here if vm_allocate() can't get a single page of
646 * memory, implying _simple_asl_log() would also fail. So we just
647 * print to the file descriptor.
649 _malloc_printf(MALLOC_PRINTF_NOLOG
, "Stack for last operation where the malloc check succeeded: ");
650 while (index
< num_frames
) _malloc_printf(MALLOC_PRINTF_NOLOG
, "%p ", frames
[index
++]);
651 _malloc_printf(MALLOC_PRINTF_NOLOG
, "\n(Use 'atos' for a symbolic stack)\n");
654 if (malloc_check_each
> 1) {
655 unsigned recomm_each
= (malloc_check_each
> 10) ? malloc_check_each
/10 : 1;
656 unsigned recomm_start
= (malloc_check_counter
> malloc_check_each
+1) ? malloc_check_counter
-1-malloc_check_each
: 1;
657 malloc_printf("*** Recommend using 'setenv MallocCheckHeapStart %d; setenv MallocCheckHeapEach %d' to narrow down failure\n", recomm_start
, recomm_each
);
659 if (malloc_check_abort
) {
660 CRSetCrashLogMessage(b
? _simple_string(b
) : "*** MallocCheckHeap: FAILED check");
664 if (malloc_check_sleep
> 0) {
665 _malloc_printf(ASL_LEVEL_NOTICE
, "*** Sleeping for %d seconds to leave time to attach\n",
667 sleep(malloc_check_sleep
);
668 } else if (malloc_check_sleep
< 0) {
669 _malloc_printf(ASL_LEVEL_NOTICE
, "*** Sleeping once for %d seconds to leave time to attach\n",
670 -malloc_check_sleep
);
671 sleep(-malloc_check_sleep
);
672 malloc_check_sleep
= 0;
675 malloc_check_start
+= malloc_check_each
;
679 malloc_zone_malloc(malloc_zone_t
*zone
, size_t size
) {
681 if (malloc_check_start
&& (malloc_check_counter
++ >= malloc_check_start
)) {
684 if (size
> MALLOC_ABSOLUTE_MAX_SIZE
) {
687 ptr
= zone
->malloc(zone
, size
);
689 malloc_logger(MALLOC_LOG_TYPE_ALLOCATE
| MALLOC_LOG_TYPE_HAS_ZONE
, (uintptr_t)zone
, (uintptr_t)size
, 0, (uintptr_t)ptr
, 0);
694 malloc_zone_calloc(malloc_zone_t
*zone
, size_t num_items
, size_t size
) {
696 if (malloc_check_start
&& (malloc_check_counter
++ >= malloc_check_start
)) {
699 if (size
> MALLOC_ABSOLUTE_MAX_SIZE
) {
702 ptr
= zone
->calloc(zone
, num_items
, size
);
704 malloc_logger(MALLOC_LOG_TYPE_ALLOCATE
| MALLOC_LOG_TYPE_HAS_ZONE
| MALLOC_LOG_TYPE_CLEARED
, (uintptr_t)zone
, (uintptr_t)(num_items
* size
), 0,
710 malloc_zone_valloc(malloc_zone_t
*zone
, size_t size
) {
712 if (malloc_check_start
&& (malloc_check_counter
++ >= malloc_check_start
)) {
715 if (size
> MALLOC_ABSOLUTE_MAX_SIZE
) {
718 ptr
= zone
->valloc(zone
, size
);
720 malloc_logger(MALLOC_LOG_TYPE_ALLOCATE
| MALLOC_LOG_TYPE_HAS_ZONE
, (uintptr_t)zone
, (uintptr_t)size
, 0, (uintptr_t)ptr
, 0);
725 malloc_zone_realloc(malloc_zone_t
*zone
, void *ptr
, size_t size
) {
727 if (malloc_check_start
&& (malloc_check_counter
++ >= malloc_check_start
)) {
730 if (size
> MALLOC_ABSOLUTE_MAX_SIZE
) {
733 new_ptr
= zone
->realloc(zone
, ptr
, size
);
735 malloc_logger(MALLOC_LOG_TYPE_ALLOCATE
| MALLOC_LOG_TYPE_DEALLOCATE
| MALLOC_LOG_TYPE_HAS_ZONE
, (uintptr_t)zone
, (uintptr_t)ptr
, (uintptr_t)size
,
736 (uintptr_t)new_ptr
, 0);
741 malloc_zone_free(malloc_zone_t
*zone
, void *ptr
) {
743 malloc_logger(MALLOC_LOG_TYPE_DEALLOCATE
| MALLOC_LOG_TYPE_HAS_ZONE
, (uintptr_t)zone
, (uintptr_t)ptr
, 0, 0, 0);
744 if (malloc_check_start
&& (malloc_check_counter
++ >= malloc_check_start
)) {
747 zone
->free(zone
, ptr
);
751 malloc_zone_free_definite_size(malloc_zone_t
*zone
, void *ptr
, size_t size
) {
753 malloc_logger(MALLOC_LOG_TYPE_DEALLOCATE
| MALLOC_LOG_TYPE_HAS_ZONE
, (uintptr_t)zone
, (uintptr_t)ptr
, 0, 0, 0);
754 if (malloc_check_start
&& (malloc_check_counter
++ >= malloc_check_start
)) {
757 zone
->free_definite_size(zone
, ptr
, size
);
761 malloc_zone_from_ptr(const void *ptr
) {
765 return find_registered_zone(ptr
, NULL
);
769 malloc_zone_memalign(malloc_zone_t
*zone
, size_t alignment
, size_t size
) {
771 if (zone
->version
< 5) // Version must be >= 5 to look at the new memalign field.
773 if (!(zone
->memalign
))
775 if (malloc_check_start
&& (malloc_check_counter
++ >= malloc_check_start
)) {
778 if (size
> MALLOC_ABSOLUTE_MAX_SIZE
) {
781 if (alignment
< sizeof( void *) || // excludes 0 == alignment
782 0 != (alignment
& (alignment
- 1))) { // relies on sizeof(void *) being a power of two.
785 ptr
= zone
->memalign(zone
, alignment
, size
);
787 malloc_logger(MALLOC_LOG_TYPE_ALLOCATE
| MALLOC_LOG_TYPE_HAS_ZONE
, (uintptr_t)zone
, (uintptr_t)size
, 0, (uintptr_t)ptr
, 0);
791 /********* Functions for zone implementors ************/
794 malloc_zone_register(malloc_zone_t
*zone
) {
796 malloc_zone_register_while_locked(zone
);
801 malloc_zone_unregister(malloc_zone_t
*z
) {
804 if (malloc_num_zones
== 0)
808 for (index
= 0; index
< malloc_num_zones
; ++index
) {
809 if (z
!= malloc_zones
[index
])
812 // Modify the page to be allow write access, so that we can update the
813 // malloc_zones array.
814 size_t protect_size
= malloc_num_zones_allocated
* sizeof(malloc_zone_t
*);
815 mprotect(malloc_zones
, protect_size
, PROT_READ
| PROT_WRITE
);
817 // If we found a match, replace it with the entry at the end of the list, shrink the list,
818 // and leave the end of the list intact to avoid racing with find_registered_zone().
820 malloc_zones
[index
] = malloc_zones
[malloc_num_zones
- 1];
823 mprotect(malloc_zones
, protect_size
, PROT_READ
);
825 // Exchange the roles of the FRZ counters. The counter that has captured the number of threads presently
826 // executing *inside* find_regiatered_zone is swapped with the counter drained to zero last time through.
827 // The former is then allowed to drain to zero while this thread yields.
828 int *p
= pFRZCounterLive
;
829 pFRZCounterLive
= pFRZCounterDrain
;
830 pFRZCounterDrain
= p
;
831 __sync_synchronize(); // Full memory barrier
833 while (0 != *pFRZCounterDrain
) { pthread_yield_np(); }
840 malloc_printf("*** malloc_zone_unregister() failed for %p\n", z
);
844 malloc_set_zone_name(malloc_zone_t
*z
, const char *name
) {
847 mprotect(z
, sizeof(malloc_zone_t
), PROT_READ
| PROT_WRITE
);
849 free((char *)z
->zone_name
);
853 size_t buflen
= strlen(name
) + 1;
854 newName
= malloc_zone_malloc(z
, buflen
);
856 strlcpy(newName
, name
, buflen
);
857 z
->zone_name
= (const char *)newName
;
862 mprotect(z
, sizeof(malloc_zone_t
), PROT_READ
);
866 malloc_get_zone_name(malloc_zone_t
*zone
) {
867 return zone
->zone_name
;
871 * XXX malloc_printf now uses _simple_*printf. It only deals with a
872 * subset of printf format specifiers, but it doesn't call malloc.
875 __private_extern__
void
876 _malloc_vprintf(int flags
, const char *format
, va_list ap
)
880 if (_malloc_no_asl_log
|| (flags
& MALLOC_PRINTF_NOLOG
) || (b
= _simple_salloc()) == NULL
) {
881 if (!(flags
& MALLOC_PRINTF_NOPREFIX
)) {
883 /* XXX somewhat rude 'knowing' that pthread_t is a pointer */
884 _simple_dprintf(malloc_debug_file
, "%s(%d,%p) malloc: ", getprogname(), getpid(), (void *)pthread_self());
886 _simple_dprintf(malloc_debug_file
, "%s(%d) malloc: ", getprogname(), getpid());
889 _simple_vdprintf(malloc_debug_file
, format
, ap
);
892 if (!(flags
& MALLOC_PRINTF_NOPREFIX
)) {
894 /* XXX somewhat rude 'knowing' that pthread_t is a pointer */
895 _simple_sprintf(b
, "%s(%d,%p) malloc: ", getprogname(), getpid(), (void *)pthread_self());
897 _simple_sprintf(b
, "%s(%d) malloc: ", getprogname(), getpid());
900 _simple_vsprintf(b
, format
, ap
);
901 _simple_put(b
, malloc_debug_file
);
902 _simple_asl_log(flags
& MALLOC_PRINTF_LEVEL_MASK
, Malloc_Facility
, _simple_string(b
));
906 __private_extern__
void
907 _malloc_printf(int flags
, const char *format
, ...)
911 va_start(ap
, format
);
912 _malloc_vprintf(flags
, format
, ap
);
917 malloc_printf(const char *format
, ...)
921 va_start(ap
, format
);
922 _malloc_vprintf(ASL_LEVEL_ERR
, format
, ap
);
926 /********* Generic ANSI callouts ************/
929 malloc(size_t size
) {
931 retval
= malloc_zone_malloc(inline_malloc_default_zone(), size
);
932 if (retval
== NULL
) {
939 calloc(size_t num_items
, size_t size
) {
941 retval
= malloc_zone_calloc(inline_malloc_default_zone(), num_items
, size
);
942 if (retval
== NULL
) {
954 zone
= find_registered_zone(ptr
, &size
);
956 malloc_printf("*** error for object %p: pointer being freed was not allocated\n"
957 "*** set a breakpoint in malloc_error_break to debug\n", ptr
);
958 malloc_error_break();
959 if ((malloc_debug_flags
& (SCALABLE_MALLOC_ABORT_ON_CORRUPTION
|SCALABLE_MALLOC_ABORT_ON_ERROR
))) {
960 _SIMPLE_STRING b
= _simple_salloc();
962 _simple_sprintf(b
, "*** error for object %p: pointer being freed was not allocated\n", ptr
);
963 CRSetCrashLogMessage(_simple_string(b
));
965 CRSetCrashLogMessage("*** error: pointer being freed was not allocated\n");
969 } else if (zone
->version
>= 6 && zone
->free_definite_size
)
970 malloc_zone_free_definite_size(zone
, ptr
, size
);
972 malloc_zone_free(zone
, ptr
);
976 realloc(void *in_ptr
, size_t new_size
) {
982 // SUSv3: "If size is 0 and ptr is not a null pointer, the object
983 // pointed to is freed. If the space cannot be allocated, the object
984 // shall remain unchanged." Also "If size is 0, either a null pointer
985 // or a unique pointer that can be successfully passed to free() shall
986 // be returned." We choose to allocate a minimum size object by calling
987 // malloc_zone_malloc with zero size, which matches "If ptr is a null
988 // pointer, realloc() shall be equivalent to malloc() for the specified
989 // size." So we only free the original memory if the allocation succeeds.
990 old_ptr
= (new_size
== 0) ? NULL
: in_ptr
;
992 retval
= malloc_zone_malloc(inline_malloc_default_zone(), new_size
);
994 zone
= find_registered_zone(old_ptr
, &old_size
);
996 malloc_printf("*** error for object %p: pointer being realloc'd was not allocated\n"
997 "*** set a breakpoint in malloc_error_break to debug\n", old_ptr
);
998 malloc_error_break();
999 if ((malloc_debug_flags
& (SCALABLE_MALLOC_ABORT_ON_CORRUPTION
|SCALABLE_MALLOC_ABORT_ON_ERROR
))) {
1000 _SIMPLE_STRING b
= _simple_salloc();
1002 _simple_sprintf(b
, "*** error for object %p: pointer being realloc'd was not allocated\n", old_ptr
);
1003 CRSetCrashLogMessage(_simple_string(b
));
1005 CRSetCrashLogMessage("*** error: pointer being realloc'd was not allocated\n");
1010 retval
= malloc_zone_realloc(zone
, old_ptr
, new_size
);
1013 if (retval
== NULL
) {
1015 } else if (new_size
== 0) {
1022 valloc(size_t size
) {
1024 malloc_zone_t
*zone
= inline_malloc_default_zone();
1025 retval
= malloc_zone_valloc(zone
, size
);
1026 if (retval
== NULL
) {
1038 malloc_size(const void *ptr
) {
1044 (void)find_registered_zone(ptr
, &size
);
1049 malloc_good_size (size_t size
) {
1050 malloc_zone_t
*zone
= inline_malloc_default_zone();
1051 return zone
->introspect
->good_size(zone
, size
);
1055 * The posix_memalign() function shall allocate size bytes aligned on a boundary specified by alignment,
1056 * and shall return a pointer to the allocated memory in memptr.
1057 * The value of alignment shall be a multiple of sizeof( void *), that is also a power of two.
1058 * Upon successful completion, the value pointed to by memptr shall be a multiple of alignment.
1060 * Upon successful completion, posix_memalign() shall return zero; otherwise,
1061 * an error number shall be returned to indicate the error.
1063 * The posix_memalign() function shall fail if:
1065 * The value of the alignment parameter is not a power of two multiple of sizeof( void *).
1067 * There is insufficient memory available with the requested alignment.
1071 posix_memalign(void **memptr
, size_t alignment
, size_t size
)
1075 /* POSIX is silent on NULL == memptr !?! */
1077 retval
= malloc_zone_memalign(inline_malloc_default_zone(), alignment
, size
);
1078 if (retval
== NULL
) {
1079 // To avoid testing the alignment constraints redundantly, we'll rely on the
1080 // test made in malloc_zone_memalign to vet each request. Only if that test fails
1081 // and returns NULL, do we arrive here to detect the bogus alignment and give the
1082 // required EINVAL return.
1083 if (alignment
< sizeof( void *) || // excludes 0 == alignment
1084 0 != (alignment
& (alignment
- 1))) { // relies on sizeof(void *) being a power of two.
1089 *memptr
= retval
; // Set iff allocation succeeded
1094 static malloc_zone_t
*
1095 find_registered_purgeable_zone(void *ptr
) {
1100 * Look for a zone which contains ptr. If that zone does not have the purgeable malloc flag
1101 * set, or the allocation is too small, do nothing. Otherwise, set the allocation volatile.
1102 * FIXME: for performance reasons, we should probably keep a separate list of purgeable zones
1103 * and only search those.
1106 malloc_zone_t
*zone
= find_registered_zone(ptr
, &size
);
1108 /* FIXME: would really like a zone->introspect->flags->purgeable check, but haven't determined
1109 * binary compatibility impact of changing the introspect struct yet. */
1113 /* Check to make sure pointer is page aligned and size is multiple of page size */
1114 if ((size
< vm_page_size
) || ((size
% vm_page_size
) != 0))
1121 malloc_make_purgeable(void *ptr
) {
1122 malloc_zone_t
*zone
= find_registered_purgeable_zone(ptr
);
1126 int state
= VM_PURGABLE_VOLATILE
;
1127 vm_purgable_control(mach_task_self(), (vm_address_t
)ptr
, VM_PURGABLE_SET_STATE
, &state
);
1131 /* Returns true if ptr is valid. Ignore the return value from vm_purgeable_control and only report
1134 malloc_make_nonpurgeable(void *ptr
) {
1135 malloc_zone_t
*zone
= find_registered_purgeable_zone(ptr
);
1139 int state
= VM_PURGABLE_NONVOLATILE
;
1140 vm_purgable_control(mach_task_self(), (vm_address_t
)ptr
, VM_PURGABLE_SET_STATE
, &state
);
1142 if (state
== VM_PURGABLE_EMPTY
)
1148 size_t malloc_zone_pressure_relief(malloc_zone_t
*zone
, size_t goal
)
1154 // Take lock to defend against malloc_destroy_zone()
1156 while (index
< malloc_num_zones
) {
1157 zone
= malloc_zones
[index
++];
1158 if (zone
->version
< 8)
1160 if (NULL
== zone
->pressure_relief
)
1162 if (0 == goal
) /* Greedy */
1163 total
+= zone
->pressure_relief(zone
, 0);
1164 else if (goal
> total
)
1165 total
+= zone
->pressure_relief(zone
, goal
- total
);
1166 else /* total >= goal */
1172 // Assumes zone is not destroyed for the duration of this call
1173 if (zone
->version
< 8)
1175 if (NULL
== zone
->pressure_relief
)
1177 return zone
->pressure_relief(zone
, goal
);
1181 /********* Batch methods ************/
1184 malloc_zone_batch_malloc(malloc_zone_t
*zone
, size_t size
, void **results
, unsigned num_requested
) {
1185 unsigned (*batch_malloc
)(malloc_zone_t
*, size_t, void **, unsigned) = zone
-> batch_malloc
;
1188 if (malloc_check_start
&& (malloc_check_counter
++ >= malloc_check_start
)) {
1191 unsigned batched
= batch_malloc(zone
, size
, results
, num_requested
);
1192 if (malloc_logger
) {
1194 while (index
< batched
) {
1195 malloc_logger(MALLOC_LOG_TYPE_ALLOCATE
| MALLOC_LOG_TYPE_HAS_ZONE
, (uintptr_t)zone
, (uintptr_t)size
, 0, (uintptr_t)results
[index
], 0);
1203 malloc_zone_batch_free(malloc_zone_t
*zone
, void **to_be_freed
, unsigned num
) {
1204 if (malloc_check_start
&& (malloc_check_counter
++ >= malloc_check_start
)) {
1207 if (malloc_logger
) {
1209 while (index
< num
) {
1210 malloc_logger(MALLOC_LOG_TYPE_DEALLOCATE
| MALLOC_LOG_TYPE_HAS_ZONE
, (uintptr_t)zone
, (uintptr_t)to_be_freed
[index
], 0, 0, 0);
1214 void (*batch_free
)(malloc_zone_t
*, void **, unsigned) = zone
-> batch_free
;
1216 batch_free(zone
, to_be_freed
, num
);
1218 void (*free_fun
)(malloc_zone_t
*, void *) = zone
->free
;
1220 void *ptr
= *to_be_freed
++;
1221 free_fun(zone
, ptr
);
1226 /********* Functions for performance tools ************/
1228 static kern_return_t
1229 _malloc_default_reader(task_t task
, vm_address_t address
, vm_size_t size
, void **ptr
) {
1230 *ptr
= (void *)address
;
1235 malloc_get_all_zones(task_t task
, memory_reader_t reader
, vm_address_t
**addresses
, unsigned *count
) {
1236 // 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 )
1237 vm_address_t remote_malloc_zones
= (vm_address_t
)&malloc_zones
;
1238 vm_address_t remote_malloc_num_zones
= (vm_address_t
)&malloc_num_zones
;
1240 vm_address_t zones_address
;
1241 vm_address_t
*zones_address_ref
;
1243 unsigned *num_zones_ref
;
1244 if (!reader
) reader
= _malloc_default_reader
;
1245 // printf("Read malloc_zones at address %p should be %p\n", &malloc_zones, malloc_zones);
1246 err
= reader(task
, remote_malloc_zones
, sizeof(void *), (void **)&zones_address_ref
);
1247 // printf("Read malloc_zones[%p]=%p\n", remote_malloc_zones, *zones_address_ref);
1249 malloc_printf("*** malloc_get_all_zones: error reading zones_address at %p\n", (unsigned)remote_malloc_zones
);
1252 zones_address
= *zones_address_ref
;
1253 // printf("Reading num_zones at address %p\n", remote_malloc_num_zones);
1254 err
= reader(task
, remote_malloc_num_zones
, sizeof(unsigned), (void **)&num_zones_ref
);
1256 malloc_printf("*** malloc_get_all_zones: error reading num_zones at %p\n", (unsigned)remote_malloc_num_zones
);
1259 num_zones
= *num_zones_ref
;
1260 // printf("Read malloc_num_zones[%p]=%d\n", remote_malloc_num_zones, num_zones);
1262 // printf("malloc_get_all_zones succesfully found %d zones\n", num_zones);
1263 err
= reader(task
, zones_address
, sizeof(malloc_zone_t
*) * num_zones
, (void **)addresses
);
1265 malloc_printf("*** malloc_get_all_zones: error reading zones at %p\n", &zones_address
);
1268 // printf("malloc_get_all_zones succesfully read %d zones\n", num_zones);
1272 /********* Debug helpers ************/
1275 malloc_zone_print_ptr_info(void *ptr
) {
1276 malloc_zone_t
*zone
;
1278 zone
= malloc_zone_from_ptr(ptr
);
1280 printf("ptr %p in registered zone %p\n", ptr
, zone
);
1282 printf("ptr %p not in heap\n", ptr
);
1287 malloc_zone_check(malloc_zone_t
*zone
) {
1291 while (index
< malloc_num_zones
) {
1292 zone
= malloc_zones
[index
++];
1293 if (!zone
->introspect
->check(zone
)) ok
= 0;
1296 ok
= zone
->introspect
->check(zone
);
1302 malloc_zone_print(malloc_zone_t
*zone
, boolean_t verbose
) {
1305 while (index
< malloc_num_zones
) {
1306 zone
= malloc_zones
[index
++];
1307 zone
->introspect
->print(zone
, verbose
);
1310 zone
->introspect
->print(zone
, verbose
);
1315 malloc_zone_statistics(malloc_zone_t
*zone
, malloc_statistics_t
*stats
) {
1317 memset(stats
, 0, sizeof(*stats
));
1319 while (index
< malloc_num_zones
) {
1320 zone
= malloc_zones
[index
++];
1321 malloc_statistics_t this_stats
;
1322 zone
->introspect
->statistics(zone
, &this_stats
);
1323 stats
->blocks_in_use
+= this_stats
.blocks_in_use
;
1324 stats
->size_in_use
+= this_stats
.size_in_use
;
1325 stats
->max_size_in_use
+= this_stats
.max_size_in_use
;
1326 stats
->size_allocated
+= this_stats
.size_allocated
;
1329 zone
->introspect
->statistics(zone
, stats
);
1334 malloc_zone_log(malloc_zone_t
*zone
, void *address
) {
1337 while (index
< malloc_num_zones
) {
1338 zone
= malloc_zones
[index
++];
1339 zone
->introspect
->log(zone
, address
);
1342 zone
->introspect
->log(zone
, address
);
1346 /********* Misc other entry points ************/
1349 DefaultMallocError(int x
) {
1350 #if USE_SLEEP_RATHER_THAN_ABORT
1351 malloc_printf("*** error %d\n", x
);
1354 _SIMPLE_STRING b
= _simple_salloc();
1356 _simple_sprintf(b
, "*** error %d", x
);
1357 malloc_printf("%s\n", _simple_string(b
));
1358 CRSetCrashLogMessage(_simple_string(b
));
1360 _malloc_printf(MALLOC_PRINTF_NOLOG
, "*** error %d", x
);
1361 CRSetCrashLogMessage("*** DefaultMallocError called");
1368 malloc_error(void (*func
)(int)))(int) {
1369 return DefaultMallocError
;
1372 /* Stack logging fork-handling prototypes */
1373 extern void __stack_logging_fork_prepare();
1374 extern void __stack_logging_fork_parent();
1375 extern void __stack_logging_fork_child();
1376 extern void __stack_logging_early_finished();
1379 _malloc_fork_prepare() {
1380 /* Prepare the malloc module for a fork by insuring that no thread is in a malloc critical section */
1383 while (index
< malloc_num_zones
) {
1384 malloc_zone_t
*zone
= malloc_zones
[index
++];
1385 zone
->introspect
->force_lock(zone
);
1387 __stack_logging_fork_prepare();
1391 _malloc_fork_parent() {
1392 /* Called in the parent process after a fork() to resume normal operation. */
1394 __stack_logging_fork_parent();
1396 while (index
< malloc_num_zones
) {
1397 malloc_zone_t
*zone
= malloc_zones
[index
++];
1398 zone
->introspect
->force_unlock(zone
);
1403 _malloc_fork_child() {
1404 /* 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. */
1406 __stack_logging_fork_child();
1408 while (index
< malloc_num_zones
) {
1409 malloc_zone_t
*zone
= malloc_zones
[index
++];
1410 zone
->introspect
->force_unlock(zone
);
1415 * A Glibc-like mstats() interface.
1417 * Note that this interface really isn't very good, as it doesn't understand
1418 * that we may have multiple allocators running at once. We just massage
1419 * the result from malloc_zone_statistics in any case.
1424 malloc_statistics_t s
;
1427 malloc_zone_statistics(NULL
, &s
);
1428 m
.bytes_total
= s
.size_allocated
;
1429 m
.chunks_used
= s
.blocks_in_use
;
1430 m
.bytes_used
= s
.size_in_use
;
1432 m
.bytes_free
= m
.bytes_total
- m
.bytes_used
; /* isn't this somewhat obvious? */
1438 malloc_zone_enable_discharge_checking(malloc_zone_t
*zone
)
1440 if (zone
->version
< 7) // Version must be >= 7 to look at the new discharge checking fields.
1442 if (NULL
== zone
->introspect
->enable_discharge_checking
)
1444 return zone
->introspect
->enable_discharge_checking(zone
);
1448 malloc_zone_disable_discharge_checking(malloc_zone_t
*zone
)
1450 if (zone
->version
< 7) // Version must be >= 7 to look at the new discharge checking fields.
1452 if (NULL
== zone
->introspect
->disable_discharge_checking
)
1454 zone
->introspect
->disable_discharge_checking(zone
);
1458 malloc_zone_discharge(malloc_zone_t
*zone
, void *memory
)
1461 zone
= malloc_zone_from_ptr(memory
);
1464 if (zone
->version
< 7) // Version must be >= 7 to look at the new discharge checking fields.
1466 if (NULL
== zone
->introspect
->discharge
)
1468 zone
->introspect
->discharge(zone
, memory
);
1472 malloc_zone_enumerate_discharged_pointers(malloc_zone_t
*zone
, void (^report_discharged
)(void *memory
, void *info
))
1476 while (index
< malloc_num_zones
) {
1477 zone
= malloc_zones
[index
++];
1478 if (zone
->version
< 7)
1480 if (NULL
== zone
->introspect
->enumerate_discharged_pointers
)
1482 zone
->introspect
->enumerate_discharged_pointers(zone
, report_discharged
);
1485 if (zone
->version
< 7)
1487 if (NULL
== zone
->introspect
->enumerate_discharged_pointers
)
1489 zone
->introspect
->enumerate_discharged_pointers(zone
, report_discharged
);
1493 /***************** OBSOLETE ENTRY POINTS ********************/
1495 #if PHASE_OUT_OLD_MALLOC
1496 #error PHASE OUT THE FOLLOWING FUNCTIONS
1498 #warning PHASE OUT THE FOLLOWING FUNCTIONS
1502 set_malloc_singlethreaded(boolean_t single
) {
1503 static boolean_t warned
= 0;
1505 #if PHASE_OUT_OLD_MALLOC
1506 malloc_printf("*** OBSOLETE: set_malloc_singlethreaded(%d)\n", single
);
1513 malloc_singlethreaded() {
1514 static boolean_t warned
= 0;
1516 malloc_printf("*** OBSOLETE: malloc_singlethreaded()\n");
1522 malloc_debug(int level
) {
1523 malloc_printf("*** OBSOLETE: malloc_debug()\n");