Repository: miniLV/Interview-series
Branch: master
Commit: 262275f6ba6b
Files: 267
Total size: 3.1 MB
Directory structure:
gitextract_jkwm6bgm/
├── .gitignore
├── BlockFile.md
├── InterView-obj-isa-class/
│ ├── InterView-obj-isa-class/
│ │ ├── NSObject+MNTest.h
│ │ ├── NSObject+MNTest.m
│ │ └── main.m
│ ├── InterView-obj-isa-class.xcodeproj/
│ │ ├── project.pbxproj
│ │ └── project.xcworkspace/
│ │ ├── contents.xcworkspacedata
│ │ └── xcshareddata/
│ │ └── IDEWorkspaceChecks.plist
│ ├── libmalloc-166.220.1/
│ │ ├── .clang-format
│ │ ├── .gitattributes
│ │ ├── .gitignore
│ │ ├── include/
│ │ │ └── malloc/
│ │ │ ├── _malloc.h
│ │ │ └── malloc.h
│ │ ├── libmalloc.xcodeproj/
│ │ │ └── project.pbxproj
│ │ ├── man/
│ │ │ ├── malloc.3
│ │ │ ├── malloc_size.3
│ │ │ ├── malloc_zone_malloc.3
│ │ │ └── manpages.lst
│ │ ├── private/
│ │ │ ├── malloc_private.h
│ │ │ └── stack_logging.h
│ │ ├── resolver/
│ │ │ ├── resolver.c
│ │ │ ├── resolver.h
│ │ │ └── resolver_internal.h
│ │ ├── src/
│ │ │ ├── base.h
│ │ │ ├── bitarray.c
│ │ │ ├── bitarray.h
│ │ │ ├── debug.h
│ │ │ ├── dtrace.h
│ │ │ ├── empty.s
│ │ │ ├── frozen_malloc.c
│ │ │ ├── frozen_malloc.h
│ │ │ ├── internal.h
│ │ │ ├── legacy_malloc.c
│ │ │ ├── legacy_malloc.h
│ │ │ ├── locking.h
│ │ │ ├── magazine_inline.h
│ │ │ ├── magazine_large.c
│ │ │ ├── magazine_lite.c
│ │ │ ├── magazine_malloc.c
│ │ │ ├── magazine_malloc.h
│ │ │ ├── magazine_rack.c
│ │ │ ├── magazine_rack.h
│ │ │ ├── magazine_small.c
│ │ │ ├── magazine_tiny.c
│ │ │ ├── magazine_zone.h
│ │ │ ├── magmallocProvider.d
│ │ │ ├── malloc.c
│ │ │ ├── malloc_common.c
│ │ │ ├── malloc_common.h
│ │ │ ├── malloc_printf.c
│ │ │ ├── nano_malloc.c
│ │ │ ├── nano_malloc.h
│ │ │ ├── nano_malloc_common.c
│ │ │ ├── nano_malloc_common.h
│ │ │ ├── nano_zone.h
│ │ │ ├── nano_zone_common.h
│ │ │ ├── nanov2_malloc.c
│ │ │ ├── nanov2_malloc.h
│ │ │ ├── nanov2_zone.h
│ │ │ ├── platform.h
│ │ │ ├── printf.h
│ │ │ ├── purgeable_malloc.c
│ │ │ ├── purgeable_malloc.h
│ │ │ ├── radix_tree.c
│ │ │ ├── radix_tree.h
│ │ │ ├── radix_tree_debug.c
│ │ │ ├── radix_tree_internal.h
│ │ │ ├── stack_logging_disk.c
│ │ │ ├── stack_logging_internal.h
│ │ │ ├── thresholds.h
│ │ │ ├── trace.h
│ │ │ ├── vm.c
│ │ │ └── vm.h
│ │ ├── tests/
│ │ │ ├── Makefile
│ │ │ ├── MallocBench/
│ │ │ │ ├── Benchmark.cpp
│ │ │ │ ├── Benchmark.h
│ │ │ │ ├── CPUCount.cpp
│ │ │ │ ├── CPUCount.h
│ │ │ │ ├── CommandLine.cpp
│ │ │ │ ├── CommandLine.h
│ │ │ │ ├── Interpreter.cpp
│ │ │ │ ├── Interpreter.h
│ │ │ │ ├── balloon.cpp
│ │ │ │ ├── balloon.h
│ │ │ │ ├── big.cpp
│ │ │ │ ├── big.h
│ │ │ │ ├── churn.cpp
│ │ │ │ ├── churn.h
│ │ │ │ ├── fragment.cpp
│ │ │ │ ├── fragment.h
│ │ │ │ ├── list.cpp
│ │ │ │ ├── list.h
│ │ │ │ ├── mbmalloc.cpp
│ │ │ │ ├── mbmalloc.h
│ │ │ │ ├── medium.cpp
│ │ │ │ ├── medium.h
│ │ │ │ ├── memalign.cpp
│ │ │ │ ├── memalign.h
│ │ │ │ ├── message.cpp
│ │ │ │ ├── message.h
│ │ │ │ ├── realloc.cpp
│ │ │ │ ├── realloc.h
│ │ │ │ ├── stress.cpp
│ │ │ │ ├── stress.h
│ │ │ │ ├── stress_aligned.cpp
│ │ │ │ ├── stress_aligned.h
│ │ │ │ ├── tree.cpp
│ │ │ │ └── tree.h
│ │ │ ├── MallocBench.cpp
│ │ │ ├── asan.c
│ │ │ ├── basic_malloc_free_perf.c
│ │ │ ├── calloc_test.c
│ │ │ ├── libmalloc_tests.xcodeproj/
│ │ │ │ └── project.pbxproj
│ │ │ ├── madvise.c
│ │ │ ├── magazine_malloc.c
│ │ │ ├── magazine_rack.c
│ │ │ ├── magazine_small_test.c
│ │ │ ├── magazine_testing.h
│ │ │ ├── magazine_tiny_test.c
│ │ │ ├── malloc_claimed_address_tests.c
│ │ │ ├── malloc_free_test.c
│ │ │ ├── malloc_size_test.c
│ │ │ ├── nano_tests.c
│ │ │ ├── perf_contended_malloc_free.c
│ │ │ ├── perf_realloc.c
│ │ │ ├── radix_tree_test.m
│ │ │ ├── reallocarray.c
│ │ │ ├── stack_logging_test.c
│ │ │ ├── stress_test.c
│ │ │ └── tsan.c
│ │ ├── tools/
│ │ │ ├── malloc_replay.cpp
│ │ │ ├── malloc_replay.h
│ │ │ ├── malloc_replay_plotter.py
│ │ │ ├── radix_tree_main.m
│ │ │ └── read-radix-tree
│ │ ├── xcodeconfig/
│ │ │ ├── interposable.list
│ │ │ ├── libmalloc.dirty
│ │ │ ├── libmalloc.xcconfig
│ │ │ ├── libmalloc_eos.xcconfig
│ │ │ ├── libmalloc_resolved.xcconfig
│ │ │ ├── libmalloc_resolver.xcconfig
│ │ │ └── libmalloc_static.xcconfig
│ │ └── xcodescripts/
│ │ ├── install-codes.sh
│ │ ├── manpages.sh
│ │ ├── reindent.sh
│ │ └── sanitise_headers.sh
│ └── objc4-750/
│ ├── APPLE_LICENSE
│ ├── ReleaseNotes.rtf
│ ├── interposable.txt
│ ├── libobjc.order
│ ├── markgc.cpp
│ ├── objc.sln
│ ├── objc.vcproj
│ ├── objc.xcodeproj/
│ │ ├── project.pbxproj
│ │ └── project.xcworkspace/
│ │ ├── contents.xcworkspacedata
│ │ └── xcshareddata/
│ │ └── IDEWorkspaceChecks.plist
│ ├── objcrt/
│ │ └── objcrt.vcproj
│ ├── prebuild.bat
│ ├── runtime/
│ │ ├── Messengers.subproj/
│ │ │ ├── objc-msg-arm.s
│ │ │ ├── objc-msg-arm64.s
│ │ │ ├── objc-msg-i386.s
│ │ │ ├── objc-msg-simulator-i386.s
│ │ │ ├── objc-msg-simulator-x86_64.s
│ │ │ ├── objc-msg-win32.m
│ │ │ └── objc-msg-x86_64.s
│ │ ├── Module/
│ │ │ ├── ObjectiveC.apinotes
│ │ │ └── module.modulemap
│ │ ├── NSObjCRuntime.h
│ │ ├── NSObject.h
│ │ ├── NSObject.mm
│ │ ├── Object.h
│ │ ├── Object.mm
│ │ ├── OldClasses.subproj/
│ │ │ ├── List.h
│ │ │ └── List.m
│ │ ├── Protocol.h
│ │ ├── Protocol.mm
│ │ ├── arm64-asm.h
│ │ ├── hashtable.h
│ │ ├── hashtable2.h
│ │ ├── hashtable2.mm
│ │ ├── isa.h
│ │ ├── llvm-AlignOf.h
│ │ ├── llvm-DenseMap.h
│ │ ├── llvm-DenseMapInfo.h
│ │ ├── llvm-MathExtras.h
│ │ ├── llvm-type_traits.h
│ │ ├── maptable.h
│ │ ├── maptable.mm
│ │ ├── message.h
│ │ ├── objc-abi.h
│ │ ├── objc-accessors.mm
│ │ ├── objc-api.h
│ │ ├── objc-auto.h
│ │ ├── objc-auto.mm
│ │ ├── objc-block-trampolines.h
│ │ ├── objc-block-trampolines.mm
│ │ ├── objc-blocktramps-arm.s
│ │ ├── objc-blocktramps-arm64.s
│ │ ├── objc-blocktramps-i386.s
│ │ ├── objc-blocktramps-x86_64.s
│ │ ├── objc-cache-old.h
│ │ ├── objc-cache-old.mm
│ │ ├── objc-cache.h
│ │ ├── objc-cache.mm
│ │ ├── objc-class-old.mm
│ │ ├── objc-class.h
│ │ ├── objc-class.mm
│ │ ├── objc-config.h
│ │ ├── objc-env.h
│ │ ├── objc-errors.mm
│ │ ├── objc-exception.h
│ │ ├── objc-exception.mm
│ │ ├── objc-file-old.h
│ │ ├── objc-file-old.mm
│ │ ├── objc-file.h
│ │ ├── objc-file.mm
│ │ ├── objc-gdb.h
│ │ ├── objc-initialize.h
│ │ ├── objc-initialize.mm
│ │ ├── objc-internal.h
│ │ ├── objc-layout.mm
│ │ ├── objc-load.h
│ │ ├── objc-load.mm
│ │ ├── objc-loadmethod.h
│ │ ├── objc-loadmethod.mm
│ │ ├── objc-lockdebug.h
│ │ ├── objc-lockdebug.mm
│ │ ├── objc-locks-new.h
│ │ ├── objc-locks-old.h
│ │ ├── objc-locks.h
│ │ ├── objc-object.h
│ │ ├── objc-opt.mm
│ │ ├── objc-os.h
│ │ ├── objc-os.mm
│ │ ├── objc-private.h
│ │ ├── objc-probes.d
│ │ ├── objc-ptrauth.h
│ │ ├── objc-references.h
│ │ ├── objc-references.mm
│ │ ├── objc-runtime-new.h
│ │ ├── objc-runtime-new.mm
│ │ ├── objc-runtime-old.h
│ │ ├── objc-runtime-old.mm
│ │ ├── objc-runtime.h
│ │ ├── objc-runtime.mm
│ │ ├── objc-sel-old.mm
│ │ ├── objc-sel-set.h
│ │ ├── objc-sel-set.mm
│ │ ├── objc-sel-table.s
│ │ ├── objc-sel.mm
│ │ ├── objc-sync.h
│ │ ├── objc-sync.mm
│ │ ├── objc-typeencoding.mm
│ │ ├── objc-weak.h
│ │ ├── objc-weak.mm
│ │ ├── objc.h
│ │ ├── objcrt.c
│ │ ├── objcrt.h
│ │ └── runtime.h
│ ├── unexported_symbols
│ ├── version.bat
│ └── version.rc
├── LICENSE
├── README.md
├── category分析.md
├── isa&&Class&&meta-class.md
└── 什么是NSObject.md
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
# Xcode
#
# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore
## Build generated
build/
DerivedData/
## Various settings
*.pbxuser
!default.pbxuser
*.mode1v3
!default.mode1v3
*.mode2v3
!default.mode2v3
*.perspectivev3
!default.perspectivev3
xcuserdata/
## Other
*.moved-aside
*.xccheckout
*.xcscmblueprint
## Obj-C/Swift specific
*.hmap
*.ipa
*.dSYM.zip
*.dSYM
# CocoaPods
#
# We recommend against adding the Pods directory to your .gitignore. However
# you should judge for yourself, the pros and cons are mentioned at:
# https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control
#
# Pods/
# Carthage
#
# Add this line if you want to avoid checking in source code from Carthage dependencies.
# Carthage/Checkouts
Carthage/Build
# fastlane
#
# It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the
# screenshots whenever they are needed.
# For more information about the recommended setup visit:
# https://docs.fastlane.tools/best-practices/source-control/#source-control
fastlane/report.xml
fastlane/Preview.html
fastlane/screenshots
fastlane/test_output
# Code Injection
#
# After new code Injection tools there's a generated folder /iOSInjectionProject
# https://github.com/johnno1962/injectionforxcode
iOSInjectionProject/
================================================
FILE: BlockFile.md
================================================
# Block
> 面试驱动技术合集(初中级iOS开发),关注仓库,及时获取更新 [Interview-series](https://github.com/miniLV/Interview-series)

Block 在 iOS 算比较常见常用且常考的了,现在面试中,要么没面试题,有面试题的,基本都会考到 block 的点。
先来个面试题热热身,题目: **手撕代码 - 用Block实现两个数的求和**
*(这题如果会的,block基础知识可以跳过了,直接到* Block原理探究)
#### 简单介绍block入门级用法
Block结构比较复杂,一般用 typedef 定义,直接调用的感觉比较简单、清晰易懂
```
//typedef block的时候有提示
typedef void(^MNBlock)(int);
@interface ViewController ()
@property (nonatomic, copy) MNBlock block;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//直接用self.block调用
self.block = ^(int a) {
//dosomething...
};
}
```
- **参数解释:**
`typedef <#returnType#>(^<#name#>)(<#arguments#>);`

**题目: 手撕代码 - 用Block实现两个数的求和**
*日常开发中,block声明一般写的比较多,实现一般是靠Xcode自动补全提示出现的,手撕代码的情况下,等号右侧的block实现要怎么写?*
声明:
```
typedef int(^MNBlock)(int a, int b);
@interface ViewController ()
@property (nonatomic, copy) MNBlock sum;
```
Vip补全功能:

纸上按Enter没用啊兄弟!看来还是需要了解一下Block右边的东西~
先在 Xcode上按下 Enter,了解下再撕

```
^int(int a, int b) {
//Control reaches end of non-void block
因为返回值是int类型,所以这里需要返回
}
```

```
int(^Sum)(int, int) = ^(int a, int b){
return a + b;
};
int result = Sum(5, 10);
```

#### Block的坑出现!新手可能会写错的地方
1.声明出错 - `void ^(testBlock)`

修正版:
```
void (^testBlock)() = ^{
};
```
block的声明,^ 和 blockName 都是在小括号里面!!
2.block各种实现的参数问题
声明`typedef int(^MNBlock)(int, int);`

```
self.sum = ^int(int a, int b) {
return a + b;
};
```
这里要注意,block声明里面只有参数类型,没有实际参数的话,Xcode提示也只有参数,这里涉及到形参和实参的问题
声明是形参,可以不写参数,但是使用的时候,必须有实际参数,才可以进行使用,所以这里需要实参,可以在 `^int(int , int)` 中手动添加实参`^int(int a, int b)`,就可以让a 和 b 参与运算
小tips:实际开发中,建议声明的时候,如果需要带参数,最好形参也声明下,这样使用Xcode提示的时候,会把参数带进去,方便得多~(踩过坑的自然懂!)
3. 省略void导致看不懂block结构的 *(正常是两个void导致局面混乱)*
```
//声明
typedef void(^MNBlock)(void);
//实现
self.sum = ^{
//dosomething...
};
```
这种情况下,能知道怎么省略的,声明里两个void,能知道怎么对应的吗?
这个其实比较简单,block不管声明 or 实现,最后一个小括号,里面都是参数,而参数是可以省略的!
而为了把声明的两个void区分开,返回值 or 参数区分开,其实就ok了
参数非void的例子
```
//声明非void的参数
typedef void(^MNBlock)(int a);
//实现就必须带参数,不可省略!
self.sum = ^(int a) {
}
```
参数void的例子 ==> 参数可以省略
```
typedef int(^MNBlock)(void);
self.sum = ^{
//声明的返回值类型是int,所以一定要return;
return 5;
};
```
其实-返回值是void的,也可以不省略
```
typedef void(^MNBlock)(void);
//实现的返回值不省略
self.sum = ^void () {
};
```
参数是void的省略:
```
typedef int(^MNBlock)();
//实现里面,没有参数,就可以不写()
self.sum = ^int{
return 5;
}
```
**注意!! 声明里面的返回值void是不可以省略的!!**

4. 小箭头^混乱的问题,到底放小括号内还是小括号外
声明是 `int(^MNBlock)(int a , int b)`
实现是 `^int(int a, int b)`
注意,这里箭头之后的,不管是多写() 还是少写,都会出错


> 所以这里还不能死记,比如不管声明还是实现,死记 (^ xxx) 是没问题的 or 死记 ^…… xxx 不加括号是没问题的,在这里都行不通,只能靠脑记了
这时候,就需要用到巧记了!
*^ 和小括号组合的,一共有三种情况*
- 一种是声明的,`void(^MNBlock)`
- 一种是实现的,`^int(int a,)`
- 还一种 `^(int a)`
兄弟,看到这你还不乱吗!!

怎么记看这里,
- 手写分为两个部分,block等号左边 or 等号右边的,左边为声明,右边为实现区分开
- 声明记住:^后面跟blockName,他们需要包起来! (^blockName),只有声明会用到blockName,先记住一点,如果有blockName,要和^一起,用小括号包起来
- 实现又分为两种:
- `^int`:^后面跟的是返回值类型
- ^ 直接跟类型,不用加"( )" ==> `^int`
- `^(int a)`:^后面直接跟参数 *(返回值是void)*。
- 参数都是要用"( )"包起来的,如果^后面跟参数,就得用"( )" ==> `^(int a)`,
- 实现里,肯定有实际参数,这时候,参数类型和实参,就得用( )包起来
### ^与小括号纠缠的总结
- ^ 后面仅跟类型,不需要小括号,==> `^int`
- ^ 后面跟参数,参数需要小括号 ==> `^(int a)`
- ^ 后面跟block名称,^和blockName需要小括号 ==> `void (^MNBlock)`
## Block原理探究
```objective-c
void (^MNBlock)(void) = ^(void){
NSLog(@"this is a Block~ rua~");
};
MNBlock();
```
使用 `xcrun -sdk iphoneos clang -arch arm64 -rewrite-objc main.m` 转成 C++ 代码, 查看底层结构
```objective-c
//对应上面的 MNBlock声明
void (*MNBlock)(void) = (&__main_block_impl_0(__main_block_func_0,
&__main_block_desc_0_DATA));
//对应上面的 MNblock() 调用
MNBlock->FuncPtr(MNBlock);
```
```objective-c
//block声明调用的 - __main_block_impl_0
struct __main_block_impl_0 {
//结构体内的参数
struct __block_impl impl;
struct __main_block_desc_0* Desc;
//c++中的构造函数,类似于 OC 的 init 方法,返回一个结构体对象
__main_block_impl_0(void *fp, struct __main_block_desc_0 *desc, int flags=0) {
impl.isa = &_NSConcreteStackBlock;
impl.Flags = flags;
impl.FuncPtr = fp;
Desc = desc;
}
};
struct __block_impl {
void *isa;
int Flags;
int Reserved;
void *FuncPtr;
};
static struct __main_block_desc_0 {
size_t reserved;
size_t Block_size;
}
```
这里的block封装的函数调用解释`MNBlock->FuncPtr(MNBlock);`
MNBlock 其实内部结构是 `__main_block_impl_0`,
```
struct __main_block_impl_0 {
//函数调用地址在这个结构体内
struct __block_impl impl;
struct __main_block_desc_0* Desc;
}
struct __block_impl {
void *isa;
int Flags;
int Reserved;
//函数调用地址在这里
void *FuncPtr;
};
```
内部只有两个参数,一个`impl`,一个`Desc`,而函数的调用地址 - `FuncPtr`是再`impl`中的,为什么这里能直接这样写呢?
> 因为,__main_block_impl_0 结构的地址和他的第一个成员一样,第一个成员的地址是__block_impl,所以__main_block_impl_0 和 __block_impl 的地址其实是同一个,通过格式强制转换,将 main_block_impl_0 转成 block_impl 就可以直接拿到他内部的 FuncPtr 函数地址,然后进行调用!

- 可见- block本质上是OC对象,内部有一个isa指针
- block是封装了函数调用已经函数调用的oc对象
### Block面试题抛砖引玉~
**开胃菜先来一下,以下结果输出什么**
```
int a = 10;
void (^MNBlock)(void) = ^{
NSLog(@"a = %d",a);
};
a += 20;
MNBlock();
```
调用 `MNBlock();` 之前,a 已经 + 20了,输出30? 太天真了兄弟,这里涉及到capture的概念,即变量捕获
### Block捕获变量(capture)
捕获:Block内部会新增一个成员,来存储传进来的变量

block 内部直接捕获了穿进去的这个变量a(10)

创建block的时候,已经将变量a=10 捕获到 block内部,之后再怎么修改,不会影响block 内部的 a
**auto 和 static的区别**:以下会输出什么~
```
static int b = 10;
void (^MNBlock)(void) = ^{
NSLog(@"a = %d, b = %d",a,b);
};
a = 20;
b = 20;
MNBlock();
```
输出
```
2019-03-07 21:49:49 Block-Demo a = 10, b = 20
```
why?
查看原因:
```
auto int a = 10;
static int b = 10;
void (*MNBlock)(void) = (&__main_block_impl_0(__main_block_func_0,
&__main_block_desc_0_DATA,
a,
&b));
```
发现:两种变量,都有捕获到block内部。
a 是auto变量,走的是值传递,
b 是 static 变量,走的是地址传递,所以会影响(指针指向同一块内存,修改的等于是同个对象)
**总结**
- 只有局部变量才需要捕获,
- 全局变量不需要捕获,因为在哪都可以访问
- 需不需要捕获,其实主要是看作用域问题
- auto局部变量 ==>值传递->因为会销毁
- static局部练练==>不会销毁==>所以地址传递
**看图就行~**

**进阶考题 - self 会被捕获到 block 内部吗**
```
void (^MNBlock)(void) = ^{
NSLog(@"p = %p",self);
};
```
模拟看官作答:不会,因为整个类里,都能调用self,应该是全局的,全局变量不会捕获到block中
哈哈哈哈!中计了!其实 self 是参数(局部变量)
```
struct __MNDemo__test_block_impl_0 {
struct __block_impl impl;
struct __MNDemo__test_block_desc_0* Desc;
MNDemo *self; ==> 捕捉到了兄弟
}
```
> 解释原因:
>
> - 每个OC函数,其实默认有两个参数,一个self,一个_cmd,只是他们倆兄弟默认是隐藏的
> - 而由于他们是参数,所以是局部变量,局部变量就要被 block 捕获
> - `- (void)test(self, SEL _cmd){XXX}` 默认的OC方法里面其实有这两个隐藏的参数!所以上题的答案,self是会被block捕获的!**(能听懂掌声!)**
**进进阶考题 - 成员变量_name 会被捕获到 block 内部吗**
```
void (^MNBlock)(void) = ^{
NSLog(@"==%@",_name);
};
```
模拟看官作答:呵呵,老子都中了这么多次技了,这题学会了!! 因为_name是成员变量,全局的,也没有self,所以不需要捕获整个类就都可以随便访问它!
哎,兄弟,还是太年轻了!!
```
void (^MNBlock)(void) = ^{
NSLog(@"==%@",self->_name);
};
```
看图说话,不多bb, *(能听懂掌声!)*
## Block的类型
- `__NSGlobalBlock__`
- `__NSStackBlock__`
- `__NSMallocBlock__`
MRC环境下
```
void (^global)() = ^{
NSLog(@"globalValue = %d",globalValue);
};
void (^autoBlock)() = ^{
NSLog(@"this is a Block~ rua~ = %d",a);
};
void (^copyAuto)() = [autoBlock copy];
--------------------------------------------
print class
2019-03-08 17:40:43 Block-Demo
global class = __NSGlobalBlock__
autoBlock class = __NSStackBlock__
copyAuto = __NSMallocBlock__
```
总结:


栈上的内存系统会自动回收
- 栈空间的block 不会对 对象进行强引用
- 堆空间的block 可能会对对象产生强引用:
- 如果是weak指针,不会强引用
- 如果是strong指针,会强引用
堆上的内存是由程序员控制,所以一般将block 拷贝到堆上,让程序员控制他与内部变量的生命周期
题目:以下输出的顺序是什么(ARC环境下)
```
@implementation MNPerson
- (void)dealloc{
NSLog(@"MNPerson - dealloc");
}
@end
--------------------------------------
MNPerson *person = [[MNPerson alloc]init];
__weak MNPerson *weakPerson = person;
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
NSLog(@"1-----%@",person);
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
NSLog(@"2------%@",weakPerson);
});
});
NSLog(@"touchesBegan");
```
输出结果
```
2019-03-08 22:38:59.038452+0800 touchesBegan
2019-03-08 22:39:00.056746+0800 1-----
2019-03-08 22:39:00.057891+0800 MNPerson - dealloc
2019-03-08 22:39:02.058011+0800 2-----(null)
```
解释:
1. gcd的block会自动对auto变量进行copy操作
2. block内部对 auto 变量的强弱引用,取决于指针类型
3. 1 中的auto变量是 person,没声明默认对象是 strong 类型,所以 gcd1 会对 person进行 1s的强引用
4. gcd2 中的变量是 weakPerson,看到是__wesk指针,所以block内部不会对其产生强引用
5. 随后,gcd1 对 person进行1s的强引用之后,gcd1 的block销毁,person对象销毁,打印MNPerson dealloc
6. 最终,2s过后打印 2——weakPerson,因为person对象在gcd1 block结束之后,释放掉了,所以此时person是空,因为是weak指针,对象是null不会crash,最终打印null
#### 对象类型的auto变量
- 当 block 内部访问了对象类型的auto变量时
- 如果block在展示,不会对 auto 变量产生强引用
- 如果 block 被 拷贝到堆上
- 会调用 block 内部的 copy 函数
- copy 函数内部会调用 _Block_object_assign 函数
- _Block_object_assign 函数会根据auto变量的修饰符 *( strong、 weak、unsafe_unretained )* 做出对应的操作,看对内部auto变量进行强引用还是弱引用(类似于 retain)
- 如果 block 从 堆上移除
- 会调用 block 内部的 dispose 函数
- dispose函数内部会调用_Block_object_dispose 函数
- _Block_object_dispose 类似于 release,会对auto变量进行自动释放(当引用计数器=0的时候 )

#### block中的copy
- 在ARC环境下,编译器会根据情况,自动将栈上的block拷贝到堆上,比如以下几种情况
- block 作为函数返回值的时候
- 将block复制给__strong指针的时候
- block作为Cocoa API中方法名含有usingBlock的方法参数事
- 比如:`[array enumerateObjectsUsingBlock:XXX]`
### __block 修饰符的使用
题目:以下代码的是否编译通过,可以的话输出结果是什么
```
int a = 10;
void (^block)() = ^{
a = 20;
NSLog(@"a = %d",a);
};
```
结果如下:

*思考:无法编译,为啥呢?编译的时候,block应该是会把auto变量捕获进去的,那block结构中应该有a才对啊*
```
//main函数
int main(int argc, const char * argv[]) {
/* @autoreleasepool */ { __AtAutoreleasePool __autoreleasepool;
int a = 10;
void (*block)() = ((void (*)())&__main_block_impl_0((void *)__main_block_func_0, &__main_block_desc_0_DATA, a));
}
return 0;
}
//block执行地址
static void __main_block_func_0(struct __main_block_impl_0 *__cself) {
int a = __cself->a; // bound by copy
NSLog((NSString *)&__NSConstantStringImpl__var_folders_kh_0rp73c0s2mvfp5gjf25j5y6h0000gn_T_main_1a12fa_mi_0,a);}
```
block执行的时候,内部是 `__main_block_func_0` 函数,而a的声明,是在`main`函数,两个函数相互独立,对于他们来说,a都是一个局部变量,而且两个函数中都对a初始化,两个函数的中a不是同一个,那怎么可以在 执行函数中,修改main函数中的局部变量呢,所以编译报错!
如何改?
- **方案一:使用static**
```
static int a = 10;
void (^block)() = ^{
a = 20;
NSLog(@"a = %d",a);
};
```
因为static修饰的auto变量,最终在block中进行的不是值传递,而是地址传递,措意执行函数中的a 和 main 函数中的a,是同一个地址 ==> 等于同一个a,所以可以修改,输出20
但是使用static,就会变成静态变量,永远在内存中
- **方案二: 使用__blcok**
```
__block auto int a = 10;
void (^block)() = ^{
a = 20;
NSLog(@"a = %d",a);
};
```
```
struct __main_block_impl_0 {
struct __block_impl impl;
struct __main_block_desc_0* Desc;
__Block_byref_a_0 *a; // by ref ==> auto的话,是int a,__block,变成对象了
}
```
```
struct __Block_byref_a_0 {
void *__isa;
__Block_byref_a_0 *__forwarding;==> 指向自己的结构体
int __flags;
int __size;
int a; ==> 10在这里
};
```
a = 20;最终转成 `(a->__forwarding->a) = 20;`
> 解释下:__forwarding 是指向结构体本身的指针,等价于a本身,其实就是通过a的结构体指针,拿到里面的成员a,再对他赋值
>
> 指针传递,所以可以修改 auto 变量,通过block,间接引用 auto 变量

#### __block的内存管理
- 当 block 在栈上的时候,不会对内部的__block 变量产生强硬有
- 当 block 从栈上被 copy 到堆上的时候
- 会调用block内部的copy函数
- copy函数内部会调用_Block_object_assign 函数
- _Block_object_assign 函数会对 __block 变量进行一次 retain操作,产生强引用
抄图分析 :


- 当block从堆中移除时
- 会调用 block 内部的 dispose 函数
- dispose内部会调用_Block_object_dispose函数
- _Block_object_dispose函数会对`__block`变量进行一次release操作,如果retainCount为0,自动释放该__block变量


**总结:**
- block在栈上的时候,不会对内部的变量产生强引用
- 当block从栈上 copy 到堆上的时候,内部都会调用 __Block_object_assign
- 如果是`__block`修饰的变量,会__block修饰的对象产生强引用
- 如果是普通auto变量,看修饰的指针类型是strong 还是 weak(unsafe_unretained)
- strong修饰的,block就会对内部的auto变量产生强引用
- weak修饰的,block就不会对内部的auto变量产生强引用
- 特别注意!上述条件仅在ARC环境下生效,如果是MRC环境下,block不会对内部auto变量产生强引用!**(MRC下不会进行retain操作)**
- 当block从堆上移除的时候,内部会调用`__Block_object_dispose `函数,相当于对`block`内部所持有的对象进行移除release操作,如果retainCount为0,自动释放该__block变量
#### __block中的 _ forwarding 指针
内存拷贝的时候,如果block从栈被copy到堆上,肯定也希望内部的变量一起存储到堆上(让变量的生命周期可控,才不会被回收)
加入变量a在栈上,在栈上的指针,指向堆上的 block,堆上的block的 forwarding指向他自己,就可以保证,修改&获取的变量,都是堆上的变量

最终,__block指向的变量,是指向堆上的
#### __block 修饰的类型
```
@implementation MNObject
- (void)dealloc{
NSLog(@"MNObject - dealloc");
}
@end
--------------------------------------------
typedef void (^MNBlock)();
MNBlock block;
{
MNObject *obj = [[MNObject alloc]init];
__block __weak MNObject *weakObj = obj;
block = ^{
NSLog(@"----------%p",weakObj);
};
}
block();
```
问,上述代码的输出顺序是?
```
2019-03-09 21:57:56.673296+0800 Block-Demo[72692:8183596] MNObject - dealloc
2019-03-09 21:57:56.673520+0800 Block-Demo[72692:8183596] ----------0x0
```
解释:ARC下

上述代码,block 持有的是 weakObj,weak指针,所以block内部的__block结构体,对他内部持有的person不强引用!所以出了 小括号后,person没有被强引用,生命gg,先dealloc,输出`dealloc`,之后进行block调用,打印 ---------
**特别注意,上述逻辑进在ARC下,如果在MRC下,中间结构体对象,不会对person 进行retain操作! 即便 person 是强指针修饰,也不会对内部的person对象进行强引用!**
MRC环境下
```
MNBlock block;
{
MNObject *obj = [[MNObject alloc]init];
block = [^{
NSLog(@"----------%p",obj);
}copy];
[obj release];
}
block();
[block release];
--------------------
输出:
2019-03-09 21:59:56.673296+0800 Block-Demo[72692:8183596] MNObject - dealloc
2019-03-09 21:59:56.673520+0800 Block-Demo[72692:8183596] ----------0x0
```
上述代码,obj 是 __strong 修饰,但是并没有被 block 强引用!可见MRC环境下,__修饰的对象,生成的中间block对象不会对 auto变量产生强引用。
### Block的循环应用问题
传送门:[ 实际开发中-Block导致循环引用的问题(ARC环境下)](https://www.jianshu.com/p/fc2f4d207d25)
**考题:MRC 下,block的循环引用如何解决呢?**
- **方案1:unsafe_unretained**
MRC下,没有__weak,所以只能用_unsafe_unretained指针,原理和 weak 一样(ARC环境下不推荐使用,可能导致野指针,推荐使用weak)
```
__unsafe_unretained MNObject *weakSelf = self;
self.block = [^{
NSLog(@"----------%p",weakSelf);
}copy];
```
- **方案2: __block**
```
__block self;
self.block = [^{
NSLog(@"----------%p",self);
}copy];
```
why? 上面关于 __block的总结
> 特别注意!上述条件仅在ARC环境下生效,如果是MRC环境下,block不会对内部auto变量产生强引用!(MRC下不会进行retain操作)

- **方案3: 手动在block函数内将对象制空,并且必须手动保证block调用**
```
MNObject *obj = [[MNObject alloc]init];
__unsafe_unretained MNObject *weakObj = obj;
obj.block = [^{
NSLog(@"----------%p",obj);
obj = nil;
}copy];
obj.block();
```

但是这个一定要注意,block必须调用,因为对象指针的清空操作,是写在block函数中的,如果没调用block,循环引用问题还是会存在,所以不推荐使用。
实际开发中,循环引用的检测工具推荐,facebook开源的 [FBRetainCycleDetector](https://github.com/facebook/FBRetainCycleDetector),用过的都说好~
---
老实说,block其实非常难,能考得特别深,本文也只是简单探究&总结下中级iOS常见的block考题,以及对Block底层的初步探究,如果是像我所在的三线城市,去面试那种非一线公司的话,如果能掌握本文,可能block相关的题目能答个八九不离十吧!*(可能题目会变换组合,但是万变不离其宗)*
block的文章其实很多,但是如果要真的深入理解,还是得动手,这里推荐初中级iOSer可以跟着本文的思路,一步一步跟着探究试试,本文只是起个抛砖引玉的作用
---
友情演出:[小马哥MJ](https://github.com/CoderMJLee)
*参考资料*
[实际开发中-Block导致循环引用的问题(ARC环境下)](https://www.jianshu.com/p/fc2f4d207d25)
[招聘一个靠谱的 iOS](https://blog.sunnyxx.com/2015/07/04/ios-interview/)
[ChenYilong/iOSInterviewQuestions](https://github.com/ChenYilong/iOSInterviewQuestions/blob/master/01%E3%80%8A%E6%8B%9B%E8%81%98%E4%B8%80%E4%B8%AA%E9%9D%A0%E8%B0%B1%E7%9A%84iOS%E3%80%8B%E9%9D%A2%E8%AF%95%E9%A2%98%E5%8F%82%E8%80%83%E7%AD%94%E6%A1%88/%E3%80%8A%E6%8B%9B%E8%81%98%E4%B8%80%E4%B8%AA%E9%9D%A0%E8%B0%B1%E7%9A%84iOS%E3%80%8B%E9%9D%A2%E8%AF%95%E9%A2%98%E5%8F%82%E8%80%83%E7%AD%94%E6%A1%88%EF%BC%88%E4%B8%8B%EF%BC%89.md#45-addobserverforkeypathoptionscontext%E5%90%84%E4%B8%AA%E5%8F%82%E6%95%B0%E7%9A%84%E4%BD%9C%E7%94%A8%E5%88%86%E5%88%AB%E6%98%AF%E4%BB%80%E4%B9%88observer%E4%B8%AD%E9%9C%80%E8%A6%81%E5%AE%9E%E7%8E%B0%E5%93%AA%E4%B8%AA%E6%96%B9%E6%B3%95%E6%89%8D%E8%83%BD%E8%8E%B7%E5%BE%97kvo%E5%9B%9E%E8%B0%83)
================================================
FILE: InterView-obj-isa-class/InterView-obj-isa-class/NSObject+MNTest.h
================================================
//
// NSObject+MNTest.h
// InterView-obj-isa-class
//
// Created by 梁宇航 on 2019/1/20.
// Copyright © 2019年 梁宇航. All rights reserved.
//
#import
@interface NSObject (MNTest)
+ (void)checkSuperclass;
@end
================================================
FILE: InterView-obj-isa-class/InterView-obj-isa-class/NSObject+MNTest.m
================================================
//
// NSObject+MNTest.m
// InterView-obj-isa-class
//
// Created by 梁宇航 on 2019/1/20.
// Copyright © 2019年 梁宇航. All rights reserved.
//
#import "NSObject+MNTest.h"
@implementation NSObject (MNTest)
//+ (void)checkSuperclass{
// NSLog(@"+NSObject checkSuperclass - %p",self);
//}
- (void)checkSuperclass{
NSLog(@"-NSObject checkSuperclass - %p",self);
}
@end
================================================
FILE: InterView-obj-isa-class/InterView-obj-isa-class/main.m
================================================
//
// main.m
// InterView-obj-isa-class
//
// Created by 梁宇航 on 2019/1/20.
// Copyright © 2019年 梁宇航. All rights reserved.
//
#import
#import
#import "NSObject+MNTest.h"
@interface MNSuperclass : NSObject
- (void)superclassInstanceMethod;
+ (void)superClassMethod;
@end
@implementation MNSuperclass
- (void)superclassInstanceMethod{
NSLog(@"superclass-InstanceMethod - %p",self);
}
+ (void)superClassMethod{
NSLog(@"+ superClass-classMethod- %p",self);
}
@end
@interface MNSubclass : MNSuperclass
- (void)subclassInstanceMethod;
- (void)compareSelfWithSuperclass;
@end
@implementation MNSubclass
- (void)subclassInstanceMethod{
NSLog(@"subclassInstanceMethod- %p",self);
}
- (void)compareSelfWithSuperclass{
NSLog(@"self class = %@",[self class]);
NSLog(@"super class = %@",[super class]);
}
@end
int main(int argc, char * argv[]) {
@autoreleasepool
{
MNSubclass *subclass = [[MNSubclass alloc]init];
[subclass superclassInstanceMethod];
NSLog(@"subclass = %p, MNSubclass = %p",subclass,[MNSubclass class]);
[MNSubclass superClassMethod];
//检验 - root-meta-class的superclass 是否指向 root-class
[MNSubclass checkSuperclass];
NSLog(@"MNSubclass = %p",[MNSubclass class]);
//回答 - [self class] && [super class] 的答案
[subclass compareSelfWithSuperclass];
}
return 0;
}
================================================
FILE: InterView-obj-isa-class/InterView-obj-isa-class.xcodeproj/project.pbxproj
================================================
// !$*UTF8*$!
{
archiveVersion = 1;
classes = {
};
objectVersion = 50;
objects = {
/* Begin PBXBuildFile section */
A793EB6421F4CECA003661CD /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = A793EB6321F4CECA003661CD /* main.m */; };
A793EB6C21F4CEDF003661CD /* NSObject+MNTest.m in Sources */ = {isa = PBXBuildFile; fileRef = A793EB6A21F4CEDF003661CD /* NSObject+MNTest.m */; };
/* End PBXBuildFile section */
/* Begin PBXCopyFilesBuildPhase section */
A793EB5E21F4CECA003661CD /* CopyFiles */ = {
isa = PBXCopyFilesBuildPhase;
buildActionMask = 2147483647;
dstPath = /usr/share/man/man1/;
dstSubfolderSpec = 0;
files = (
);
runOnlyForDeploymentPostprocessing = 1;
};
/* End PBXCopyFilesBuildPhase section */
/* Begin PBXFileReference section */
A793EB6021F4CECA003661CD /* InterView-obj-isa-class */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = "InterView-obj-isa-class"; sourceTree = BUILT_PRODUCTS_DIR; };
A793EB6321F4CECA003661CD /* main.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = main.m; sourceTree = ""; };
A793EB6A21F4CEDF003661CD /* NSObject+MNTest.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "NSObject+MNTest.m"; sourceTree = ""; };
A793EB6B21F4CEDF003661CD /* NSObject+MNTest.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "NSObject+MNTest.h"; sourceTree = ""; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
A793EB5D21F4CECA003661CD /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
A793EB5721F4CECA003661CD = {
isa = PBXGroup;
children = (
A793EB6221F4CECA003661CD /* InterView-obj-isa-class */,
A793EB6121F4CECA003661CD /* Products */,
);
sourceTree = "";
};
A793EB6121F4CECA003661CD /* Products */ = {
isa = PBXGroup;
children = (
A793EB6021F4CECA003661CD /* InterView-obj-isa-class */,
);
name = Products;
sourceTree = "";
};
A793EB6221F4CECA003661CD /* InterView-obj-isa-class */ = {
isa = PBXGroup;
children = (
A793EB6B21F4CEDF003661CD /* NSObject+MNTest.h */,
A793EB6A21F4CEDF003661CD /* NSObject+MNTest.m */,
A793EB6321F4CECA003661CD /* main.m */,
);
path = "InterView-obj-isa-class";
sourceTree = "";
};
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
A793EB5F21F4CECA003661CD /* InterView-obj-isa-class */ = {
isa = PBXNativeTarget;
buildConfigurationList = A793EB6721F4CECA003661CD /* Build configuration list for PBXNativeTarget "InterView-obj-isa-class" */;
buildPhases = (
A793EB5C21F4CECA003661CD /* Sources */,
A793EB5D21F4CECA003661CD /* Frameworks */,
A793EB5E21F4CECA003661CD /* CopyFiles */,
);
buildRules = (
);
dependencies = (
);
name = "InterView-obj-isa-class";
productName = "InterView-obj-isa-class";
productReference = A793EB6021F4CECA003661CD /* InterView-obj-isa-class */;
productType = "com.apple.product-type.tool";
};
/* End PBXNativeTarget section */
/* Begin PBXProject section */
A793EB5821F4CECA003661CD /* Project object */ = {
isa = PBXProject;
attributes = {
LastUpgradeCheck = 0930;
ORGANIZATIONNAME = "梁宇航";
TargetAttributes = {
A793EB5F21F4CECA003661CD = {
CreatedOnToolsVersion = 9.3;
};
};
};
buildConfigurationList = A793EB5B21F4CECA003661CD /* Build configuration list for PBXProject "InterView-obj-isa-class" */;
compatibilityVersion = "Xcode 9.3";
developmentRegion = en;
hasScannedForEncodings = 0;
knownRegions = (
en,
);
mainGroup = A793EB5721F4CECA003661CD;
productRefGroup = A793EB6121F4CECA003661CD /* Products */;
projectDirPath = "";
projectRoot = "";
targets = (
A793EB5F21F4CECA003661CD /* InterView-obj-isa-class */,
);
};
/* End PBXProject section */
/* Begin PBXSourcesBuildPhase section */
A793EB5C21F4CECA003661CD /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
A793EB6C21F4CEDF003661CD /* NSObject+MNTest.m in Sources */,
A793EB6421F4CECA003661CD /* main.m in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXSourcesBuildPhase section */
/* Begin XCBuildConfiguration section */
A793EB6521F4CECA003661CD /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_ANALYZER_NONNULL = YES;
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++14";
CLANG_CXX_LIBRARY = "libc++";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_ENABLE_OBJC_WEAK = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
CODE_SIGN_IDENTITY = "-";
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = dwarf;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_TESTABILITY = YES;
GCC_C_LANGUAGE_STANDARD = gnu11;
GCC_DYNAMIC_NO_PIC = NO;
GCC_NO_COMMON_BLOCKS = YES;
GCC_OPTIMIZATION_LEVEL = 0;
GCC_PREPROCESSOR_DEFINITIONS = (
"DEBUG=1",
"$(inherited)",
);
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
MACOSX_DEPLOYMENT_TARGET = 10.13;
MTL_ENABLE_DEBUG_INFO = YES;
ONLY_ACTIVE_ARCH = YES;
SDKROOT = macosx;
};
name = Debug;
};
A793EB6621F4CECA003661CD /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_ANALYZER_NONNULL = YES;
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++14";
CLANG_CXX_LIBRARY = "libc++";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_ENABLE_OBJC_WEAK = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
CODE_SIGN_IDENTITY = "-";
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
ENABLE_NS_ASSERTIONS = NO;
ENABLE_STRICT_OBJC_MSGSEND = YES;
GCC_C_LANGUAGE_STANDARD = gnu11;
GCC_NO_COMMON_BLOCKS = YES;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
MACOSX_DEPLOYMENT_TARGET = 10.13;
MTL_ENABLE_DEBUG_INFO = NO;
SDKROOT = macosx;
};
name = Release;
};
A793EB6821F4CECA003661CD /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
CODE_SIGN_STYLE = Automatic;
PRODUCT_NAME = "$(TARGET_NAME)";
};
name = Debug;
};
A793EB6921F4CECA003661CD /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
CODE_SIGN_STYLE = Automatic;
PRODUCT_NAME = "$(TARGET_NAME)";
};
name = Release;
};
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
A793EB5B21F4CECA003661CD /* Build configuration list for PBXProject "InterView-obj-isa-class" */ = {
isa = XCConfigurationList;
buildConfigurations = (
A793EB6521F4CECA003661CD /* Debug */,
A793EB6621F4CECA003661CD /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
A793EB6721F4CECA003661CD /* Build configuration list for PBXNativeTarget "InterView-obj-isa-class" */ = {
isa = XCConfigurationList;
buildConfigurations = (
A793EB6821F4CECA003661CD /* Debug */,
A793EB6921F4CECA003661CD /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */
};
rootObject = A793EB5821F4CECA003661CD /* Project object */;
}
================================================
FILE: InterView-obj-isa-class/InterView-obj-isa-class.xcodeproj/project.xcworkspace/contents.xcworkspacedata
================================================
================================================
FILE: InterView-obj-isa-class/InterView-obj-isa-class.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist
================================================
IDEDidComputeMac32BitWarning
================================================
FILE: InterView-obj-isa-class/libmalloc-166.220.1/.clang-format
================================================
# Format of this file is YAML
# Minimum clang-format version required: clang-format version 3.6.0
# Detailed description of options available at http://clang.llvm.org/docs/ClangFormatStyleOptions.html
AlignEscapedNewlinesLeft: true
# Bad:
# void foo() {
# someFunction();
# someOtherFunction();
# }
# Good:
# void foo() {
# someFunction();
# someOtherFunction();
# }
AlignTrailingComments: true
# align all comments to right based of //
# == Avoid using // based comments altogether ==
AlignAfterOpenBracket: false
# don't align after a bracket, uses indentation rules to indent
AllowAllParametersOfDeclarationOnNextLine: false
# allow funtion definition as
# someFunction(foo,
# bar,
# baz);
AlignConsecutiveAssignments: false
# does not align consecutive assignments with '=' operator
AllowShortBlocksOnASingleLine: true
# single statement block can be merged on one line
# e.g if (a) { return; }
AllowShortCaseLabelsOnASingleLine: false
# Single statement case statements should be on their own lines
AllowShortFunctionsOnASingleLine: None
# Bad:
# int foo() { return 123; }
AllowShortIfStatementsOnASingleLine: false
# Bad:
# if (someOtherVar) return;
# Good:
# if (someOtherVar)
# return;
AllowShortLoopsOnASingleLine: false
# Bad:
# while(i>0) i--;
# Good:
# while(i>0) {
# i--;
# }
AlwaysBreakAfterDefinitionReturnType: true
# Ensures return type is one its own line
# e.g. unsigned int
# function(char param) { }
AlwaysBreakBeforeMultilineStrings: true
# multine strings should begin on new line
BinPackArguments: true
BinPackParameters: false
# functions arguments should all be on one line or have a single line for each param
BreakBeforeBinaryOperators: None
# break for new line after binary operator in case of length is over ColumnLimit
# e.g.
# int foo = bar +
# baz;
BreakBeforeBraces: Linux
# Always attach braces to surrounding context except -
# break before braces on function, namespace and class definitions
ColumnLimit: 132
# every body has wide screen now. 132 seems to be reasonable limit now.
ContinuationIndentWidth: 8
# indent continued lines by two tabs
IndentCaseLabels: false
# case labels have same indentation as switch statement.
IndentWidth: 4
# 4 spaces for indentation
TabWidth: 4
# tabwidth is 4 spaces
UseTab: Always
# always indent lines with tabs
IndentWrappedFunctionNames: false
KeepEmptyLinesAtTheStartOfBlocks: false
# remove excess empty lines at start of blocks.
PointerAlignment: Right
# "void *foo" (vs. "void* foo" or "void * foo")
SpaceAfterCStyleCast: false
# No space after (cast). E.g
# int blah = (int)((void *)foo + bar)
SpaceBeforeAssignmentOperators: true
# Assignment = should be seperated by spaces on both sides.
SpaceBeforeParens: ControlStatements
# for control statements a space is required before '{'
# Bad: for(){ statement; }
# Good: for() { statement; }
SpaceInEmptyParentheses: false
# No spaces required for empty ()
SpacesInCStyleCastParentheses: false
# No spaces required for (unsigned int) type cast
SpacesInParentheses: false
SpacesInSquareBrackets: false
# No spaces in [count] style invocations of []
================================================
FILE: InterView-obj-isa-class/libmalloc-166.220.1/.gitattributes
================================================
================================================
FILE: InterView-obj-isa-class/libmalloc-166.220.1/.gitignore
================================================
# /libmalloc.xcodeproj/
/libmalloc.xcodeproj/*.xcworkspace
/libmalloc.xcodeproj/xcuserdata
================================================
FILE: InterView-obj-isa-class/libmalloc-166.220.1/include/malloc/_malloc.h
================================================
/*
* Copyright (c) 2018 Apple Computer, Inc. All rights reserved.
*
* @APPLE_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apple Public Source License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. Please obtain a copy of the License at
* http://www.opensource.apple.com/apsl/ and read it before using this
* file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPLE_LICENSE_HEADER_END@
*/
#ifndef _MALLOC_UNDERSCORE_MALLOC_H_
#define _MALLOC_UNDERSCORE_MALLOC_H_
/*
* This header is included from , so the contents of this file have
* broad source compatibility and POSIX conformance implications.
* Be cautious about what is included and declared here.
*/
#include
#include
#include <_types.h>
#include
__BEGIN_DECLS
void *malloc(size_t __size) __result_use_check __alloc_size(1);
void *calloc(size_t __count, size_t __size) __result_use_check __alloc_size(1,2);
void free(void *);
void *realloc(void *__ptr, size_t __size) __result_use_check __alloc_size(2);
#if !defined(_ANSI_SOURCE) && (!defined(_POSIX_C_SOURCE) || defined(_DARWIN_C_SOURCE))
void *valloc(size_t) __alloc_size(1);
#endif // !defined(_ANSI_SOURCE) && (!defined(_POSIX_C_SOURCE) || defined(_DARWIN_C_SOURCE))
int posix_memalign(void **__memptr, size_t __alignment, size_t __size) __OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_3_0);
__END_DECLS
#endif /* _MALLOC_UNDERSCORE_MALLOC_H_ */
================================================
FILE: InterView-obj-isa-class/libmalloc-166.220.1/include/malloc/malloc.h
================================================
/*
* Copyright (c) 1999 Apple Computer, Inc. All rights reserved.
*
* @APPLE_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apple Public Source License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. Please obtain a copy of the License at
* http://www.opensource.apple.com/apsl/ and read it before using this
* file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPLE_LICENSE_HEADER_END@
*/
#ifndef _MALLOC_MALLOC_H_
#define _MALLOC_MALLOC_H_
#include
#include
#include
#include
#if __has_feature(ptrauth_calls)
#include
// Zone function pointer, type-diversified but not address-diversified (because
// the zone can be copied). Process-independent because the zone structure may
// be in the shared library cache.
#define MALLOC_ZONE_FN_PTR(fn) __ptrauth(ptrauth_key_process_independent_code, \
FALSE, ptrauth_string_discriminator("malloc_zone_fn." #fn)) fn
// Introspection function pointer, address- and type-diversified.
// Process-independent because the malloc_introspection_t structure that contains
// these pointers may be in the shared library cache.
#define MALLOC_INTROSPECT_FN_PTR(fn) __ptrauth(ptrauth_key_process_independent_code, \
TRUE, ptrauth_string_discriminator("malloc_introspect_fn." #fn)) fn
// Pointer to the introspection pointer table, type-diversified but not
// address-diversified (because the zone can be copied).
// Process-independent because the table pointer may be in the shared library cache.
#define MALLOC_INTROSPECT_TBL_PTR(ptr) __ptrauth(ptrauth_key_process_independent_data,\
FALSE, ptrauth_string_discriminator("malloc_introspect_tbl")) ptr
#endif // __has_feature(ptrauth_calls)
#ifndef MALLOC_ZONE_FN_PTR
#define MALLOC_ZONE_FN_PTR(fn) fn
#define MALLOC_INTROSPECT_FN_PTR(fn) fn
#define MALLOC_INTROSPECT_TBL_PTR(ptr) ptr
#endif // MALLOC_ZONE_FN_PTR
__BEGIN_DECLS
/********* Type definitions ************/
typedef struct _malloc_zone_t {
/* Only zone implementors should depend on the layout of this structure;
Regular callers should use the access functions below */
void *reserved1; /* RESERVED FOR CFAllocator DO NOT USE */
void *reserved2; /* RESERVED FOR CFAllocator DO NOT USE */
size_t (* MALLOC_ZONE_FN_PTR(size))(struct _malloc_zone_t *zone, const void *ptr); /* returns the size of a block or 0 if not in this zone; must be fast, especially for negative answers */
void *(* MALLOC_ZONE_FN_PTR(malloc))(struct _malloc_zone_t *zone, size_t size);
void *(* MALLOC_ZONE_FN_PTR(calloc))(struct _malloc_zone_t *zone, size_t num_items, size_t size); /* same as malloc, but block returned is set to zero */
void *(* MALLOC_ZONE_FN_PTR(valloc))(struct _malloc_zone_t *zone, size_t size); /* same as malloc, but block returned is set to zero and is guaranteed to be page aligned */
void (* MALLOC_ZONE_FN_PTR(free))(struct _malloc_zone_t *zone, void *ptr);
void *(* MALLOC_ZONE_FN_PTR(realloc))(struct _malloc_zone_t *zone, void *ptr, size_t size);
void (* MALLOC_ZONE_FN_PTR(destroy))(struct _malloc_zone_t *zone); /* zone is destroyed and all memory reclaimed */
const char *zone_name;
/* Optional batch callbacks; these may be NULL */
unsigned (* MALLOC_ZONE_FN_PTR(batch_malloc))(struct _malloc_zone_t *zone, size_t size, void **results, unsigned num_requested); /* given a size, returns pointers capable of holding that size; returns the number of pointers allocated (maybe 0 or less than num_requested) */
void (* MALLOC_ZONE_FN_PTR(batch_free))(struct _malloc_zone_t *zone, void **to_be_freed, unsigned num_to_be_freed); /* frees all the pointers in to_be_freed; note that to_be_freed may be overwritten during the process */
struct malloc_introspection_t * MALLOC_INTROSPECT_TBL_PTR(introspect);
unsigned version;
/* aligned memory allocation. The callback may be NULL. Present in version >= 5. */
void *(* MALLOC_ZONE_FN_PTR(memalign))(struct _malloc_zone_t *zone, size_t alignment, size_t size);
/* free a pointer known to be in zone and known to have the given size. The callback may be NULL. Present in version >= 6.*/
void (* MALLOC_ZONE_FN_PTR(free_definite_size))(struct _malloc_zone_t *zone, void *ptr, size_t size);
/* Empty out caches in the face of memory pressure. The callback may be NULL. Present in version >= 8. */
size_t (* MALLOC_ZONE_FN_PTR(pressure_relief))(struct _malloc_zone_t *zone, size_t goal);
/*
* Checks whether an address might belong to the zone. May be NULL. Present in version >= 10.
* False positives are allowed (e.g. the pointer was freed, or it's in zone space that has
* not yet been allocated. False negatives are not allowed.
*/
boolean_t (* MALLOC_ZONE_FN_PTR(claimed_address))(struct _malloc_zone_t *zone, void *ptr);
} malloc_zone_t;
/********* Creation and destruction ************/
extern malloc_zone_t *malloc_default_zone(void);
/* The initial zone */
extern malloc_zone_t *malloc_create_zone(vm_size_t start_size, unsigned flags);
/* Creates a new zone with default behavior and registers it */
extern void malloc_destroy_zone(malloc_zone_t *zone);
/* Destroys zone and everything it allocated */
/********* Block creation and manipulation ************/
extern void *malloc_zone_malloc(malloc_zone_t *zone, size_t size) __alloc_size(2);
/* Allocates a new pointer of size size; zone must be non-NULL */
extern void *malloc_zone_calloc(malloc_zone_t *zone, size_t num_items, size_t size) __alloc_size(2,3);
/* Allocates a new pointer of size num_items * size; block is cleared; zone must be non-NULL */
extern void *malloc_zone_valloc(malloc_zone_t *zone, size_t size) __alloc_size(2);
/* Allocates a new pointer of size size; zone must be non-NULL; Pointer is guaranteed to be page-aligned and block is cleared */
extern void malloc_zone_free(malloc_zone_t *zone, void *ptr);
/* Frees pointer in zone; zone must be non-NULL */
extern void *malloc_zone_realloc(malloc_zone_t *zone, void *ptr, size_t size) __alloc_size(3);
/* Enlarges block if necessary; zone must be non-NULL */
extern malloc_zone_t *malloc_zone_from_ptr(const void *ptr);
/* Returns the zone for a pointer, or NULL if not in any zone.
The ptr must have been returned from a malloc or realloc call. */
extern size_t malloc_size(const void *ptr);
/* Returns size of given ptr */
extern size_t malloc_good_size(size_t size);
/* Returns number of bytes greater than or equal to size that can be allocated without padding */
extern void *malloc_zone_memalign(malloc_zone_t *zone, size_t alignment, size_t size) __alloc_size(3) __OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_3_0);
/*
* Allocates a new pointer of size size whose address is an exact multiple of alignment.
* alignment must be a power of two and at least as large as sizeof(void *).
* zone must be non-NULL.
*/
/********* Batch methods ************/
extern unsigned malloc_zone_batch_malloc(malloc_zone_t *zone, size_t size, void **results, unsigned num_requested);
/* Allocates num blocks of the same size; Returns the number truly allocated (may be 0) */
extern void malloc_zone_batch_free(malloc_zone_t *zone, void **to_be_freed, unsigned num);
/* frees all the pointers in to_be_freed; note that to_be_freed may be overwritten during the process; This function will always free even if the zone has no batch callback */
/********* Functions for libcache ************/
extern malloc_zone_t *malloc_default_purgeable_zone(void) __OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_3_0);
/* Returns a pointer to the default purgeable_zone. */
extern void malloc_make_purgeable(void *ptr) __OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_3_0);
/* Make an allocation from the purgeable zone purgeable if possible. */
extern int malloc_make_nonpurgeable(void *ptr) __OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_3_0);
/* Makes an allocation from the purgeable zone nonpurgeable.
* Returns zero if the contents were not purged since the last
* call to malloc_make_purgeable, else returns non-zero. */
/********* Functions for zone implementors ************/
extern void malloc_zone_register(malloc_zone_t *zone);
/* Registers a custom malloc zone; Should typically be called after a
* malloc_zone_t has been filled in with custom methods by a client. See
* malloc_create_zone for creating additional malloc zones with the
* default allocation and free behavior. */
extern void malloc_zone_unregister(malloc_zone_t *zone);
/* De-registers a zone
Should typically be called before calling the zone destruction routine */
extern void malloc_set_zone_name(malloc_zone_t *zone, const char *name);
/* Sets the name of a zone */
extern const char *malloc_get_zone_name(malloc_zone_t *zone);
/* Returns the name of a zone */
size_t malloc_zone_pressure_relief(malloc_zone_t *zone, size_t goal) __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_4_3);
/* malloc_zone_pressure_relief() advises the malloc subsystem that the process is under memory pressure and
* that the subsystem should make its best effort towards releasing (i.e. munmap()-ing) "goal" bytes from "zone".
* If "goal" is passed as zero, the malloc subsystem will attempt to achieve maximal pressure relief in "zone".
* If "zone" is passed as NULL, all zones are examined for pressure relief opportunities.
* malloc_zone_pressure_relief() returns the number of bytes released.
*/
typedef struct {
vm_address_t address;
vm_size_t size;
} vm_range_t;
typedef struct malloc_statistics_t {
unsigned blocks_in_use;
size_t size_in_use;
size_t max_size_in_use; /* high water mark of touched memory */
size_t size_allocated; /* reserved in memory */
} malloc_statistics_t;
typedef kern_return_t memory_reader_t(task_t remote_task, vm_address_t remote_address, vm_size_t size, void **local_memory);
/* given a task, "reads" the memory at the given address and size
local_memory: set to a contiguous chunk of memory; validity of local_memory is assumed to be limited (until next call) */
#define MALLOC_PTR_IN_USE_RANGE_TYPE 1 /* for allocated pointers */
#define MALLOC_PTR_REGION_RANGE_TYPE 2 /* for region containing pointers */
#define MALLOC_ADMIN_REGION_RANGE_TYPE 4 /* for region used internally */
#define MALLOC_ZONE_SPECIFIC_FLAGS 0xff00 /* bits reserved for zone-specific purposes */
typedef void vm_range_recorder_t(task_t, void *, unsigned type, vm_range_t *, unsigned);
/* given a task and context, "records" the specified addresses */
typedef struct malloc_introspection_t {
kern_return_t (* MALLOC_INTROSPECT_FN_PTR(enumerator))(task_t task, void *, unsigned type_mask, vm_address_t zone_address, memory_reader_t reader, vm_range_recorder_t recorder); /* enumerates all the malloc pointers in use */
size_t (* MALLOC_INTROSPECT_FN_PTR(good_size))(malloc_zone_t *zone, size_t size);
boolean_t (* MALLOC_INTROSPECT_FN_PTR(check))(malloc_zone_t *zone); /* Consistency checker */
void (* MALLOC_INTROSPECT_FN_PTR(print))(malloc_zone_t *zone, boolean_t verbose); /* Prints zone */
void (* MALLOC_INTROSPECT_FN_PTR(log))(malloc_zone_t *zone, void *address); /* Enables logging of activity */
void (* MALLOC_INTROSPECT_FN_PTR(force_lock))(malloc_zone_t *zone); /* Forces locking zone */
void (* MALLOC_INTROSPECT_FN_PTR(force_unlock))(malloc_zone_t *zone); /* Forces unlocking zone */
void (* MALLOC_INTROSPECT_FN_PTR(statistics))(malloc_zone_t *zone, malloc_statistics_t *stats); /* Fills statistics */
boolean_t (* MALLOC_INTROSPECT_FN_PTR(zone_locked))(malloc_zone_t *zone); /* Are any zone locks held */
/* Discharge checking. Present in version >= 7. */
boolean_t (* MALLOC_INTROSPECT_FN_PTR(enable_discharge_checking))(malloc_zone_t *zone);
void (* MALLOC_INTROSPECT_FN_PTR(disable_discharge_checking))(malloc_zone_t *zone);
void (* MALLOC_INTROSPECT_FN_PTR(discharge))(malloc_zone_t *zone, void *memory);
#ifdef __BLOCKS__
void (* MALLOC_INTROSPECT_FN_PTR(enumerate_discharged_pointers))(malloc_zone_t *zone, void (^report_discharged)(void *memory, void *info));
#else
void *enumerate_unavailable_without_blocks;
#endif /* __BLOCKS__ */
void (* MALLOC_INTROSPECT_FN_PTR(reinit_lock))(malloc_zone_t *zone); /* Reinitialize zone locks, called only from atfork_child handler. Present in version >= 9. */
} malloc_introspection_t;
extern void malloc_printf(const char *format, ...);
/* Convenience for logging errors and warnings;
No allocation is performed during execution of this function;
Only understands usual %p %d %s formats, and %y that expresses a number of bytes (5b,10KB,1MB...)
*/
/********* Functions for performance tools ************/
extern kern_return_t malloc_get_all_zones(task_t task, memory_reader_t reader, vm_address_t **addresses, unsigned *count);
/* Fills addresses and count with the addresses of the zones in task;
Note that the validity of the addresses returned correspond to the validity of the memory returned by reader */
/********* Debug helpers ************/
extern void malloc_zone_print_ptr_info(void *ptr);
/* print to stdout if this pointer is in the malloc heap, free status, and size */
extern boolean_t malloc_zone_check(malloc_zone_t *zone);
/* Checks zone is well formed; if !zone, checks all zones */
extern void malloc_zone_print(malloc_zone_t *zone, boolean_t verbose);
/* Prints summary on zone; if !zone, prints all zones */
extern void malloc_zone_statistics(malloc_zone_t *zone, malloc_statistics_t *stats);
/* Fills statistics for zone; if !zone, sums up all zones */
extern void malloc_zone_log(malloc_zone_t *zone, void *address);
/* Controls logging of all activity; if !zone, for all zones;
If address==0 nothing is logged;
If address==-1 all activity is logged;
Else only the activity regarding address is logged */
struct mstats {
size_t bytes_total;
size_t chunks_used;
size_t bytes_used;
size_t chunks_free;
size_t bytes_free;
};
extern struct mstats mstats(void);
extern boolean_t malloc_zone_enable_discharge_checking(malloc_zone_t *zone) __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_4_3);
/* Increment the discharge checking enabled counter for a zone. Returns true if the zone supports checking, false if it does not. */
extern void malloc_zone_disable_discharge_checking(malloc_zone_t *zone) __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_4_3);
/* Decrement the discharge checking enabled counter for a zone. */
extern void malloc_zone_discharge(malloc_zone_t *zone, void *memory) __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_4_3);
/* Register memory that the programmer expects to be freed soon.
zone may be NULL in which case the zone is determined using malloc_zone_from_ptr().
If discharge checking is off for the zone this function is a no-op. */
#ifdef __BLOCKS__
extern void malloc_zone_enumerate_discharged_pointers(malloc_zone_t *zone, void (^report_discharged)(void *memory, void *info)) __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_4_3);
/* Calls report_discharged for each block that was registered using malloc_zone_discharge() but has not yet been freed.
info is used to provide zone defined information about the memory block.
If zone is NULL then the enumeration covers all zones. */
#else
extern void malloc_zone_enumerate_discharged_pointers(malloc_zone_t *zone, void *) __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_4_3);
#endif /* __BLOCKS__ */
__END_DECLS
#endif /* _MALLOC_MALLOC_H_ */
================================================
FILE: InterView-obj-isa-class/libmalloc-166.220.1/libmalloc.xcodeproj/project.pbxproj
================================================
// !$*UTF8*$!
{
archiveVersion = 1;
classes = {
};
objectVersion = 46;
objects = {
/* Begin PBXAggregateTarget section */
3FE9201116A9111000D1238A /* libmalloc */ = {
isa = PBXAggregateTarget;
buildConfigurationList = 3FE9201216A9111000D1238A /* Build configuration list for PBXAggregateTarget "libmalloc" */;
buildPhases = (
3FC1927C16DD946500315C26 /* Install Man Pages */,
3FE9201D16A9143E00D1238A /* Sanitise Headers (rdar://problem/10241868) */,
);
dependencies = (
C0CE45501C52CCBD00C24048 /* PBXTargetDependency */,
3FE9201816A9111600D1238A /* PBXTargetDependency */,
3FE9201616A9111400D1238A /* PBXTargetDependency */,
);
name = libmalloc;
productName = libmalloc;
};
45039161198FFF73004EE2A3 /* libmalloc_test */ = {
isa = PBXAggregateTarget;
buildConfigurationList = 45039162198FFF73004EE2A3 /* Build configuration list for PBXAggregateTarget "libmalloc_test" */;
buildPhases = (
);
dependencies = (
45039168198FFFA6004EE2A3 /* PBXTargetDependency */,
925383D91BD03D0000F745DB /* PBXTargetDependency */,
);
name = libmalloc_test;
productName = libmalloc_test;
};
B60A57932009307E006215CB /* executables */ = {
isa = PBXAggregateTarget;
buildConfigurationList = B60A57962009307E006215CB /* Build configuration list for PBXAggregateTarget "executables" */;
buildPhases = (
);
dependencies = (
B60A579820093093006215CB /* PBXTargetDependency */,
);
name = executables;
productName = executables;
};
/* End PBXAggregateTarget section */
/* Begin PBXBuildFile section */
084F5E841D50204F006CD296 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 084F5E831D50204F006CD296 /* Foundation.framework */; };
084F5E851D502102006CD296 /* radix_tree_debug.c in Sources */ = {isa = PBXBuildFile; fileRef = 08C28B3A1D501ACC000AE997 /* radix_tree_debug.c */; };
088C4D771D1AF049005C6B36 /* radix_tree.c in Sources */ = {isa = PBXBuildFile; fileRef = 088C4D741D1AEFB5005C6B36 /* radix_tree.c */; };
088C4D841D1AF16F005C6B36 /* radix_tree.c in Sources */ = {isa = PBXBuildFile; fileRef = 088C4D741D1AEFB5005C6B36 /* radix_tree.c */; };
08FEED021D501F6B00BE8A69 /* radix_tree_main.m in Sources */ = {isa = PBXBuildFile; fileRef = 08C28B421D501D2C000AE997 /* radix_tree_main.m */; };
0D468DCF1C7BEF51006FACF5 /* magazine_lite.c in Sources */ = {isa = PBXBuildFile; fileRef = 0D468DCC1C7BEE56006FACF5 /* magazine_lite.c */; };
0D468DD01C7BEF71006FACF5 /* stack_logging_internal.h in Headers */ = {isa = PBXBuildFile; fileRef = 0D468DCD1C7BEE65006FACF5 /* stack_logging_internal.h */; };
2B67B5682040B3AF0003E78F /* _malloc.h in Headers */ = {isa = PBXBuildFile; fileRef = 2B67B5672040B3A50003E78F /* _malloc.h */; settings = {ATTRIBUTES = (Public, ); }; };
3D157E7420354E02001630BF /* perfdata.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 3D157E7320354E02001630BF /* perfdata.framework */; };
3FE91FED16A90B9200D1238A /* bitarray.c in Sources */ = {isa = PBXBuildFile; fileRef = 3FE91FD116A90A8D00D1238A /* bitarray.c */; };
3FE91FF016A90B9200D1238A /* magazine_malloc.c in Sources */ = {isa = PBXBuildFile; fileRef = 3FE91FD616A90A8D00D1238A /* magazine_malloc.c */; };
3FE91FF116A90B9200D1238A /* magmallocProvider.d in Sources */ = {isa = PBXBuildFile; fileRef = 3FE91FD716A90A8D00D1238A /* magmallocProvider.d */; };
3FE91FF216A90B9200D1238A /* malloc.c in Sources */ = {isa = PBXBuildFile; fileRef = 3FE91FD816A90A8D00D1238A /* malloc.c */; };
3FE91FF416A90B9200D1238A /* nano_malloc.c in Sources */ = {isa = PBXBuildFile; fileRef = 3FE91FDA16A90A8D00D1238A /* nano_malloc.c */; };
3FE91FF616A90B9200D1238A /* stack_logging_disk.c in Sources */ = {isa = PBXBuildFile; fileRef = 3FE91FDC16A90A8D00D1238A /* stack_logging_disk.c */; };
3FE91FFA16A90BEF00D1238A /* malloc.h in Headers */ = {isa = PBXBuildFile; fileRef = 3FE91FF916A90BEF00D1238A /* malloc.h */; settings = {ATTRIBUTES = (Public, ); }; };
3FE91FFF16A9109E00D1238A /* bitarray.c in Sources */ = {isa = PBXBuildFile; fileRef = 3FE91FD116A90A8D00D1238A /* bitarray.c */; };
3FE9200116A9109E00D1238A /* magazine_malloc.c in Sources */ = {isa = PBXBuildFile; fileRef = 3FE91FD616A90A8D00D1238A /* magazine_malloc.c */; };
3FE9200216A9109E00D1238A /* magmallocProvider.d in Sources */ = {isa = PBXBuildFile; fileRef = 3FE91FD716A90A8D00D1238A /* magmallocProvider.d */; };
3FE9200316A9109E00D1238A /* malloc.c in Sources */ = {isa = PBXBuildFile; fileRef = 3FE91FD816A90A8D00D1238A /* malloc.c */; };
3FE9200416A9109E00D1238A /* nano_malloc.c in Sources */ = {isa = PBXBuildFile; fileRef = 3FE91FDA16A90A8D00D1238A /* nano_malloc.c */; };
3FE9200616A9109E00D1238A /* stack_logging_disk.c in Sources */ = {isa = PBXBuildFile; fileRef = 3FE91FDC16A90A8D00D1238A /* stack_logging_disk.c */; };
925383DA1BD03D5100F745DB /* stress_test.c in Sources */ = {isa = PBXBuildFile; fileRef = 925383D11BD03B4A00F745DB /* stress_test.c */; };
B61341DE20114B660038D163 /* ktrace.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = B61341DD20114B070038D163 /* ktrace.framework */; };
B629CF28202BA149007719B9 /* nanov2_malloc.c in Sources */ = {isa = PBXBuildFile; fileRef = B68B7FA41FCDD9A500BAD1AA /* nanov2_malloc.c */; };
B629CF2D202BB337007719B9 /* radix_tree.c in Sources */ = {isa = PBXBuildFile; fileRef = 088C4D741D1AEFB5005C6B36 /* radix_tree.c */; };
B629CF2E202BB337007719B9 /* bitarray.c in Sources */ = {isa = PBXBuildFile; fileRef = 3FE91FD116A90A8D00D1238A /* bitarray.c */; };
B629CF2F202BB337007719B9 /* purgeable_malloc.c in Sources */ = {isa = PBXBuildFile; fileRef = C957429E1BF681B00027269A /* purgeable_malloc.c */; };
B629CF30202BB337007719B9 /* magazine_large.c in Sources */ = {isa = PBXBuildFile; fileRef = C957429B1BF672F80027269A /* magazine_large.c */; };
B629CF31202BB337007719B9 /* magazine_malloc.c in Sources */ = {isa = PBXBuildFile; fileRef = 3FE91FD616A90A8D00D1238A /* magazine_malloc.c */; };
B629CF32202BB337007719B9 /* empty.s in Sources */ = {isa = PBXBuildFile; fileRef = C9ABCA041CB6FC6800ECB399 /* empty.s */; };
B629CF33202BB337007719B9 /* magazine_small.c in Sources */ = {isa = PBXBuildFile; fileRef = C95742981BF670D00027269A /* magazine_small.c */; };
B629CF34202BB337007719B9 /* legacy_malloc.c in Sources */ = {isa = PBXBuildFile; fileRef = C95742AA1BF685CB0027269A /* legacy_malloc.c */; };
B629CF35202BB337007719B9 /* magmallocProvider.d in Sources */ = {isa = PBXBuildFile; fileRef = 3FE91FD716A90A8D00D1238A /* magmallocProvider.d */; };
B629CF36202BB337007719B9 /* malloc.c in Sources */ = {isa = PBXBuildFile; fileRef = 3FE91FD816A90A8D00D1238A /* malloc.c */; };
B629CF37202BB337007719B9 /* frozen_malloc.c in Sources */ = {isa = PBXBuildFile; fileRef = C95742A41BF6842F0027269A /* frozen_malloc.c */; };
B629CF38202BB337007719B9 /* nanov2_malloc.c in Sources */ = {isa = PBXBuildFile; fileRef = B68B7FA41FCDD9A500BAD1AA /* nanov2_malloc.c */; };
B629CF39202BB337007719B9 /* nano_malloc.c in Sources */ = {isa = PBXBuildFile; fileRef = 3FE91FDA16A90A8D00D1238A /* nano_malloc.c */; };
B629CF3A202BB337007719B9 /* stack_logging_disk.c in Sources */ = {isa = PBXBuildFile; fileRef = 3FE91FDC16A90A8D00D1238A /* stack_logging_disk.c */; };
B629CF3B202BB337007719B9 /* magazine_tiny.c in Sources */ = {isa = PBXBuildFile; fileRef = C957428F1BF419DF0027269A /* magazine_tiny.c */; };
B629CF3C202BB337007719B9 /* nano_malloc_common.c in Sources */ = {isa = PBXBuildFile; fileRef = B68B7F9D1FCDCBC600BAD1AA /* nano_malloc_common.c */; };
B65FBE2C2087AA2F00E21F59 /* malloc_printf.c in Sources */ = {isa = PBXBuildFile; fileRef = B65FBE2B2087AA2F00E21F59 /* malloc_printf.c */; };
B66C71D92034BFAE0047E265 /* malloc_common.h in Headers */ = {isa = PBXBuildFile; fileRef = B66C71D72034BFAE0047E265 /* malloc_common.h */; };
B66C71DA2034BFAE0047E265 /* malloc_common.c in Sources */ = {isa = PBXBuildFile; fileRef = B66C71D82034BFAE0047E265 /* malloc_common.c */; };
B66C71DB2034BFD30047E265 /* malloc_common.c in Sources */ = {isa = PBXBuildFile; fileRef = B66C71D82034BFAE0047E265 /* malloc_common.c */; };
B66C71DC2034BFD40047E265 /* malloc_common.c in Sources */ = {isa = PBXBuildFile; fileRef = B66C71D82034BFAE0047E265 /* malloc_common.c */; };
B68B7F9E1FCDCBC600BAD1AA /* nano_malloc_common.h in Headers */ = {isa = PBXBuildFile; fileRef = B68B7F9C1FCDCBC600BAD1AA /* nano_malloc_common.h */; };
B68B7F9F1FCDCBC600BAD1AA /* nano_malloc_common.c in Sources */ = {isa = PBXBuildFile; fileRef = B68B7F9D1FCDCBC600BAD1AA /* nano_malloc_common.c */; };
B68B7FA01FCDCBE700BAD1AA /* nano_malloc_common.c in Sources */ = {isa = PBXBuildFile; fileRef = B68B7F9D1FCDCBC600BAD1AA /* nano_malloc_common.c */; };
B68B7FA11FCDCBE800BAD1AA /* nano_malloc_common.c in Sources */ = {isa = PBXBuildFile; fileRef = B68B7F9D1FCDCBC600BAD1AA /* nano_malloc_common.c */; };
B68B7FA31FCDD67100BAD1AA /* nanov2_malloc.h in Headers */ = {isa = PBXBuildFile; fileRef = B68B7FA21FCDD60F00BAD1AA /* nanov2_malloc.h */; };
B68B7FA51FCDD9A500BAD1AA /* nanov2_malloc.c in Sources */ = {isa = PBXBuildFile; fileRef = B68B7FA41FCDD9A500BAD1AA /* nanov2_malloc.c */; };
B68B7FA61FCDD9B200BAD1AA /* nanov2_malloc.c in Sources */ = {isa = PBXBuildFile; fileRef = B68B7FA41FCDD9A500BAD1AA /* nanov2_malloc.c */; };
B68B7FA71FCDD9B200BAD1AA /* nanov2_malloc.c in Sources */ = {isa = PBXBuildFile; fileRef = B68B7FA41FCDD9A500BAD1AA /* nanov2_malloc.c */; };
B6910F67202B630D00FF2EB0 /* radix_tree.c in Sources */ = {isa = PBXBuildFile; fileRef = 088C4D741D1AEFB5005C6B36 /* radix_tree.c */; };
B6910F68202B630D00FF2EB0 /* bitarray.c in Sources */ = {isa = PBXBuildFile; fileRef = 3FE91FD116A90A8D00D1238A /* bitarray.c */; };
B6910F69202B630D00FF2EB0 /* purgeable_malloc.c in Sources */ = {isa = PBXBuildFile; fileRef = C957429E1BF681B00027269A /* purgeable_malloc.c */; };
B6910F6A202B630D00FF2EB0 /* magazine_large.c in Sources */ = {isa = PBXBuildFile; fileRef = C957429B1BF672F80027269A /* magazine_large.c */; };
B6910F6B202B630D00FF2EB0 /* magazine_malloc.c in Sources */ = {isa = PBXBuildFile; fileRef = 3FE91FD616A90A8D00D1238A /* magazine_malloc.c */; };
B6910F6C202B630D00FF2EB0 /* empty.s in Sources */ = {isa = PBXBuildFile; fileRef = C9ABCA041CB6FC6800ECB399 /* empty.s */; };
B6910F6D202B630D00FF2EB0 /* magazine_small.c in Sources */ = {isa = PBXBuildFile; fileRef = C95742981BF670D00027269A /* magazine_small.c */; };
B6910F6E202B630D00FF2EB0 /* legacy_malloc.c in Sources */ = {isa = PBXBuildFile; fileRef = C95742AA1BF685CB0027269A /* legacy_malloc.c */; };
B6910F6F202B630D00FF2EB0 /* magmallocProvider.d in Sources */ = {isa = PBXBuildFile; fileRef = 3FE91FD716A90A8D00D1238A /* magmallocProvider.d */; };
B6910F70202B630D00FF2EB0 /* malloc.c in Sources */ = {isa = PBXBuildFile; fileRef = 3FE91FD816A90A8D00D1238A /* malloc.c */; };
B6910F71202B630D00FF2EB0 /* frozen_malloc.c in Sources */ = {isa = PBXBuildFile; fileRef = C95742A41BF6842F0027269A /* frozen_malloc.c */; };
B6910F73202B630D00FF2EB0 /* nano_malloc.c in Sources */ = {isa = PBXBuildFile; fileRef = 3FE91FDA16A90A8D00D1238A /* nano_malloc.c */; };
B6910F74202B630D00FF2EB0 /* stack_logging_disk.c in Sources */ = {isa = PBXBuildFile; fileRef = 3FE91FDC16A90A8D00D1238A /* stack_logging_disk.c */; };
B6910F75202B630D00FF2EB0 /* magazine_tiny.c in Sources */ = {isa = PBXBuildFile; fileRef = C957428F1BF419DF0027269A /* magazine_tiny.c */; };
B6910F76202B630D00FF2EB0 /* nano_malloc_common.c in Sources */ = {isa = PBXBuildFile; fileRef = B68B7F9D1FCDCBC600BAD1AA /* nano_malloc_common.c */; };
B6CA644E1FCE2C1900DEBA12 /* nanov2_zone.h in Headers */ = {isa = PBXBuildFile; fileRef = B6CA644D1FCE2C0A00DEBA12 /* nanov2_zone.h */; };
B6CA644F1FCE2C1A00DEBA12 /* nanov2_zone.h in Headers */ = {isa = PBXBuildFile; fileRef = B6CA644D1FCE2C0A00DEBA12 /* nanov2_zone.h */; };
B6CA64501FCE2C1B00DEBA12 /* nanov2_zone.h in Headers */ = {isa = PBXBuildFile; fileRef = B6CA644D1FCE2C0A00DEBA12 /* nanov2_zone.h */; };
B6CA64521FCF1AD200DEBA12 /* nano_zone_common.h in Headers */ = {isa = PBXBuildFile; fileRef = B6CA64511FCF1AAD00DEBA12 /* nano_zone_common.h */; };
B6CA64531FCF1AD400DEBA12 /* nano_zone_common.h in Headers */ = {isa = PBXBuildFile; fileRef = B6CA64511FCF1AAD00DEBA12 /* nano_zone_common.h */; };
B6CA64541FCF1AD400DEBA12 /* nano_zone_common.h in Headers */ = {isa = PBXBuildFile; fileRef = B6CA64511FCF1AAD00DEBA12 /* nano_zone_common.h */; };
B6D2ED572007D91A007AF994 /* malloc_replay.cpp in Sources */ = {isa = PBXBuildFile; fileRef = B6D2ED552007D91A007AF994 /* malloc_replay.cpp */; };
B6D5C7F1202E26F80035E376 /* resolver.c in Sources */ = {isa = PBXBuildFile; fileRef = B6D5C7ED202E26CA0035E376 /* resolver.c */; };
B6D5C7F2202E26F80035E376 /* resolver.c in Sources */ = {isa = PBXBuildFile; fileRef = B6D5C7ED202E26CA0035E376 /* resolver.c */; };
B6D5C7F3202E26F90035E376 /* resolver.c in Sources */ = {isa = PBXBuildFile; fileRef = B6D5C7ED202E26CA0035E376 /* resolver.c */; };
B6D5C7F4202E26F90035E376 /* resolver.c in Sources */ = {isa = PBXBuildFile; fileRef = B6D5C7ED202E26CA0035E376 /* resolver.c */; };
B6D5C7F5202E26FA0035E376 /* resolver.c in Sources */ = {isa = PBXBuildFile; fileRef = B6D5C7ED202E26CA0035E376 /* resolver.c */; };
C0352EC71C3F3C4400DB5126 /* malloc_private.h in Headers */ = {isa = PBXBuildFile; fileRef = C0352EC61C3F3C3600DB5126 /* malloc_private.h */; settings = {ATTRIBUTES = (Private, ); }; };
C0CE45311C52C90500C24048 /* bitarray.c in Sources */ = {isa = PBXBuildFile; fileRef = 3FE91FD116A90A8D00D1238A /* bitarray.c */; };
C0CE45321C52C90500C24048 /* purgeable_malloc.c in Sources */ = {isa = PBXBuildFile; fileRef = C957429E1BF681B00027269A /* purgeable_malloc.c */; };
C0CE45331C52C90500C24048 /* magazine_large.c in Sources */ = {isa = PBXBuildFile; fileRef = C957429B1BF672F80027269A /* magazine_large.c */; };
C0CE45341C52C90500C24048 /* magazine_malloc.c in Sources */ = {isa = PBXBuildFile; fileRef = 3FE91FD616A90A8D00D1238A /* magazine_malloc.c */; };
C0CE45351C52C90500C24048 /* magazine_small.c in Sources */ = {isa = PBXBuildFile; fileRef = C95742981BF670D00027269A /* magazine_small.c */; };
C0CE45361C52C90500C24048 /* legacy_malloc.c in Sources */ = {isa = PBXBuildFile; fileRef = C95742AA1BF685CB0027269A /* legacy_malloc.c */; };
C0CE45371C52C90500C24048 /* magmallocProvider.d in Sources */ = {isa = PBXBuildFile; fileRef = 3FE91FD716A90A8D00D1238A /* magmallocProvider.d */; };
C0CE45381C52C90500C24048 /* malloc.c in Sources */ = {isa = PBXBuildFile; fileRef = 3FE91FD816A90A8D00D1238A /* malloc.c */; };
C0CE45391C52C90500C24048 /* frozen_malloc.c in Sources */ = {isa = PBXBuildFile; fileRef = C95742A41BF6842F0027269A /* frozen_malloc.c */; };
C0CE453A1C52C90500C24048 /* nano_malloc.c in Sources */ = {isa = PBXBuildFile; fileRef = 3FE91FDA16A90A8D00D1238A /* nano_malloc.c */; };
C0CE453C1C52C90500C24048 /* stack_logging_disk.c in Sources */ = {isa = PBXBuildFile; fileRef = 3FE91FDC16A90A8D00D1238A /* stack_logging_disk.c */; };
C0CE453D1C52C90500C24048 /* magazine_tiny.c in Sources */ = {isa = PBXBuildFile; fileRef = C957428F1BF419DF0027269A /* magazine_tiny.c */; };
C0CE45401C52C90500C24048 /* magazine_inline.h in Headers */ = {isa = PBXBuildFile; fileRef = C95742921BF41C970027269A /* magazine_inline.h */; };
C0CE45411C52C90500C24048 /* nano_zone.h in Headers */ = {isa = PBXBuildFile; fileRef = C957427E1BF33D130027269A /* nano_zone.h */; };
C0CE45421C52C90500C24048 /* thresholds.h in Headers */ = {isa = PBXBuildFile; fileRef = C957428C1BF411330027269A /* thresholds.h */; };
C0CE45431C52C90500C24048 /* debug.h in Headers */ = {isa = PBXBuildFile; fileRef = C957427B1BF2C8DE0027269A /* debug.h */; };
C0CE45441C52C90500C24048 /* frozen_malloc.h in Headers */ = {isa = PBXBuildFile; fileRef = C95742A51BF6842F0027269A /* frozen_malloc.h */; };
C0CE45451C52C90500C24048 /* magazine_zone.h in Headers */ = {isa = PBXBuildFile; fileRef = C95742861BF3F9550027269A /* magazine_zone.h */; };
C0CE45461C52C90500C24048 /* magazine_malloc.h in Headers */ = {isa = PBXBuildFile; fileRef = C95742951BF41E480027269A /* magazine_malloc.h */; };
C0CE45471C52C90500C24048 /* purgeable_malloc.h in Headers */ = {isa = PBXBuildFile; fileRef = C957429F1BF681B00027269A /* purgeable_malloc.h */; };
C0CE45481C52C90500C24048 /* base.h in Headers */ = {isa = PBXBuildFile; fileRef = C95742891BF3FD290027269A /* base.h */; };
C0CE454E1C52C9E600C24048 /* libmalloc.a in CopyFiles */ = {isa = PBXBuildFile; fileRef = C0CE454C1C52C90500C24048 /* libmalloc.a */; };
C932D2681D6B8D840063B19E /* vm.c in Sources */ = {isa = PBXBuildFile; fileRef = C932D2661D6B8D840063B19E /* vm.c */; };
C932D2691D6B8D840063B19E /* vm.h in Headers */ = {isa = PBXBuildFile; fileRef = C932D2671D6B8D840063B19E /* vm.h */; };
C938BBD31C74F7A400522BBD /* trace.h in Headers */ = {isa = PBXBuildFile; fileRef = C938BBD21C74F7A400522BBD /* trace.h */; };
C9571C3A1C18AA1D00A67EE3 /* stack_logging.h in Headers */ = {isa = PBXBuildFile; fileRef = C9571C391C18AA1D00A67EE3 /* stack_logging.h */; settings = {ATTRIBUTES = (Private, ); }; };
C95742721BF2C2880027269A /* bitarray.h in Headers */ = {isa = PBXBuildFile; fileRef = 3FE91FD216A90A8D00D1238A /* bitarray.h */; };
C95742731BF2C2880027269A /* internal.h in Headers */ = {isa = PBXBuildFile; fileRef = C957426D1BF2C0C80027269A /* internal.h */; };
C95742741BF2C2880027269A /* locking.h in Headers */ = {isa = PBXBuildFile; fileRef = C957426E1BF2C1480027269A /* locking.h */; };
C95742751BF2C2880027269A /* printf.h in Headers */ = {isa = PBXBuildFile; fileRef = 3FE91FD916A90A8D00D1238A /* printf.h */; };
C95742761BF2C2880027269A /* platform.h in Headers */ = {isa = PBXBuildFile; fileRef = C9F77BBA1BF2B84800812E13 /* platform.h */; };
C95742771BF2C2880027269A /* legacy_malloc.h in Headers */ = {isa = PBXBuildFile; fileRef = 3FE91FFB16A90E6C00D1238A /* legacy_malloc.h */; };
C957427A1BF2C67E0027269A /* nano_malloc.h in Headers */ = {isa = PBXBuildFile; fileRef = C95742791BF2C5F40027269A /* nano_malloc.h */; };
C957427C1BF2C8DE0027269A /* debug.h in Headers */ = {isa = PBXBuildFile; fileRef = C957427B1BF2C8DE0027269A /* debug.h */; };
C957427D1BF2C8DE0027269A /* debug.h in Headers */ = {isa = PBXBuildFile; fileRef = C957427B1BF2C8DE0027269A /* debug.h */; };
C957427F1BF33D130027269A /* nano_zone.h in Headers */ = {isa = PBXBuildFile; fileRef = C957427E1BF33D130027269A /* nano_zone.h */; };
C95742801BF33D130027269A /* nano_zone.h in Headers */ = {isa = PBXBuildFile; fileRef = C957427E1BF33D130027269A /* nano_zone.h */; };
C95742871BF3F9550027269A /* magazine_zone.h in Headers */ = {isa = PBXBuildFile; fileRef = C95742861BF3F9550027269A /* magazine_zone.h */; };
C95742881BF3F9550027269A /* magazine_zone.h in Headers */ = {isa = PBXBuildFile; fileRef = C95742861BF3F9550027269A /* magazine_zone.h */; };
C957428A1BF3FD290027269A /* base.h in Headers */ = {isa = PBXBuildFile; fileRef = C95742891BF3FD290027269A /* base.h */; };
C957428B1BF3FD290027269A /* base.h in Headers */ = {isa = PBXBuildFile; fileRef = C95742891BF3FD290027269A /* base.h */; };
C957428D1BF411330027269A /* thresholds.h in Headers */ = {isa = PBXBuildFile; fileRef = C957428C1BF411330027269A /* thresholds.h */; };
C957428E1BF411330027269A /* thresholds.h in Headers */ = {isa = PBXBuildFile; fileRef = C957428C1BF411330027269A /* thresholds.h */; };
C95742901BF419DF0027269A /* magazine_tiny.c in Sources */ = {isa = PBXBuildFile; fileRef = C957428F1BF419DF0027269A /* magazine_tiny.c */; };
C95742911BF419DF0027269A /* magazine_tiny.c in Sources */ = {isa = PBXBuildFile; fileRef = C957428F1BF419DF0027269A /* magazine_tiny.c */; };
C95742931BF41C970027269A /* magazine_inline.h in Headers */ = {isa = PBXBuildFile; fileRef = C95742921BF41C970027269A /* magazine_inline.h */; };
C95742941BF41C970027269A /* magazine_inline.h in Headers */ = {isa = PBXBuildFile; fileRef = C95742921BF41C970027269A /* magazine_inline.h */; };
C95742961BF41E480027269A /* magazine_malloc.h in Headers */ = {isa = PBXBuildFile; fileRef = C95742951BF41E480027269A /* magazine_malloc.h */; };
C95742971BF41E480027269A /* magazine_malloc.h in Headers */ = {isa = PBXBuildFile; fileRef = C95742951BF41E480027269A /* magazine_malloc.h */; };
C95742991BF670D00027269A /* magazine_small.c in Sources */ = {isa = PBXBuildFile; fileRef = C95742981BF670D00027269A /* magazine_small.c */; };
C957429A1BF670D00027269A /* magazine_small.c in Sources */ = {isa = PBXBuildFile; fileRef = C95742981BF670D00027269A /* magazine_small.c */; };
C957429C1BF672F80027269A /* magazine_large.c in Sources */ = {isa = PBXBuildFile; fileRef = C957429B1BF672F80027269A /* magazine_large.c */; };
C957429D1BF672F80027269A /* magazine_large.c in Sources */ = {isa = PBXBuildFile; fileRef = C957429B1BF672F80027269A /* magazine_large.c */; };
C95742A01BF681B00027269A /* purgeable_malloc.c in Sources */ = {isa = PBXBuildFile; fileRef = C957429E1BF681B00027269A /* purgeable_malloc.c */; };
C95742A11BF681B00027269A /* purgeable_malloc.c in Sources */ = {isa = PBXBuildFile; fileRef = C957429E1BF681B00027269A /* purgeable_malloc.c */; };
C95742A21BF681B00027269A /* purgeable_malloc.h in Headers */ = {isa = PBXBuildFile; fileRef = C957429F1BF681B00027269A /* purgeable_malloc.h */; };
C95742A31BF681B00027269A /* purgeable_malloc.h in Headers */ = {isa = PBXBuildFile; fileRef = C957429F1BF681B00027269A /* purgeable_malloc.h */; };
C95742A61BF6842F0027269A /* frozen_malloc.c in Sources */ = {isa = PBXBuildFile; fileRef = C95742A41BF6842F0027269A /* frozen_malloc.c */; };
C95742A71BF6842F0027269A /* frozen_malloc.c in Sources */ = {isa = PBXBuildFile; fileRef = C95742A41BF6842F0027269A /* frozen_malloc.c */; };
C95742A81BF6842F0027269A /* frozen_malloc.h in Headers */ = {isa = PBXBuildFile; fileRef = C95742A51BF6842F0027269A /* frozen_malloc.h */; };
C95742A91BF6842F0027269A /* frozen_malloc.h in Headers */ = {isa = PBXBuildFile; fileRef = C95742A51BF6842F0027269A /* frozen_malloc.h */; };
C95742AB1BF685CB0027269A /* legacy_malloc.c in Sources */ = {isa = PBXBuildFile; fileRef = C95742AA1BF685CB0027269A /* legacy_malloc.c */; };
C95742AC1BF685CB0027269A /* legacy_malloc.c in Sources */ = {isa = PBXBuildFile; fileRef = C95742AA1BF685CB0027269A /* legacy_malloc.c */; };
C99E320B1D6F7366005655A8 /* magazine_rack.c in Sources */ = {isa = PBXBuildFile; fileRef = C99E32091D6F7366005655A8 /* magazine_rack.c */; };
C99E320C1D6F7366005655A8 /* magazine_rack.h in Headers */ = {isa = PBXBuildFile; fileRef = C99E320A1D6F7366005655A8 /* magazine_rack.h */; };
C9ABCA051CB6FC6800ECB399 /* empty.s in Sources */ = {isa = PBXBuildFile; fileRef = C9ABCA041CB6FC6800ECB399 /* empty.s */; };
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */
3FE9201516A9111400D1238A /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 3FFC1BE516A908F800027192 /* Project object */;
proxyType = 1;
remoteGlobalIDString = 3FE91FFD16A9109E00D1238A;
remoteInfo = libmalloc_eOS;
};
3FE9201716A9111600D1238A /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 3FFC1BE516A908F800027192 /* Project object */;
proxyType = 1;
remoteGlobalIDString = 3FE91FE716A90AEC00D1238A;
remoteInfo = libsystem_malloc;
};
45039167198FFFA6004EE2A3 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 3FFC1BE516A908F800027192 /* Project object */;
proxyType = 1;
remoteGlobalIDString = 456E51C8197DF0D600A7E488;
remoteInfo = libmalloc_stress_test;
};
925383D81BD03D0000F745DB /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 3FFC1BE516A908F800027192 /* Project object */;
proxyType = 1;
remoteGlobalIDString = 925383D41BD03C0500F745DB;
remoteInfo = darwintests;
};
B60A579720093093006215CB /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 3FFC1BE516A908F800027192 /* Project object */;
proxyType = 1;
remoteGlobalIDString = B6D2ED492007D76F007AF994;
remoteInfo = libmalloc_replay;
};
B629CF43202BB389007719B9 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 3FFC1BE516A908F800027192 /* Project object */;
proxyType = 1;
remoteGlobalIDString = B629CF2B202BB337007719B9;
remoteInfo = libmalloc_alt;
};
B676F4AB202B66EF00933F6D /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 3FFC1BE516A908F800027192 /* Project object */;
proxyType = 1;
remoteGlobalIDString = B6910F65202B630D00FF2EB0;
remoteInfo = libmalloc_mp;
};
C0CE454F1C52CCBD00C24048 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 3FFC1BE516A908F800027192 /* Project object */;
proxyType = 1;
remoteGlobalIDString = C0CE452F1C52C90500C24048;
remoteInfo = libmalloc_static;
};
/* End PBXContainerItemProxy section */
/* Begin PBXCopyFilesBuildPhase section */
456E51C7197DF0D600A7E488 /* CopyFiles */ = {
isa = PBXCopyFilesBuildPhase;
buildActionMask = 2147483647;
dstPath = /usr/share/man/man1/;
dstSubfolderSpec = 0;
files = (
);
runOnlyForDeploymentPostprocessing = 1;
};
C0CE454D1C52C9D900C24048 /* CopyFiles */ = {
isa = PBXCopyFilesBuildPhase;
buildActionMask = 8;
dstPath = /usr/local/lib/loaderd;
dstSubfolderSpec = 0;
files = (
C0CE454E1C52C9E600C24048 /* libmalloc.a in CopyFiles */,
);
runOnlyForDeploymentPostprocessing = 1;
};
/* End PBXCopyFilesBuildPhase section */
/* Begin PBXFileReference section */
084F5E831D50204F006CD296 /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = System/Library/Frameworks/Foundation.framework; sourceTree = SDKROOT; };
088C4D731D1AEFB5005C6B36 /* radix_tree_internal.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = radix_tree_internal.h; sourceTree = ""; };
088C4D741D1AEFB5005C6B36 /* radix_tree.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = radix_tree.c; sourceTree = ""; };
088C4D751D1AEFB5005C6B36 /* radix_tree.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = radix_tree.h; sourceTree = ""; };
088C4D761D1AEFC5005C6B36 /* radix_tree_test.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = radix_tree_test.m; sourceTree = ""; };
08C28B3A1D501ACC000AE997 /* radix_tree_debug.c */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.c; path = radix_tree_debug.c; sourceTree = ""; };
08C28B401D501D2C000AE997 /* radix-tree */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = "radix-tree"; sourceTree = BUILT_PRODUCTS_DIR; };
08C28B421D501D2C000AE997 /* radix_tree_main.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = radix_tree_main.m; sourceTree = ""; };
0D468DCC1C7BEE56006FACF5 /* magazine_lite.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = magazine_lite.c; sourceTree = ""; };
0D468DCD1C7BEE65006FACF5 /* stack_logging_internal.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = stack_logging_internal.h; sourceTree = ""; };
0D468DCE1C7BEE74006FACF5 /* stack_logging_test.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = stack_logging_test.c; sourceTree = ""; };
2B67B5672040B3A50003E78F /* _malloc.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = _malloc.h; sourceTree = ""; };
3D157E7320354E02001630BF /* perfdata.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = perfdata.framework; path = ../MacOSX10.14.Internal.sdk/System/Library/PrivateFrameworks/perfdata.framework; sourceTree = SDKROOT; };
3FC452FF18E4ABFE003D6A38 /* manpages.sh */ = {isa = PBXFileReference; lastKnownFileType = text.script.sh; path = manpages.sh; sourceTree = ""; };
3FE91FC916A90A8D00D1238A /* malloc.3 */ = {isa = PBXFileReference; lastKnownFileType = text; path = malloc.3; sourceTree = ""; };
3FE91FCA16A90A8D00D1238A /* malloc_size.3 */ = {isa = PBXFileReference; lastKnownFileType = text; path = malloc_size.3; sourceTree = ""; };
3FE91FCB16A90A8D00D1238A /* malloc_zone_malloc.3 */ = {isa = PBXFileReference; lastKnownFileType = text; path = malloc_zone_malloc.3; sourceTree = ""; };
3FE91FD116A90A8D00D1238A /* bitarray.c */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.c; path = bitarray.c; sourceTree = ""; };
3FE91FD216A90A8D00D1238A /* bitarray.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = bitarray.h; sourceTree = ""; };
3FE91FD616A90A8D00D1238A /* magazine_malloc.c */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.c; lineEnding = 0; path = magazine_malloc.c; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.c; };
3FE91FD716A90A8D00D1238A /* magmallocProvider.d */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.dtrace; path = magmallocProvider.d; sourceTree = ""; };
3FE91FD816A90A8D00D1238A /* malloc.c */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.c; path = malloc.c; sourceTree = ""; };
3FE91FD916A90A8D00D1238A /* printf.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = printf.h; sourceTree = ""; };
3FE91FDA16A90A8D00D1238A /* nano_malloc.c */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.c; path = nano_malloc.c; sourceTree = ""; };
3FE91FDC16A90A8D00D1238A /* stack_logging_disk.c */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.c; path = stack_logging_disk.c; sourceTree = ""; usesTabs = 1; };
3FE91FE016A90A8D00D1238A /* libmalloc.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = libmalloc.xcconfig; sourceTree = ""; };
3FE91FE116A90A8D00D1238A /* libmalloc_eos.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = libmalloc_eos.xcconfig; sourceTree = ""; };
3FE91FE316A90A8D00D1238A /* sanitise_headers.sh */ = {isa = PBXFileReference; lastKnownFileType = text.script.sh; path = sanitise_headers.sh; sourceTree = ""; };
3FE91FE816A90AEC00D1238A /* libsystem_malloc.dylib */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.dylib"; includeInIndex = 0; path = libsystem_malloc.dylib; sourceTree = BUILT_PRODUCTS_DIR; };
3FE91FF916A90BEF00D1238A /* malloc.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = malloc.h; sourceTree = ""; };
3FE91FFB16A90E6C00D1238A /* legacy_malloc.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = legacy_malloc.h; sourceTree = ""; };
3FE9201016A9109E00D1238A /* libmalloc_eOS.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libmalloc_eOS.a; sourceTree = BUILT_PRODUCTS_DIR; };
456E51C9197DF0D600A7E488 /* libmalloc_stress_test */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = libmalloc_stress_test; sourceTree = BUILT_PRODUCTS_DIR; };
8CB962B01F7E9F610046942E /* asan.c */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.c; path = asan.c; sourceTree = ""; };
8CB962B11F7E9FD00046942E /* tsan.c */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.c; path = tsan.c; sourceTree = ""; };
925383D01BD03B4A00F745DB /* Makefile */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.make; path = Makefile; sourceTree = ""; };
925383D11BD03B4A00F745DB /* stress_test.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = stress_test.c; sourceTree = ""; };
925383D31BD03B8F00F745DB /* manpages.lst */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = manpages.lst; sourceTree = ""; };
B61341DD20114B070038D163 /* ktrace.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = ktrace.framework; path = Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.Internal.sdk/System/Library/PrivateFrameworks/ktrace.framework; sourceTree = DEVELOPER_DIR; };
B629CF29202BA3C2007719B9 /* libmalloc_resolver.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = libmalloc_resolver.xcconfig; sourceTree = ""; };
B629CF42202BB337007719B9 /* libmalloc_alt.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libmalloc_alt.a; sourceTree = BUILT_PRODUCTS_DIR; };
B629CF46202BBDEC007719B9 /* resolver_internal.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = resolver_internal.h; sourceTree = ""; };
B629CF48202BBE3B007719B9 /* resolver.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = resolver.h; sourceTree = ""; };
B64E100A205311DC004C4BA6 /* malloc_size_test.c */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.c; path = malloc_size_test.c; sourceTree = ""; };
B6536A62204754B6005FBE22 /* perf_contended_malloc_free.c */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.c; path = perf_contended_malloc_free.c; sourceTree = ""; };
B6536A6320475BA4005FBE22 /* basic_malloc_free_perf.c */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.c; path = basic_malloc_free_perf.c; sourceTree = ""; };
B65FBE2B2087AA2F00E21F59 /* malloc_printf.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = malloc_printf.c; sourceTree = ""; };
B66AA658202A70B00019D607 /* libmalloc_resolved.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = libmalloc_resolved.xcconfig; sourceTree = ""; };
B66C71D72034BFAE0047E265 /* malloc_common.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = malloc_common.h; sourceTree = ""; };
B66C71D82034BFAE0047E265 /* malloc_common.c */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.c; path = malloc_common.c; sourceTree = ""; };
B670DABD2072D0BB00139A1D /* perf_realloc.c */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.c; path = perf_realloc.c; sourceTree = ""; };
B671CFFD207578CC00EEAF20 /* libmalloc.dirty */ = {isa = PBXFileReference; lastKnownFileType = text; path = libmalloc.dirty; sourceTree = ""; };
B675F74520213D0A00B5038B /* nano_tests.c */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.c; path = nano_tests.c; sourceTree = ""; };
B68B7F9C1FCDCBC600BAD1AA /* nano_malloc_common.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = nano_malloc_common.h; sourceTree = ""; };
B68B7F9D1FCDCBC600BAD1AA /* nano_malloc_common.c */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.c; path = nano_malloc_common.c; sourceTree = ""; };
B68B7FA21FCDD60F00BAD1AA /* nanov2_malloc.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = nanov2_malloc.h; sourceTree = ""; };
B68B7FA41FCDD9A500BAD1AA /* nanov2_malloc.c */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.c; path = nanov2_malloc.c; sourceTree = ""; };
B6910F89202B630D00FF2EB0 /* libmalloc_mp.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libmalloc_mp.a; sourceTree = BUILT_PRODUCTS_DIR; };
B69B2B941FB3D00500FD5A8F /* magazine_malloc.c */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.c; path = magazine_malloc.c; sourceTree = ""; };
B6A414EA1FBDF01C0038DC53 /* malloc_claimed_address_tests.c */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.c; path = malloc_claimed_address_tests.c; sourceTree = ""; };
B6A494971F9918DD0016A799 /* calloc_test.c */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.c; path = calloc_test.c; sourceTree = ""; };
B6A9C48C1F991716007D0853 /* malloc_free_test.c */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.c; path = malloc_free_test.c; sourceTree = ""; };
B6C1C9C720D9B70F002CCC0B /* nano_trace_replay.c */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.c; path = nano_trace_replay.c; sourceTree = ""; };
B6CA644D1FCE2C0A00DEBA12 /* nanov2_zone.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = nanov2_zone.h; sourceTree = ""; };
B6CA64511FCF1AAD00DEBA12 /* nano_zone_common.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = nano_zone_common.h; sourceTree = ""; };
B6D2ED512007D76F007AF994 /* libmalloc_replay */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = libmalloc_replay; sourceTree = BUILT_PRODUCTS_DIR; };
B6D2ED552007D91A007AF994 /* malloc_replay.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = malloc_replay.cpp; sourceTree = ""; };
B6D2ED562007D91A007AF994 /* malloc_replay.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = malloc_replay.h; sourceTree = ""; };
B6D5C7ED202E26CA0035E376 /* resolver.c */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.c; path = resolver.c; sourceTree = ""; };
C0352EC61C3F3C3600DB5126 /* malloc_private.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = malloc_private.h; sourceTree = ""; };
C0CE450E1C52B9E300C24048 /* libmalloc_static.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = libmalloc_static.xcconfig; sourceTree = ""; };
C0CE454C1C52C90500C24048 /* libmalloc.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libmalloc.a; sourceTree = BUILT_PRODUCTS_DIR; };
C92853A01C767F08001FEAF3 /* install-codes.sh */ = {isa = PBXFileReference; lastKnownFileType = text.script.sh; path = "install-codes.sh"; sourceTree = ""; };
C931B58F1C81248100D0D230 /* madvise.c */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.c; path = madvise.c; sourceTree = ""; };
C932D2631D6B6ED40063B19E /* magazine_tiny_test.c */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.c; path = magazine_tiny_test.c; sourceTree = ""; };
C932D2641D6B73270063B19E /* dtrace.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = dtrace.h; sourceTree = ""; };
C932D2661D6B8D840063B19E /* vm.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = vm.c; sourceTree = ""; };
C932D2671D6B8D840063B19E /* vm.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = vm.h; sourceTree = ""; };
C938BBD21C74F7A400522BBD /* trace.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = trace.h; sourceTree = ""; };
C93F76D71D6B9F8C0088931B /* magazine_testing.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = magazine_testing.h; sourceTree = ""; };
C9571C391C18AA1D00A67EE3 /* stack_logging.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = stack_logging.h; sourceTree = ""; };
C9571C3C1C18AD5F00A67EE3 /* balloon.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = balloon.cpp; sourceTree = ""; };
C9571C3D1C18AD5F00A67EE3 /* balloon.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = balloon.h; sourceTree = ""; };
C9571C3E1C18AD5F00A67EE3 /* Benchmark.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = Benchmark.cpp; sourceTree = ""; };
C9571C3F1C18AD5F00A67EE3 /* Benchmark.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = Benchmark.h; sourceTree = ""; };
C9571C401C18AD5F00A67EE3 /* big.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = big.cpp; sourceTree = ""; };
C9571C411C18AD5F00A67EE3 /* big.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = big.h; sourceTree = ""; };
C9571C421C18AD5F00A67EE3 /* churn.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = churn.cpp; sourceTree = ""; };
C9571C431C18AD5F00A67EE3 /* churn.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = churn.h; sourceTree = ""; };
C9571C441C18AD5F00A67EE3 /* CommandLine.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = CommandLine.cpp; sourceTree = ""; };
C9571C451C18AD5F00A67EE3 /* CommandLine.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = CommandLine.h; sourceTree = ""; };
C9571C461C18AD5F00A67EE3 /* CPUCount.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = CPUCount.cpp; sourceTree = ""; };
C9571C471C18AD5F00A67EE3 /* CPUCount.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = CPUCount.h; sourceTree = ""; };
C9571C4C1C18AD5F00A67EE3 /* fragment.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = fragment.cpp; sourceTree = ""; };
C9571C4D1C18AD5F00A67EE3 /* fragment.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = fragment.h; sourceTree = ""; };
C9571C4E1C18AD5F00A67EE3 /* Interpreter.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = Interpreter.cpp; sourceTree = ""; };
C9571C4F1C18AD5F00A67EE3 /* Interpreter.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = Interpreter.h; sourceTree = ""; };
C9571C501C18AD5F00A67EE3 /* list.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = list.cpp; sourceTree = ""; };
C9571C511C18AD5F00A67EE3 /* list.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = list.h; sourceTree = ""; };
C9571C521C18AD5F00A67EE3 /* mbmalloc.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = mbmalloc.cpp; sourceTree = ""; };
C9571C531C18AD5F00A67EE3 /* mbmalloc.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = mbmalloc.h; sourceTree = ""; };
C9571C541C18AD5F00A67EE3 /* medium.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = medium.cpp; sourceTree = ""; };
C9571C551C18AD5F00A67EE3 /* medium.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = medium.h; sourceTree = ""; };
C9571C561C18AD5F00A67EE3 /* memalign.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = memalign.cpp; sourceTree = ""; };
C9571C571C18AD5F00A67EE3 /* memalign.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = memalign.h; sourceTree = ""; };
C9571C581C18AD5F00A67EE3 /* message.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = message.cpp; sourceTree = ""; };
C9571C591C18AD5F00A67EE3 /* message.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = message.h; sourceTree = ""; };
C9571C5A1C18AD5F00A67EE3 /* realloc.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = realloc.cpp; sourceTree = ""; };
C9571C5B1C18AD5F00A67EE3 /* realloc.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = realloc.h; sourceTree = ""; };
C9571C5E1C18AD5F00A67EE3 /* stress_aligned.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = stress_aligned.cpp; sourceTree = ""; };
C9571C5F1C18AD5F00A67EE3 /* stress_aligned.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = stress_aligned.h; sourceTree = ""; };
C9571C601C18AD5F00A67EE3 /* stress.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = stress.cpp; sourceTree = ""; };
C9571C611C18AD5F00A67EE3 /* stress.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = stress.h; sourceTree = ""; };
C9571C641C18AD5F00A67EE3 /* tree.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = tree.cpp; sourceTree = ""; };
C9571C651C18AD5F00A67EE3 /* tree.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = tree.h; sourceTree = ""; };
C9571C661C18AD6A00A67EE3 /* MallocBench.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = MallocBench.cpp; sourceTree = ""; };
C957426D1BF2C0C80027269A /* internal.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = internal.h; sourceTree = ""; };
C957426E1BF2C1480027269A /* locking.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = locking.h; sourceTree = ""; };
C95742791BF2C5F40027269A /* nano_malloc.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = nano_malloc.h; sourceTree = ""; };
C957427B1BF2C8DE0027269A /* debug.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = debug.h; sourceTree = ""; };
C957427E1BF33D130027269A /* nano_zone.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = nano_zone.h; sourceTree = ""; };
C95742861BF3F9550027269A /* magazine_zone.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = magazine_zone.h; sourceTree = ""; };
C95742891BF3FD290027269A /* base.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = base.h; sourceTree = ""; };
C957428C1BF411330027269A /* thresholds.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = thresholds.h; sourceTree = ""; };
C957428F1BF419DF0027269A /* magazine_tiny.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; lineEnding = 0; path = magazine_tiny.c; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.c; };
C95742921BF41C970027269A /* magazine_inline.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; lineEnding = 0; path = magazine_inline.h; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.objcpp; };
C95742951BF41E480027269A /* magazine_malloc.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = magazine_malloc.h; sourceTree = ""; };
C95742981BF670D00027269A /* magazine_small.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; lineEnding = 0; path = magazine_small.c; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.c; };
C957429B1BF672F80027269A /* magazine_large.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = magazine_large.c; sourceTree = ""; };
C957429E1BF681B00027269A /* purgeable_malloc.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = purgeable_malloc.c; sourceTree = ""; };
C957429F1BF681B00027269A /* purgeable_malloc.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = purgeable_malloc.h; sourceTree = ""; };
C95742A41BF6842F0027269A /* frozen_malloc.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = frozen_malloc.c; sourceTree = ""; };
C95742A51BF6842F0027269A /* frozen_malloc.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = frozen_malloc.h; sourceTree = ""; };
C95742AA1BF685CB0027269A /* legacy_malloc.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = legacy_malloc.c; sourceTree = ""; };
C99E32091D6F7366005655A8 /* magazine_rack.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = magazine_rack.c; sourceTree = ""; };
C99E320A1D6F7366005655A8 /* magazine_rack.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = magazine_rack.h; sourceTree = ""; };
C9ABCA041CB6FC6800ECB399 /* empty.s */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.asm; path = empty.s; sourceTree = ""; };
C9F77BBA1BF2B84800812E13 /* platform.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = platform.h; sourceTree = ""; };
C9F8C2681D70B521008C4044 /* magazine_small_test.c */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.c; path = magazine_small_test.c; sourceTree = ""; };
C9F8C2691D74C93A008C4044 /* magazine_rack.c */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.c; path = magazine_rack.c; sourceTree = ""; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
08C28B3D1D501D2C000AE997 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
084F5E841D50204F006CD296 /* Foundation.framework in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
3FE91FE516A90AEC00D1238A /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
3FE9200716A9109E00D1238A /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
456E51C6197DF0D600A7E488 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
B629CF3D202BB337007719B9 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
B6910F77202B630D00FF2EB0 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
B6D2ED4C2007D76F007AF994 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
3D157E7420354E02001630BF /* perfdata.framework in Frameworks */,
B61341DE20114B660038D163 /* ktrace.framework in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
C0CE453E1C52C90500C24048 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
084F5E821D50204F006CD296 /* Frameworks */ = {
isa = PBXGroup;
children = (
3D157E7320354E02001630BF /* perfdata.framework */,
B61341DD20114B070038D163 /* ktrace.framework */,
084F5E831D50204F006CD296 /* Foundation.framework */,
);
name = Frameworks;
sourceTree = "";
};
08C28B411D501D2C000AE997 /* tools */ = {
isa = PBXGroup;
children = (
08C28B421D501D2C000AE997 /* radix_tree_main.m */,
B6D2ED552007D91A007AF994 /* malloc_replay.cpp */,
B6D2ED562007D91A007AF994 /* malloc_replay.h */,
);
path = tools;
sourceTree = "";
};
3FE91FC816A90A8D00D1238A /* man */ = {
isa = PBXGroup;
children = (
925383D31BD03B8F00F745DB /* manpages.lst */,
3FE91FC916A90A8D00D1238A /* malloc.3 */,
3FE91FCA16A90A8D00D1238A /* malloc_size.3 */,
3FE91FCB16A90A8D00D1238A /* malloc_zone_malloc.3 */,
);
path = man;
sourceTree = "";
};
3FE91FCC16A90A8D00D1238A /* src */ = {
isa = PBXGroup;
children = (
08C28B3A1D501ACC000AE997 /* radix_tree_debug.c */,
088C4D731D1AEFB5005C6B36 /* radix_tree_internal.h */,
088C4D741D1AEFB5005C6B36 /* radix_tree.c */,
088C4D751D1AEFB5005C6B36 /* radix_tree.h */,
C95742891BF3FD290027269A /* base.h */,
3FE91FD116A90A8D00D1238A /* bitarray.c */,
3FE91FD216A90A8D00D1238A /* bitarray.h */,
C957427B1BF2C8DE0027269A /* debug.h */,
C932D2641D6B73270063B19E /* dtrace.h */,
C9ABCA041CB6FC6800ECB399 /* empty.s */,
C95742A41BF6842F0027269A /* frozen_malloc.c */,
C95742A51BF6842F0027269A /* frozen_malloc.h */,
C957426D1BF2C0C80027269A /* internal.h */,
C95742AA1BF685CB0027269A /* legacy_malloc.c */,
3FE91FFB16A90E6C00D1238A /* legacy_malloc.h */,
C957426E1BF2C1480027269A /* locking.h */,
C95742921BF41C970027269A /* magazine_inline.h */,
C957429B1BF672F80027269A /* magazine_large.c */,
0D468DCC1C7BEE56006FACF5 /* magazine_lite.c */,
3FE91FD616A90A8D00D1238A /* magazine_malloc.c */,
C95742951BF41E480027269A /* magazine_malloc.h */,
B65FBE2B2087AA2F00E21F59 /* malloc_printf.c */,
C99E32091D6F7366005655A8 /* magazine_rack.c */,
C99E320A1D6F7366005655A8 /* magazine_rack.h */,
C95742981BF670D00027269A /* magazine_small.c */,
C957428F1BF419DF0027269A /* magazine_tiny.c */,
C95742861BF3F9550027269A /* magazine_zone.h */,
3FE91FD716A90A8D00D1238A /* magmallocProvider.d */,
3FE91FD816A90A8D00D1238A /* malloc.c */,
B66C71D82034BFAE0047E265 /* malloc_common.c */,
B66C71D72034BFAE0047E265 /* malloc_common.h */,
B68B7F9D1FCDCBC600BAD1AA /* nano_malloc_common.c */,
B68B7F9C1FCDCBC600BAD1AA /* nano_malloc_common.h */,
3FE91FDA16A90A8D00D1238A /* nano_malloc.c */,
C95742791BF2C5F40027269A /* nano_malloc.h */,
C957427E1BF33D130027269A /* nano_zone.h */,
B6CA64511FCF1AAD00DEBA12 /* nano_zone_common.h */,
B68B7FA41FCDD9A500BAD1AA /* nanov2_malloc.c */,
B68B7FA21FCDD60F00BAD1AA /* nanov2_malloc.h */,
B6CA644D1FCE2C0A00DEBA12 /* nanov2_zone.h */,
C9F77BBA1BF2B84800812E13 /* platform.h */,
3FE91FD916A90A8D00D1238A /* printf.h */,
C957429E1BF681B00027269A /* purgeable_malloc.c */,
C957429F1BF681B00027269A /* purgeable_malloc.h */,
3FE91FDC16A90A8D00D1238A /* stack_logging_disk.c */,
0D468DCD1C7BEE65006FACF5 /* stack_logging_internal.h */,
C957428C1BF411330027269A /* thresholds.h */,
C938BBD21C74F7A400522BBD /* trace.h */,
C932D2661D6B8D840063B19E /* vm.c */,
C932D2671D6B8D840063B19E /* vm.h */,
);
path = src;
sourceTree = "";
};
3FE91FDF16A90A8D00D1238A /* xcodeconfig */ = {
isa = PBXGroup;
children = (
3FE91FE016A90A8D00D1238A /* libmalloc.xcconfig */,
3FE91FE116A90A8D00D1238A /* libmalloc_eos.xcconfig */,
C0CE450E1C52B9E300C24048 /* libmalloc_static.xcconfig */,
B66AA658202A70B00019D607 /* libmalloc_resolved.xcconfig */,
B629CF29202BA3C2007719B9 /* libmalloc_resolver.xcconfig */,
B671CFFD207578CC00EEAF20 /* libmalloc.dirty */,
);
path = xcodeconfig;
sourceTree = "";
};
3FE91FE216A90A8D00D1238A /* xcodescripts */ = {
isa = PBXGroup;
children = (
3FC452FF18E4ABFE003D6A38 /* manpages.sh */,
3FE91FE316A90A8D00D1238A /* sanitise_headers.sh */,
C92853A01C767F08001FEAF3 /* install-codes.sh */,
);
path = xcodescripts;
sourceTree = "";
};
3FE91FE916A90AEC00D1238A /* Products */ = {
isa = PBXGroup;
children = (
3FE91FE816A90AEC00D1238A /* libsystem_malloc.dylib */,
3FE9201016A9109E00D1238A /* libmalloc_eOS.a */,
456E51C9197DF0D600A7E488 /* libmalloc_stress_test */,
C0CE454C1C52C90500C24048 /* libmalloc.a */,
08C28B401D501D2C000AE997 /* radix-tree */,
B6D2ED512007D76F007AF994 /* libmalloc_replay */,
B6910F89202B630D00FF2EB0 /* libmalloc_mp.a */,
B629CF42202BB337007719B9 /* libmalloc_alt.a */,
);
name = Products;
sourceTree = "";
};
3FE91FF716A90BEF00D1238A /* include */ = {
isa = PBXGroup;
children = (
3FE91FF816A90BEF00D1238A /* malloc */,
);
path = include;
sourceTree = "";
};
3FE91FF816A90BEF00D1238A /* malloc */ = {
isa = PBXGroup;
children = (
2B67B5672040B3A50003E78F /* _malloc.h */,
3FE91FF916A90BEF00D1238A /* malloc.h */,
);
path = malloc;
sourceTree = "";
};
3FFC1BE416A908F800027192 = {
isa = PBXGroup;
children = (
3FE91FF716A90BEF00D1238A /* include */,
3FE91FC816A90A8D00D1238A /* man */,
C9571C381C18AA0A00A67EE3 /* private */,
3FE91FCC16A90A8D00D1238A /* src */,
B629CF45202BBDCC007719B9 /* resolver */,
925383BD1BD03B4A00F745DB /* tests */,
3FE91FDF16A90A8D00D1238A /* xcodeconfig */,
3FE91FE216A90A8D00D1238A /* xcodescripts */,
08C28B411D501D2C000AE997 /* tools */,
3FE91FE916A90AEC00D1238A /* Products */,
084F5E821D50204F006CD296 /* Frameworks */,
);
sourceTree = "";
tabWidth = 4;
usesTabs = 1;
};
925383BD1BD03B4A00F745DB /* tests */ = {
isa = PBXGroup;
children = (
8CB962B01F7E9F610046942E /* asan.c */,
8CB962B11F7E9FD00046942E /* tsan.c */,
C931B58F1C81248100D0D230 /* madvise.c */,
C9F8C2691D74C93A008C4044 /* magazine_rack.c */,
B6A494971F9918DD0016A799 /* calloc_test.c */,
B6A9C48C1F991716007D0853 /* malloc_free_test.c */,
B6A414EA1FBDF01C0038DC53 /* malloc_claimed_address_tests.c */,
C9F8C2681D70B521008C4044 /* magazine_small_test.c */,
B64E100A205311DC004C4BA6 /* malloc_size_test.c */,
C93F76D71D6B9F8C0088931B /* magazine_testing.h */,
C932D2631D6B6ED40063B19E /* magazine_tiny_test.c */,
B69B2B941FB3D00500FD5A8F /* magazine_malloc.c */,
925383D01BD03B4A00F745DB /* Makefile */,
C9571C3B1C18AD4F00A67EE3 /* MallocBench */,
C9571C661C18AD6A00A67EE3 /* MallocBench.cpp */,
B6536A6320475BA4005FBE22 /* basic_malloc_free_perf.c */,
B675F74520213D0A00B5038B /* nano_tests.c */,
B6C1C9C720D9B70F002CCC0B /* nano_trace_replay.c */,
B6536A62204754B6005FBE22 /* perf_contended_malloc_free.c */,
B670DABD2072D0BB00139A1D /* perf_realloc.c */,
088C4D761D1AEFC5005C6B36 /* radix_tree_test.m */,
0D468DCE1C7BEE74006FACF5 /* stack_logging_test.c */,
925383D11BD03B4A00F745DB /* stress_test.c */,
);
path = tests;
sourceTree = "";
};
B629CF45202BBDCC007719B9 /* resolver */ = {
isa = PBXGroup;
children = (
B629CF48202BBE3B007719B9 /* resolver.h */,
B629CF46202BBDEC007719B9 /* resolver_internal.h */,
B6D5C7ED202E26CA0035E376 /* resolver.c */,
);
path = resolver;
sourceTree = "";
};
C9571C381C18AA0A00A67EE3 /* private */ = {
isa = PBXGroup;
children = (
C9571C391C18AA1D00A67EE3 /* stack_logging.h */,
C0352EC61C3F3C3600DB5126 /* malloc_private.h */,
);
path = private;
sourceTree = "";
};
C9571C3B1C18AD4F00A67EE3 /* MallocBench */ = {
isa = PBXGroup;
children = (
C9571C3C1C18AD5F00A67EE3 /* balloon.cpp */,
C9571C3D1C18AD5F00A67EE3 /* balloon.h */,
C9571C3E1C18AD5F00A67EE3 /* Benchmark.cpp */,
C9571C3F1C18AD5F00A67EE3 /* Benchmark.h */,
C9571C401C18AD5F00A67EE3 /* big.cpp */,
C9571C411C18AD5F00A67EE3 /* big.h */,
C9571C421C18AD5F00A67EE3 /* churn.cpp */,
C9571C431C18AD5F00A67EE3 /* churn.h */,
C9571C441C18AD5F00A67EE3 /* CommandLine.cpp */,
C9571C451C18AD5F00A67EE3 /* CommandLine.h */,
C9571C461C18AD5F00A67EE3 /* CPUCount.cpp */,
C9571C471C18AD5F00A67EE3 /* CPUCount.h */,
C9571C4C1C18AD5F00A67EE3 /* fragment.cpp */,
C9571C4D1C18AD5F00A67EE3 /* fragment.h */,
C9571C4E1C18AD5F00A67EE3 /* Interpreter.cpp */,
C9571C4F1C18AD5F00A67EE3 /* Interpreter.h */,
C9571C501C18AD5F00A67EE3 /* list.cpp */,
C9571C511C18AD5F00A67EE3 /* list.h */,
C9571C521C18AD5F00A67EE3 /* mbmalloc.cpp */,
C9571C531C18AD5F00A67EE3 /* mbmalloc.h */,
C9571C541C18AD5F00A67EE3 /* medium.cpp */,
C9571C551C18AD5F00A67EE3 /* medium.h */,
C9571C561C18AD5F00A67EE3 /* memalign.cpp */,
C9571C571C18AD5F00A67EE3 /* memalign.h */,
C9571C581C18AD5F00A67EE3 /* message.cpp */,
C9571C591C18AD5F00A67EE3 /* message.h */,
C9571C5A1C18AD5F00A67EE3 /* realloc.cpp */,
C9571C5B1C18AD5F00A67EE3 /* realloc.h */,
C9571C5E1C18AD5F00A67EE3 /* stress_aligned.cpp */,
C9571C5F1C18AD5F00A67EE3 /* stress_aligned.h */,
C9571C601C18AD5F00A67EE3 /* stress.cpp */,
C9571C611C18AD5F00A67EE3 /* stress.h */,
C9571C641C18AD5F00A67EE3 /* tree.cpp */,
C9571C651C18AD5F00A67EE3 /* tree.h */,
);
path = MallocBench;
sourceTree = "";
};
/* End PBXGroup section */
/* Begin PBXHeadersBuildPhase section */
3FE91FE616A90AEC00D1238A /* Headers */ = {
isa = PBXHeadersBuildPhase;
buildActionMask = 2147483647;
files = (
C957428A1BF3FD290027269A /* base.h in Headers */,
C0352EC71C3F3C4400DB5126 /* malloc_private.h in Headers */,
0D468DD01C7BEF71006FACF5 /* stack_logging_internal.h in Headers */,
C95742731BF2C2880027269A /* internal.h in Headers */,
B6CA644E1FCE2C1900DEBA12 /* nanov2_zone.h in Headers */,
C99E320C1D6F7366005655A8 /* magazine_rack.h in Headers */,
C95742721BF2C2880027269A /* bitarray.h in Headers */,
C932D2691D6B8D840063B19E /* vm.h in Headers */,
B6CA64521FCF1AD200DEBA12 /* nano_zone_common.h in Headers */,
C938BBD31C74F7A400522BBD /* trace.h in Headers */,
C95742A81BF6842F0027269A /* frozen_malloc.h in Headers */,
C957428D1BF411330027269A /* thresholds.h in Headers */,
C95742741BF2C2880027269A /* locking.h in Headers */,
C95742931BF41C970027269A /* magazine_inline.h in Headers */,
B68B7FA31FCDD67100BAD1AA /* nanov2_malloc.h in Headers */,
C95742761BF2C2880027269A /* platform.h in Headers */,
C957427A1BF2C67E0027269A /* nano_malloc.h in Headers */,
B66C71D92034BFAE0047E265 /* malloc_common.h in Headers */,
C957427C1BF2C8DE0027269A /* debug.h in Headers */,
2B67B5682040B3AF0003E78F /* _malloc.h in Headers */,
C95742961BF41E480027269A /* magazine_malloc.h in Headers */,
C9571C3A1C18AA1D00A67EE3 /* stack_logging.h in Headers */,
3FE91FFA16A90BEF00D1238A /* malloc.h in Headers */,
C95742871BF3F9550027269A /* magazine_zone.h in Headers */,
C95742771BF2C2880027269A /* legacy_malloc.h in Headers */,
C95742A21BF681B00027269A /* purgeable_malloc.h in Headers */,
B68B7F9E1FCDCBC600BAD1AA /* nano_malloc_common.h in Headers */,
C957427F1BF33D130027269A /* nano_zone.h in Headers */,
C95742751BF2C2880027269A /* printf.h in Headers */,
);
runOnlyForDeploymentPostprocessing = 0;
};
3FE9200816A9109E00D1238A /* Headers */ = {
isa = PBXHeadersBuildPhase;
buildActionMask = 2147483647;
files = (
C95742941BF41C970027269A /* magazine_inline.h in Headers */,
C95742801BF33D130027269A /* nano_zone.h in Headers */,
B6CA644F1FCE2C1A00DEBA12 /* nanov2_zone.h in Headers */,
C957428E1BF411330027269A /* thresholds.h in Headers */,
C957427D1BF2C8DE0027269A /* debug.h in Headers */,
C95742A91BF6842F0027269A /* frozen_malloc.h in Headers */,
C95742881BF3F9550027269A /* magazine_zone.h in Headers */,
C95742971BF41E480027269A /* magazine_malloc.h in Headers */,
C95742A31BF681B00027269A /* purgeable_malloc.h in Headers */,
C957428B1BF3FD290027269A /* base.h in Headers */,
B6CA64531FCF1AD400DEBA12 /* nano_zone_common.h in Headers */,
);
runOnlyForDeploymentPostprocessing = 0;
};
C0CE453F1C52C90500C24048 /* Headers */ = {
isa = PBXHeadersBuildPhase;
buildActionMask = 2147483647;
files = (
C0CE45401C52C90500C24048 /* magazine_inline.h in Headers */,
C0CE45411C52C90500C24048 /* nano_zone.h in Headers */,
B6CA64501FCE2C1B00DEBA12 /* nanov2_zone.h in Headers */,
C0CE45421C52C90500C24048 /* thresholds.h in Headers */,
C0CE45431C52C90500C24048 /* debug.h in Headers */,
C0CE45441C52C90500C24048 /* frozen_malloc.h in Headers */,
C0CE45451C52C90500C24048 /* magazine_zone.h in Headers */,
C0CE45461C52C90500C24048 /* magazine_malloc.h in Headers */,
C0CE45471C52C90500C24048 /* purgeable_malloc.h in Headers */,
C0CE45481C52C90500C24048 /* base.h in Headers */,
B6CA64541FCF1AD400DEBA12 /* nano_zone_common.h in Headers */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXHeadersBuildPhase section */
/* Begin PBXLegacyTarget section */
925383D41BD03C0500F745DB /* darwintests */ = {
isa = PBXLegacyTarget;
buildArgumentsString = "$(ACTION)";
buildConfigurationList = 925383D51BD03C0500F745DB /* Build configuration list for PBXLegacyTarget "darwintests" */;
buildPhases = (
);
buildToolPath = /usr/bin/make;
buildWorkingDirectory = tests;
dependencies = (
);
name = darwintests;
passBuildSettingsInEnvironment = 1;
productName = darwintests;
};
/* End PBXLegacyTarget section */
/* Begin PBXNativeTarget section */
08C28B3F1D501D2C000AE997 /* radix-tree */ = {
isa = PBXNativeTarget;
buildConfigurationList = 08C28B441D501D2C000AE997 /* Build configuration list for PBXNativeTarget "radix-tree" */;
buildPhases = (
08C28B3C1D501D2C000AE997 /* Sources */,
08C28B3D1D501D2C000AE997 /* Frameworks */,
);
buildRules = (
);
dependencies = (
);
name = "radix-tree";
productName = "radix-tree";
productReference = 08C28B401D501D2C000AE997 /* radix-tree */;
productType = "com.apple.product-type.tool";
};
3FE91FE716A90AEC00D1238A /* libsystem_malloc */ = {
isa = PBXNativeTarget;
buildConfigurationList = 3FE91FEA16A90AEC00D1238A /* Build configuration list for PBXNativeTarget "libsystem_malloc" */;
buildPhases = (
3FE91FE416A90AEC00D1238A /* Sources */,
3FE91FE516A90AEC00D1238A /* Frameworks */,
3FE91FE616A90AEC00D1238A /* Headers */,
C92853A11C767F78001FEAF3 /* Install Codes File */,
);
buildRules = (
);
dependencies = (
B676F4AC202B66EF00933F6D /* PBXTargetDependency */,
B629CF44202BB389007719B9 /* PBXTargetDependency */,
);
name = libsystem_malloc;
productName = libmalloc;
productReference = 3FE91FE816A90AEC00D1238A /* libsystem_malloc.dylib */;
productType = "com.apple.product-type.library.dynamic";
};
3FE91FFD16A9109E00D1238A /* libmalloc_eOS */ = {
isa = PBXNativeTarget;
buildConfigurationList = 3FE9200D16A9109E00D1238A /* Build configuration list for PBXNativeTarget "libmalloc_eOS" */;
buildPhases = (
3FE91FFE16A9109E00D1238A /* Sources */,
3FE9200716A9109E00D1238A /* Frameworks */,
3FE9200816A9109E00D1238A /* Headers */,
);
buildRules = (
);
dependencies = (
);
name = libmalloc_eOS;
productName = libmalloc;
productReference = 3FE9201016A9109E00D1238A /* libmalloc_eOS.a */;
productType = "com.apple.product-type.library.static";
};
456E51C8197DF0D600A7E488 /* libmalloc_stress_test */ = {
isa = PBXNativeTarget;
buildConfigurationList = 456E51CF197DF0D600A7E488 /* Build configuration list for PBXNativeTarget "libmalloc_stress_test" */;
buildPhases = (
456E51C5197DF0D600A7E488 /* Sources */,
456E51C6197DF0D600A7E488 /* Frameworks */,
456E51C7197DF0D600A7E488 /* CopyFiles */,
);
buildRules = (
);
dependencies = (
);
name = libmalloc_stress_test;
productName = libmalloc_stress_test;
productReference = 456E51C9197DF0D600A7E488 /* libmalloc_stress_test */;
productType = "com.apple.product-type.tool";
};
B629CF2B202BB337007719B9 /* libmalloc_alt */ = {
isa = PBXNativeTarget;
buildConfigurationList = B629CF3F202BB337007719B9 /* Build configuration list for PBXNativeTarget "libmalloc_alt" */;
buildPhases = (
B629CF2C202BB337007719B9 /* Sources */,
B629CF3D202BB337007719B9 /* Frameworks */,
B629CF3E202BB337007719B9 /* Symlink normal variant */,
);
buildRules = (
);
dependencies = (
);
name = libmalloc_alt;
productName = libmalloc;
productReference = B629CF42202BB337007719B9 /* libmalloc_alt.a */;
productType = "com.apple.product-type.library.static";
};
B6910F65202B630D00FF2EB0 /* libmalloc_mp */ = {
isa = PBXNativeTarget;
buildConfigurationList = B6910F86202B630D00FF2EB0 /* Build configuration list for PBXNativeTarget "libmalloc_mp" */;
buildPhases = (
B6910F66202B630D00FF2EB0 /* Sources */,
B6910F77202B630D00FF2EB0 /* Frameworks */,
B629CF2A202BB226007719B9 /* Symlink normal variant */,
);
buildRules = (
);
dependencies = (
);
name = libmalloc_mp;
productName = libmalloc;
productReference = B6910F89202B630D00FF2EB0 /* libmalloc_mp.a */;
productType = "com.apple.product-type.library.static";
};
B6D2ED492007D76F007AF994 /* libmalloc_replay */ = {
isa = PBXNativeTarget;
buildConfigurationList = B6D2ED4E2007D76F007AF994 /* Build configuration list for PBXNativeTarget "libmalloc_replay" */;
buildPhases = (
B6D2ED4A2007D76F007AF994 /* Sources */,
B6D2ED4C2007D76F007AF994 /* Frameworks */,
);
buildRules = (
);
dependencies = (
);
name = libmalloc_replay;
productName = libmalloc_stress_test;
productReference = B6D2ED512007D76F007AF994 /* libmalloc_replay */;
productType = "com.apple.product-type.tool";
};
C0CE452F1C52C90500C24048 /* libmalloc_static */ = {
isa = PBXNativeTarget;
buildConfigurationList = C0CE45491C52C90500C24048 /* Build configuration list for PBXNativeTarget "libmalloc_static" */;
buildPhases = (
C0CE45301C52C90500C24048 /* Sources */,
C0CE453E1C52C90500C24048 /* Frameworks */,
C0CE453F1C52C90500C24048 /* Headers */,
C0CE454D1C52C9D900C24048 /* CopyFiles */,
);
buildRules = (
);
dependencies = (
);
name = libmalloc_static;
productName = libmalloc;
productReference = C0CE454C1C52C90500C24048 /* libmalloc.a */;
productType = "com.apple.product-type.library.static";
};
/* End PBXNativeTarget section */
/* Begin PBXProject section */
3FFC1BE516A908F800027192 /* Project object */ = {
isa = PBXProject;
attributes = {
LastSwiftUpdateCheck = 0700;
LastUpgradeCheck = 0900;
TargetAttributes = {
08C28B3F1D501D2C000AE997 = {
CreatedOnToolsVersion = 8.0;
ProvisioningStyle = Automatic;
};
45039161198FFF73004EE2A3 = {
CreatedOnToolsVersion = 6.0;
};
456E51C8197DF0D600A7E488 = {
CreatedOnToolsVersion = 6.0;
};
925383D41BD03C0500F745DB = {
CreatedOnToolsVersion = 7.1;
};
B60A57932009307E006215CB = {
CreatedOnToolsVersion = 9.3;
ProvisioningStyle = Automatic;
};
};
};
buildConfigurationList = 3FFC1BE816A908F800027192 /* Build configuration list for PBXProject "libmalloc" */;
compatibilityVersion = "Xcode 3.2";
developmentRegion = English;
hasScannedForEncodings = 0;
knownRegions = (
en,
);
mainGroup = 3FFC1BE416A908F800027192;
productRefGroup = 3FE91FE916A90AEC00D1238A /* Products */;
projectDirPath = "";
projectRoot = "";
targets = (
3FE9201116A9111000D1238A /* libmalloc */,
45039161198FFF73004EE2A3 /* libmalloc_test */,
3FE91FE716A90AEC00D1238A /* libsystem_malloc */,
B6910F65202B630D00FF2EB0 /* libmalloc_mp */,
B629CF2B202BB337007719B9 /* libmalloc_alt */,
3FE91FFD16A9109E00D1238A /* libmalloc_eOS */,
C0CE452F1C52C90500C24048 /* libmalloc_static */,
B6D2ED492007D76F007AF994 /* libmalloc_replay */,
456E51C8197DF0D600A7E488 /* libmalloc_stress_test */,
08C28B3F1D501D2C000AE997 /* radix-tree */,
925383D41BD03C0500F745DB /* darwintests */,
B60A57932009307E006215CB /* executables */,
);
};
/* End PBXProject section */
/* Begin PBXShellScriptBuildPhase section */
3FC1927C16DD946500315C26 /* Install Man Pages */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 8;
files = (
);
inputPaths = (
"$(SRCROOT)/xcodescripts/manpages.sh",
);
name = "Install Man Pages";
outputPaths = (
);
runOnlyForDeploymentPostprocessing = 1;
shellPath = "/bin/bash -e";
shellScript = ". \"${SCRIPT_INPUT_FILE_0}\"";
};
3FE9201D16A9143E00D1238A /* Sanitise Headers (rdar://problem/10241868) */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 8;
files = (
);
inputPaths = (
"$(SRCROOT)/xcodescripts/sanitise_headers.sh",
);
name = "Sanitise Headers (rdar://problem/10241868)";
outputPaths = (
);
runOnlyForDeploymentPostprocessing = 1;
shellPath = /bin/sh;
shellScript = ". \"${SCRIPT_INPUT_FILE_0}\"";
};
B629CF2A202BB226007719B9 /* Symlink normal variant */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputPaths = (
);
name = "Symlink normal variant";
outputPaths = (
"$(CONFIGURATION_BUILD_DIR)/$(EXECUTABLE_PREFIX)$(PRODUCT_NAME)_normal$(EXECUTABLE_SUFFIX)",
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = "/bin/bash -e -x";
shellScript = "ln -fs \"${EXECUTABLE_PREFIX}${PRODUCT_NAME}${EXECUTABLE_SUFFIX}\" \"${SCRIPT_OUTPUT_FILE_0}\"";
showEnvVarsInLog = 0;
};
B629CF3E202BB337007719B9 /* Symlink normal variant */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputPaths = (
);
name = "Symlink normal variant";
outputPaths = (
"$(CONFIGURATION_BUILD_DIR)/$(EXECUTABLE_PREFIX)$(PRODUCT_NAME)_normal$(EXECUTABLE_SUFFIX)",
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = "/bin/bash -e -x";
shellScript = "ln -fs \"${EXECUTABLE_PREFIX}${PRODUCT_NAME}${EXECUTABLE_SUFFIX}\" \"${SCRIPT_OUTPUT_FILE_0}\"";
showEnvVarsInLog = 0;
};
C92853A11C767F78001FEAF3 /* Install Codes File */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputPaths = (
"$(SRCROOT)/src/trace.h",
);
name = "Install Codes File";
outputPaths = (
"$(DSTROOT)/usr/local/share/misc/libmalloc.codes",
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/bash;
shellScript = ". \"$PROJECT_DIR\"/xcodescripts/install-codes.sh";
};
/* End PBXShellScriptBuildPhase section */
/* Begin PBXSourcesBuildPhase section */
08C28B3C1D501D2C000AE997 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
084F5E851D502102006CD296 /* radix_tree_debug.c in Sources */,
08FEED021D501F6B00BE8A69 /* radix_tree_main.m in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
3FE91FE416A90AEC00D1238A /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
088C4D771D1AF049005C6B36 /* radix_tree.c in Sources */,
3FE91FED16A90B9200D1238A /* bitarray.c in Sources */,
B66C71DA2034BFAE0047E265 /* malloc_common.c in Sources */,
C95742A01BF681B00027269A /* purgeable_malloc.c in Sources */,
C957429C1BF672F80027269A /* magazine_large.c in Sources */,
3FE91FF016A90B9200D1238A /* magazine_malloc.c in Sources */,
C95742991BF670D00027269A /* magazine_small.c in Sources */,
C99E320B1D6F7366005655A8 /* magazine_rack.c in Sources */,
C95742AB1BF685CB0027269A /* legacy_malloc.c in Sources */,
C932D2681D6B8D840063B19E /* vm.c in Sources */,
3FE91FF116A90B9200D1238A /* magmallocProvider.d in Sources */,
0D468DCF1C7BEF51006FACF5 /* magazine_lite.c in Sources */,
B68B7FA51FCDD9A500BAD1AA /* nanov2_malloc.c in Sources */,
B6D5C7F1202E26F80035E376 /* resolver.c in Sources */,
B68B7F9F1FCDCBC600BAD1AA /* nano_malloc_common.c in Sources */,
3FE91FF216A90B9200D1238A /* malloc.c in Sources */,
C95742A61BF6842F0027269A /* frozen_malloc.c in Sources */,
3FE91FF416A90B9200D1238A /* nano_malloc.c in Sources */,
3FE91FF616A90B9200D1238A /* stack_logging_disk.c in Sources */,
C95742901BF419DF0027269A /* magazine_tiny.c in Sources */,
B65FBE2C2087AA2F00E21F59 /* malloc_printf.c in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
3FE91FFE16A9109E00D1238A /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
B66C71DB2034BFD30047E265 /* malloc_common.c in Sources */,
3FE91FFF16A9109E00D1238A /* bitarray.c in Sources */,
C95742A11BF681B00027269A /* purgeable_malloc.c in Sources */,
C957429D1BF672F80027269A /* magazine_large.c in Sources */,
3FE9200116A9109E00D1238A /* magazine_malloc.c in Sources */,
C957429A1BF670D00027269A /* magazine_small.c in Sources */,
C95742AC1BF685CB0027269A /* legacy_malloc.c in Sources */,
B68B7FA01FCDCBE700BAD1AA /* nano_malloc_common.c in Sources */,
B68B7FA61FCDD9B200BAD1AA /* nanov2_malloc.c in Sources */,
3FE9200216A9109E00D1238A /* magmallocProvider.d in Sources */,
3FE9200316A9109E00D1238A /* malloc.c in Sources */,
C95742A71BF6842F0027269A /* frozen_malloc.c in Sources */,
3FE9200416A9109E00D1238A /* nano_malloc.c in Sources */,
3FE9200616A9109E00D1238A /* stack_logging_disk.c in Sources */,
C95742911BF419DF0027269A /* magazine_tiny.c in Sources */,
B6D5C7F4202E26F90035E376 /* resolver.c in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
456E51C5197DF0D600A7E488 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
925383DA1BD03D5100F745DB /* stress_test.c in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
B629CF2C202BB337007719B9 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
B629CF2D202BB337007719B9 /* radix_tree.c in Sources */,
B629CF2E202BB337007719B9 /* bitarray.c in Sources */,
B629CF2F202BB337007719B9 /* purgeable_malloc.c in Sources */,
B6D5C7F3202E26F90035E376 /* resolver.c in Sources */,
B629CF30202BB337007719B9 /* magazine_large.c in Sources */,
B629CF31202BB337007719B9 /* magazine_malloc.c in Sources */,
B629CF32202BB337007719B9 /* empty.s in Sources */,
B629CF33202BB337007719B9 /* magazine_small.c in Sources */,
B629CF34202BB337007719B9 /* legacy_malloc.c in Sources */,
B629CF35202BB337007719B9 /* magmallocProvider.d in Sources */,
B629CF36202BB337007719B9 /* malloc.c in Sources */,
B629CF37202BB337007719B9 /* frozen_malloc.c in Sources */,
B629CF38202BB337007719B9 /* nanov2_malloc.c in Sources */,
B629CF39202BB337007719B9 /* nano_malloc.c in Sources */,
B629CF3A202BB337007719B9 /* stack_logging_disk.c in Sources */,
B629CF3B202BB337007719B9 /* magazine_tiny.c in Sources */,
B629CF3C202BB337007719B9 /* nano_malloc_common.c in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
B6910F66202B630D00FF2EB0 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
B6910F67202B630D00FF2EB0 /* radix_tree.c in Sources */,
B6910F68202B630D00FF2EB0 /* bitarray.c in Sources */,
B6910F69202B630D00FF2EB0 /* purgeable_malloc.c in Sources */,
B6D5C7F2202E26F80035E376 /* resolver.c in Sources */,
B6910F6A202B630D00FF2EB0 /* magazine_large.c in Sources */,
B6910F6B202B630D00FF2EB0 /* magazine_malloc.c in Sources */,
B6910F6C202B630D00FF2EB0 /* empty.s in Sources */,
B6910F6D202B630D00FF2EB0 /* magazine_small.c in Sources */,
B6910F6E202B630D00FF2EB0 /* legacy_malloc.c in Sources */,
B6910F6F202B630D00FF2EB0 /* magmallocProvider.d in Sources */,
B6910F70202B630D00FF2EB0 /* malloc.c in Sources */,
B6910F71202B630D00FF2EB0 /* frozen_malloc.c in Sources */,
B629CF28202BA149007719B9 /* nanov2_malloc.c in Sources */,
B6910F73202B630D00FF2EB0 /* nano_malloc.c in Sources */,
B6910F74202B630D00FF2EB0 /* stack_logging_disk.c in Sources */,
B6910F75202B630D00FF2EB0 /* magazine_tiny.c in Sources */,
B6910F76202B630D00FF2EB0 /* nano_malloc_common.c in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
B6D2ED4A2007D76F007AF994 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
B6D2ED572007D91A007AF994 /* malloc_replay.cpp in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
C0CE45301C52C90500C24048 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
088C4D841D1AF16F005C6B36 /* radix_tree.c in Sources */,
C0CE45311C52C90500C24048 /* bitarray.c in Sources */,
C0CE45321C52C90500C24048 /* purgeable_malloc.c in Sources */,
B6D5C7F5202E26FA0035E376 /* resolver.c in Sources */,
C0CE45331C52C90500C24048 /* magazine_large.c in Sources */,
C0CE45341C52C90500C24048 /* magazine_malloc.c in Sources */,
C9ABCA051CB6FC6800ECB399 /* empty.s in Sources */,
C0CE45351C52C90500C24048 /* magazine_small.c in Sources */,
C0CE45361C52C90500C24048 /* legacy_malloc.c in Sources */,
C0CE45371C52C90500C24048 /* magmallocProvider.d in Sources */,
C0CE45381C52C90500C24048 /* malloc.c in Sources */,
C0CE45391C52C90500C24048 /* frozen_malloc.c in Sources */,
B68B7FA71FCDD9B200BAD1AA /* nanov2_malloc.c in Sources */,
B66C71DC2034BFD40047E265 /* malloc_common.c in Sources */,
C0CE453A1C52C90500C24048 /* nano_malloc.c in Sources */,
C0CE453C1C52C90500C24048 /* stack_logging_disk.c in Sources */,
C0CE453D1C52C90500C24048 /* magazine_tiny.c in Sources */,
B68B7FA11FCDCBE800BAD1AA /* nano_malloc_common.c in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXSourcesBuildPhase section */
/* Begin PBXTargetDependency section */
3FE9201616A9111400D1238A /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
target = 3FE91FFD16A9109E00D1238A /* libmalloc_eOS */;
targetProxy = 3FE9201516A9111400D1238A /* PBXContainerItemProxy */;
};
3FE9201816A9111600D1238A /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
target = 3FE91FE716A90AEC00D1238A /* libsystem_malloc */;
targetProxy = 3FE9201716A9111600D1238A /* PBXContainerItemProxy */;
};
45039168198FFFA6004EE2A3 /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
target = 456E51C8197DF0D600A7E488 /* libmalloc_stress_test */;
targetProxy = 45039167198FFFA6004EE2A3 /* PBXContainerItemProxy */;
};
925383D91BD03D0000F745DB /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
target = 925383D41BD03C0500F745DB /* darwintests */;
targetProxy = 925383D81BD03D0000F745DB /* PBXContainerItemProxy */;
};
B60A579820093093006215CB /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
target = B6D2ED492007D76F007AF994 /* libmalloc_replay */;
targetProxy = B60A579720093093006215CB /* PBXContainerItemProxy */;
};
B629CF44202BB389007719B9 /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
target = B629CF2B202BB337007719B9 /* libmalloc_alt */;
targetProxy = B629CF43202BB389007719B9 /* PBXContainerItemProxy */;
};
B676F4AC202B66EF00933F6D /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
target = B6910F65202B630D00FF2EB0 /* libmalloc_mp */;
targetProxy = B676F4AB202B66EF00933F6D /* PBXContainerItemProxy */;
};
C0CE45501C52CCBD00C24048 /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
target = C0CE452F1C52C90500C24048 /* libmalloc_static */;
targetProxy = C0CE454F1C52CCBD00C24048 /* PBXContainerItemProxy */;
};
/* End PBXTargetDependency section */
/* Begin XCBuildConfiguration section */
08C28B451D501D2C000AE997 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
PRODUCT_NAME = "$(TARGET_NAME)";
};
name = Debug;
};
08C28B461D501D2C000AE997 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
PRODUCT_NAME = "$(TARGET_NAME)";
};
name = Release;
};
3FE91FEB16A90AEC00D1238A /* Debug */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = B629CF29202BA3C2007719B9 /* libmalloc_resolver.xcconfig */;
buildSettings = {
COMBINE_HIDPI_IMAGES = YES;
};
name = Debug;
};
3FE91FEC16A90AEC00D1238A /* Release */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = B629CF29202BA3C2007719B9 /* libmalloc_resolver.xcconfig */;
buildSettings = {
COMBINE_HIDPI_IMAGES = YES;
};
name = Release;
};
3FE9200E16A9109E00D1238A /* Debug */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = 3FE91FE116A90A8D00D1238A /* libmalloc_eos.xcconfig */;
buildSettings = {
COMBINE_HIDPI_IMAGES = YES;
};
name = Debug;
};
3FE9200F16A9109E00D1238A /* Release */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = 3FE91FE116A90A8D00D1238A /* libmalloc_eos.xcconfig */;
buildSettings = {
COMBINE_HIDPI_IMAGES = YES;
};
name = Release;
};
3FE9201316A9111000D1238A /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
COMBINE_HIDPI_IMAGES = YES;
PRODUCT_NAME = "$(TARGET_NAME)";
};
name = Debug;
};
3FE9201416A9111000D1238A /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
COMBINE_HIDPI_IMAGES = YES;
PRODUCT_NAME = "$(TARGET_NAME)";
};
name = Release;
};
3FFC1BE916A908F800027192 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ONLY_ACTIVE_ARCH = YES;
};
name = Debug;
};
3FFC1BEA16A908F800027192 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
};
name = Release;
};
45039163198FFF73004EE2A3 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
PRODUCT_NAME = "$(TARGET_NAME)";
};
name = Debug;
};
45039164198FFF73004EE2A3 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
PRODUCT_NAME = "$(TARGET_NAME)";
};
name = Release;
};
456E51CD197DF0D600A7E488 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_UNREACHABLE_CODE = YES;
COPY_PHASE_STRIP = NO;
GCC_OPTIMIZATION_LEVEL = 0;
GCC_PREPROCESSOR_DEFINITIONS = (
"DEBUG=1",
"$(inherited)",
);
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = macosx.internal;
SUPPORTED_PLATFORMS = "macosx iphoneos appletvos watchos";
};
name = Debug;
};
456E51CE197DF0D600A7E488 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_UNREACHABLE_CODE = YES;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = macosx.internal;
"SKIP_INSTALL[sdk=iphonesimulator*]" = YES;
SUPPORTED_PLATFORMS = "macosx iphoneos appletvos watchos";
};
name = Release;
};
925383D61BD03C0500F745DB /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = macosx.internal;
SUPPORTED_PLATFORMS = "macosx iphoneos appletvos watchos";
};
name = Debug;
};
925383D71BD03C0500F745DB /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = macosx.internal;
SUPPORTED_PLATFORMS = "macosx iphoneos appletvos watchos";
};
name = Release;
};
B60A57942009307E006215CB /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
CODE_SIGN_STYLE = Automatic;
PRODUCT_NAME = "$(TARGET_NAME)";
};
name = Debug;
};
B60A57952009307E006215CB /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
CODE_SIGN_STYLE = Automatic;
PRODUCT_NAME = "$(TARGET_NAME)";
};
name = Release;
};
B629CF40202BB337007719B9 /* Debug */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = B66AA658202A70B00019D607 /* libmalloc_resolved.xcconfig */;
buildSettings = {
COMBINE_HIDPI_IMAGES = YES;
PRODUCT_NAME = "$(PRODUCT_NAME)";
RESOLVED_VARIANT = alt;
};
name = Debug;
};
B629CF41202BB337007719B9 /* Release */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = B66AA658202A70B00019D607 /* libmalloc_resolved.xcconfig */;
buildSettings = {
COMBINE_HIDPI_IMAGES = YES;
PRODUCT_NAME = "$(PRODUCT_NAME)";
RESOLVED_VARIANT = alt;
};
name = Release;
};
B6910F87202B630D00FF2EB0 /* Debug */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = B66AA658202A70B00019D607 /* libmalloc_resolved.xcconfig */;
buildSettings = {
COMBINE_HIDPI_IMAGES = YES;
PRODUCT_NAME = "$(PRODUCT_NAME)";
RESOLVED_VARIANT = mp;
};
name = Debug;
};
B6910F88202B630D00FF2EB0 /* Release */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = B66AA658202A70B00019D607 /* libmalloc_resolved.xcconfig */;
buildSettings = {
COMBINE_HIDPI_IMAGES = YES;
PRODUCT_NAME = "$(PRODUCT_NAME)";
RESOLVED_VARIANT = mp;
};
name = Release;
};
B6D2ED4F2007D76F007AF994 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
CLANG_CXX_LANGUAGE_STANDARD = "c++0x";
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_UNREACHABLE_CODE = YES;
COPY_PHASE_STRIP = NO;
FRAMEWORK_SEARCH_PATHS = (
"$(SDKROOT)/System/Library/PrivateFrameworks",
"$(SDKROOT)$(SYSTEM_LIBRARY_DIR)/PrivateFrameworks",
);
GCC_OPTIMIZATION_LEVEL = 0;
GCC_PREPROCESSOR_DEFINITIONS = (
"DEBUG=1",
"$(inherited)",
);
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
HEADER_SEARCH_PATHS = "$(SRCROOT)/src";
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = macosx.internal;
SUPPORTED_PLATFORMS = "macosx iphoneos iphonesimulator appletvos appletvsimulator watchos watchsimulator";
VALID_ARCHS = "armv6 armv7 arm64 arm64_32 armv7k x86_64 x86_64h";
};
name = Debug;
};
B6D2ED502007D76F007AF994 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
CLANG_CXX_LANGUAGE_STANDARD = "c++0x";
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_UNREACHABLE_CODE = YES;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
FRAMEWORK_SEARCH_PATHS = (
"$(SDKROOT)/System/Library/PrivateFrameworks",
"$(SDKROOT)$(SYSTEM_LIBRARY_DIR)/PrivateFrameworks",
);
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
HEADER_SEARCH_PATHS = "$(SRCROOT)/src";
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = macosx.internal;
"SKIP_INSTALL[sdk=iphonesimulator*]" = YES;
SUPPORTED_PLATFORMS = "macosx iphoneos iphonesimulator appletvos appletvsimulator watchos watchsimulator";
VALID_ARCHS = "armv6 armv7 arm64 arm64_32 armv7k x86_64 x86_64h";
};
name = Release;
};
C0CE454A1C52C90500C24048 /* Debug */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = C0CE450E1C52B9E300C24048 /* libmalloc_static.xcconfig */;
buildSettings = {
COMBINE_HIDPI_IMAGES = YES;
PRODUCT_NAME = "$(PRODUCT_NAME)";
};
name = Debug;
};
C0CE454B1C52C90500C24048 /* Release */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = C0CE450E1C52B9E300C24048 /* libmalloc_static.xcconfig */;
buildSettings = {
COMBINE_HIDPI_IMAGES = YES;
PRODUCT_NAME = "$(PRODUCT_NAME)";
};
name = Release;
};
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
08C28B441D501D2C000AE997 /* Build configuration list for PBXNativeTarget "radix-tree" */ = {
isa = XCConfigurationList;
buildConfigurations = (
08C28B451D501D2C000AE997 /* Debug */,
08C28B461D501D2C000AE997 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
3FE91FEA16A90AEC00D1238A /* Build configuration list for PBXNativeTarget "libsystem_malloc" */ = {
isa = XCConfigurationList;
buildConfigurations = (
3FE91FEB16A90AEC00D1238A /* Debug */,
3FE91FEC16A90AEC00D1238A /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
3FE9200D16A9109E00D1238A /* Build configuration list for PBXNativeTarget "libmalloc_eOS" */ = {
isa = XCConfigurationList;
buildConfigurations = (
3FE9200E16A9109E00D1238A /* Debug */,
3FE9200F16A9109E00D1238A /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
3FE9201216A9111000D1238A /* Build configuration list for PBXAggregateTarget "libmalloc" */ = {
isa = XCConfigurationList;
buildConfigurations = (
3FE9201316A9111000D1238A /* Debug */,
3FE9201416A9111000D1238A /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
3FFC1BE816A908F800027192 /* Build configuration list for PBXProject "libmalloc" */ = {
isa = XCConfigurationList;
buildConfigurations = (
3FFC1BE916A908F800027192 /* Debug */,
3FFC1BEA16A908F800027192 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
45039162198FFF73004EE2A3 /* Build configuration list for PBXAggregateTarget "libmalloc_test" */ = {
isa = XCConfigurationList;
buildConfigurations = (
45039163198FFF73004EE2A3 /* Debug */,
45039164198FFF73004EE2A3 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
456E51CF197DF0D600A7E488 /* Build configuration list for PBXNativeTarget "libmalloc_stress_test" */ = {
isa = XCConfigurationList;
buildConfigurations = (
456E51CD197DF0D600A7E488 /* Debug */,
456E51CE197DF0D600A7E488 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
925383D51BD03C0500F745DB /* Build configuration list for PBXLegacyTarget "darwintests" */ = {
isa = XCConfigurationList;
buildConfigurations = (
925383D61BD03C0500F745DB /* Debug */,
925383D71BD03C0500F745DB /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
B60A57962009307E006215CB /* Build configuration list for PBXAggregateTarget "executables" */ = {
isa = XCConfigurationList;
buildConfigurations = (
B60A57942009307E006215CB /* Debug */,
B60A57952009307E006215CB /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
B629CF3F202BB337007719B9 /* Build configuration list for PBXNativeTarget "libmalloc_alt" */ = {
isa = XCConfigurationList;
buildConfigurations = (
B629CF40202BB337007719B9 /* Debug */,
B629CF41202BB337007719B9 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
B6910F86202B630D00FF2EB0 /* Build configuration list for PBXNativeTarget "libmalloc_mp" */ = {
isa = XCConfigurationList;
buildConfigurations = (
B6910F87202B630D00FF2EB0 /* Debug */,
B6910F88202B630D00FF2EB0 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
B6D2ED4E2007D76F007AF994 /* Build configuration list for PBXNativeTarget "libmalloc_replay" */ = {
isa = XCConfigurationList;
buildConfigurations = (
B6D2ED4F2007D76F007AF994 /* Debug */,
B6D2ED502007D76F007AF994 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
C0CE45491C52C90500C24048 /* Build configuration list for PBXNativeTarget "libmalloc_static" */ = {
isa = XCConfigurationList;
buildConfigurations = (
C0CE454A1C52C90500C24048 /* Debug */,
C0CE454B1C52C90500C24048 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */
};
rootObject = 3FFC1BE516A908F800027192 /* Project object */;
}
================================================
FILE: InterView-obj-isa-class/libmalloc-166.220.1/man/malloc.3
================================================
.\" Copyright (c) 2006 Apple Computer, Inc. All rights reserved.
.\"
.\" @APPLE_LICENSE_HEADER_START@
.\"
.\" The contents of this file constitute Original Code as defined in and
.\" are subject to the Apple Public Source License Version 1.1 (the
.\" "License"). You may not use this file except in compliance with the
.\" License. Please obtain a copy of the License at
.\" http://www.apple.com/publicsource and read it before using this file.
.\"
.\" This Original Code and all software distributed under the License are
.\" distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, EITHER
.\" EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
.\" INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
.\" FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT. Please see the
.\" License for the specific language governing rights and limitations
.\" under the License.
.\"
.\" @APPLE_LICENSE_HEADER_END@
.\"
.Dd Aug 13, 2008
.Dt MALLOC 3
.Os
.Sh NAME
.Nm calloc ,
.Nm free ,
.Nm malloc ,
.Nm realloc ,
.Nm reallocf ,
.Nm valloc
.Nd memory allocation
.Sh SYNOPSIS
.In stdlib.h
.Ft void *
.Fo calloc
.Fa "size_t count"
.Fa "size_t size"
.Fc
.Ft void
.Fo free
.Fa "void *ptr"
.Fc
.Ft void *
.Fo malloc
.Fa "size_t size"
.Fc
.Ft void *
.Fo realloc
.Fa "void *ptr"
.Fa "size_t size"
.Fc
.Ft void *
.Fo reallocf
.Fa "void *ptr"
.Fa "size_t size"
.Fc
.Ft void *
.Fo valloc
.Fa "size_t size"
.Fc
.Sh DESCRIPTION
The
.Fn malloc ,
.Fn calloc ,
.Fn valloc ,
.Fn realloc ,
and
.Fn reallocf
functions allocate memory.
The allocated memory is aligned such that it can be used for any data type,
including AltiVec- and SSE-related types.
The
.Fn free
function frees allocations that were created via the preceding allocation
functions.
.Pp
The
.Fn malloc
function allocates
.Fa size
bytes of memory and returns a pointer to the allocated memory.
.Pp
The
.Fn calloc
function contiguously allocates enough space for
.Fa count
objects that are
.Fa size
bytes of memory each and returns a pointer to the allocated memory.
The allocated memory is filled with bytes of value zero.
.Pp
The
.Fn valloc
function allocates
.Fa size
bytes of memory and returns a pointer to the allocated memory.
The allocated memory is aligned on a page boundary.
.Pp
The
.Fn realloc
function tries to change the size of the allocation pointed to by
.Fa ptr
to
.Fa size ,
and returns
.Fa ptr .
If there is not enough room to enlarge the memory allocation pointed to by
.Fa ptr ,
.Fn realloc
creates a new allocation, copies as much of the old data pointed to by
.Fa ptr
as will fit to the new allocation, frees the old allocation, and returns a
pointer to the allocated memory.
If
.Fa ptr
is
.Dv NULL ,
.Fn realloc
is identical to a call to
.Fn malloc
for
.Fa size
bytes.
If
.Fa size
is zero and
.Fa ptr
is not
.Dv NULL ,
a new, minimum sized object is allocated and the original object is freed.
When extending a region allocated with calloc(3), realloc(3) does not guarantee
that the additional memory is also zero-filled.
.Pp
The
.Fn reallocf
function is identical to the
.Fn realloc
function, except that it
will free the passed pointer when the requested memory cannot be allocated.
This is a
.Fx
specific API designed to ease the problems with traditional coding styles
for realloc causing memory leaks in libraries.
.Pp
The
.Fn free
function deallocates the memory allocation pointed to by
.Fa ptr . If
.Fa ptr
is a NULL pointer, no operation is performed.
.Sh RETURN VALUES
If successful,
.Fn calloc ,
.Fn malloc ,
.Fn realloc ,
.Fn reallocf ,
and
.Fn valloc
functions return a pointer to allocated memory.
If there is an error, they return a
.Dv NULL
pointer and set
.Va errno
to
.Er ENOMEM .
.Pp
For
.Fn realloc ,
the input pointer is still valid if reallocation failed.
For
.Fn reallocf ,
the input pointer will have been freed if reallocation failed.
.Pp
The
.Fn free
function does not return a value.
.Sh DEBUGGING ALLOCATION ERRORS
A number of facilities are provided to aid in debugging allocation errors in
applications.
These facilities are primarily controlled via environment variables.
The recognized environment variables and their meanings are documented below.
.Sh ENVIRONMENT
The following environment variables change the behavior of the
allocation-related functions.
.Bl -tag -width ".Ev MallocStackLoggingNoCompact"
.It Ev MallocDebugReport
If set, specifies where messages are written. Set to "stderr" to write messages
to the standard error stream, "none" to discard all messages and "crash" to
write messages to standard error only for a condition that is about to cause a
crash. When not set, message are written to the standard error stream if it
appears to be a terminal (that is, if isatty(STDERR_FILENO) returns a non-zero
value) and are otherwise discarded.
.It Ev MallocGuardEdges
If set, add a guard page before and after each large block.
.It Ev MallocDoNotProtectPrelude
If set, do not add a guard page before large blocks,
even if the
.Ev MallocGuardEdges
environment variable is set.
.It Ev MallocDoNotProtectPostlude
If set, do not add a guard page after large blocks,
even if the
.Ev MallocGuardEdges
environment variable is set.
.It Ev MallocStackLogging
The default behavior if this is set is to record all allocation and deallocation events to an on-disk log, along with stacks, so that tools like
.Xr leaks 1
and
.Xr malloc_history 1
can be used.
.Pp
Set to "vm" to record only allocation of virtual memory regions allocated by system calls and mach traps, such as by
.Xr mmap 1
.
.Pp
Set to "malloc" to record only allocations via
.Xr malloc 3
and related interfaces, not virtual memory regions.
.Pp
Set to "lite" to record current allocations only, not history. These are recorded by in-memory data structures, instead of an on-disk log.
.It Ev MallocStackLoggingNoCompact
If set, record all stacks in a manner that is compatible with the
.Nm malloc_history
program.
.It Ev MallocStackLoggingDirectory
If set, records stack logs to the directory specified instead of saving them to the default location (/tmp).
.It Ev MallocScribble
If set, fill memory that has been allocated with 0xaa bytes.
This increases the likelihood that a program making assumptions about the contents of
freshly allocated memory will fail.
Also if set, fill memory that has been deallocated with 0x55 bytes.
This increases the likelihood that a program will fail due to accessing memory
that is no longer allocated. Note that due to the way in which freed memory is
managed internally, the 0x55 pattern may not appear in some parts of a
deallocated memory block.
.It Ev MallocCheckHeapStart
If set, specifies the number of allocations
.Fa
to wait before begining periodic heap checks every
.Fa
as specified by
.Ev MallocCheckHeapEach .
If
.Ev MallocCheckHeapStart
is set but
.Ev MallocCheckHeapEach
is not specified, the default check repetition is 1000.
.It Ev MallocCheckHeapEach
If set, run a consistency check on the heap every
.Fa
operations.
.Ev MallocCheckHeapEach
is only meaningful if
.Ev MallocCheckHeapStart
is also set.
.It Ev MallocCheckHeapSleep
Sets the number of seconds to sleep (waiting for a debugger to attach) when
.Ev MallocCheckHeapStart
is set and a heap corruption is detected.
The default is 100 seconds.
Setting this to zero means not to sleep at all.
Setting this to a negative number means to sleep (for the positive number of
seconds) only the very first time a heap corruption is detected.
.It Ev MallocCheckHeapAbort
When
.Ev MallocCheckHeapStart
is set and this is set to a non-zero value, causes
.Xr abort 3
to be called if a heap corruption is detected, instead of any sleeping.
.It Ev MallocErrorAbort
If set, causes
.Xr abort 3
to be called if an error was encountered in
.Xr malloc 3
or
.Xr free 3
, such as a calling
.Xr free 3
on a pointer previously freed.
.It Ev MallocCorruptionAbort
Similar to
.Ev MallocErrorAbort
but will not abort in out of memory conditions, making it more useful to catch
only those errors which will cause memory corruption.
MallocCorruptionAbort is always set on 64-bit processes.
.It Ev MallocHelp
If set, print a list of environment variables that are paid heed to by the
allocation-related functions, along with short descriptions.
The list should correspond to this documentation.
.El
.Sh DIAGNOSTIC MESSAGES
.Sh SEE ALSO
.Xr leaks 1 ,
.Xr malloc_history 1 ,
.Xr abort 3 ,
.Xr malloc_size 3 ,
.Xr malloc_zone_malloc 3 ,
.Xr posix_memalign 3 ,
.Xr libgmalloc 3
================================================
FILE: InterView-obj-isa-class/libmalloc-166.220.1/man/malloc_size.3
================================================
.\" Copyright (c) 2006 Apple Computer, Inc. All rights reserved.
.\"
.\" @APPLE_LICENSE_HEADER_START@
.\"
.\" The contents of this file constitute Original Code as defined in and
.\" are subject to the Apple Public Source License Version 1.1 (the
.\" "License"). You may not use this file except in compliance with the
.\" License. Please obtain a copy of the License at
.\" http://www.apple.com/publicsource and read it before using this file.
.\"
.\" This Original Code and all software distributed under the License are
.\" distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, EITHER
.\" EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
.\" INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
.\" FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT. Please see the
.\" License for the specific language governing rights and limitations
.\" under the License.
.\"
.\" @APPLE_LICENSE_HEADER_END@
.\"
.Dd May 23, 2006
.Dt MALLOC_SIZE 3
.Os
.Sh NAME
.Nm malloc_good_size ,
.Nm malloc_size
.Nd memory allocation information
.Sh SYNOPSIS
.In malloc/malloc.h
.Ft size_t
.Fo malloc_good_size
.Fa "size_t size"
.Fc
.Ft size_t
.Fo malloc_size
.Fa "const void *ptr"
.Fc
.Sh DESCRIPTION
The
.Fn malloc_size
function returns the size of the memory block
that backs the allocation pointed to by
.Fa ptr .
The memory block size is always at least as large
as the allocation it backs, and may be larger.
.Pp
The
.Fn malloc_good_size
function rounds
.Fa size
up to a value that the allocator implementation can allocate
without adding any padding;
it then returns that rounded-up value.
.Sh SEE ALSO
.Xr malloc 3
================================================
FILE: InterView-obj-isa-class/libmalloc-166.220.1/man/malloc_zone_malloc.3
================================================
.\" Copyright (c) 2008 Apple, Inc. All rights reserved.
.\"
.\" @APPLE_LICENSE_HEADER_START@
.\"
.\" The contents of this file constitute Original Code as defined in and
.\" are subject to the Apple Public Source License Version 1.1 (the
.\" "License"). You may not use this file except in compliance with the
.\" License. Please obtain a copy of the License at
.\" http://www.apple.com/publicsource and read it before using this file.
.\"
.\" This Original Code and all software distributed under the License are
.\" distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, EITHER
.\" EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
.\" INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
.\" FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT. Please see the
.\" License for the specific language governing rights and limitations
.\" under the License.
.\"
.\" @APPLE_LICENSE_HEADER_END@
.\"
.Dd Aug 13, 2008
.Dt MALLOC_ZONE_MALLOC 3
.Os
.Sh NAME
.Nm malloc_create_zone ,
.Nm malloc_destroy_zone ,
.Nm malloc_default_zone ,
.Nm malloc_zone_from_ptr ,
.Nm malloc_zone_malloc ,
.Nm malloc_zone_calloc ,
.Nm malloc_zone_valloc ,
.Nm malloc_zone_realloc ,
.Nm malloc_zone_memalign ,
.Nm malloc_zone_free
.Nd zone-based memory allocation
.Sh SYNOPSIS
.In malloc/malloc.h
.Ft malloc_zone_t *
.Fo malloc_create_zone
.Fa "vm_size_t start_size"
.Fa "unsigned flags"
.Fc
.Ft void
.Fo malloc_destroy_zone
.Fa "malloc_zone_t *zone"
.Fc
.Ft malloc_zone_t *
.Fo malloc_default_zone
.Fa void
.Fc
.Ft malloc_zone_t *
.Fo malloc_zone_from_ptr
.Fa "const void *ptr"
.Fc
.Ft void *
.Fo malloc_zone_malloc
.Fa "malloc_zone_t *zone"
.Fa "size_t size"
.Fc
.Ft void *
.Fo malloc_zone_calloc
.Fa "malloc_zone_t *zone"
.Fa "size_t num_items"
.Fa "size_t size"
.Fc
.Ft void *
.Fo malloc_zone_valloc
.Fa "malloc_zone_t *zone"
.Fa "size_t size"
.Fc
.Ft void *
.Fo malloc_zone_realloc
.Fa "malloc_zone_t *zone"
.Fa "void *ptr"
.Fa "size_t size"
.Fc
.Ft void *
.Fo malloc_zone_memalign
.Fa "malloc_zone_t *zone"
.Fa "size_t alignment"
.Fa "size_t size"
.Fc
.Ft void
.Fo malloc_zone_free
.Fa "malloc_zone_t *zone"
.Fa "void *ptr"
.Fc
.Sh DESCRIPTION
The
.Fn malloc_create_zone
function creates a malloc zone, advising an initial allocation of
.Fa start_size
bytes, and specifying
.Fa flags
The returned malloc zone can be used to provide custom allocation and
deallocation behavior, and to retrieve additional information about the
allocations in that zone.
At present there are no client settable flag values recognized by malloc_create_zone(),
the flags argument should always be passed as zero.
.Pp
The
.Fn malloc_destroy_zone
function deallocates all memory associated with objects in
.Fa zone
as well as
.Fa zone
itself.
.Pp
The
.Fn malloc_default_zone
function returns the default system malloc zone, used by
.Xr malloc 3 ,
and
.Xr free 3 .
.Pp
The
.Fn malloc_zone_from_ptr
function returns a pointer to the malloc zone which contains
.Fa ptr
or NULL, if the pointer does not point to an allocated object in any current
malloc zone.
.Pp
The
.Fn malloc_zone_malloc ,
.Fn malloc_zone_calloc ,
.Fn malloc_zone_valloc ,
.Fn malloc_zone_realloc ,
.Fn malloc_zone_memalign ,
and
.Fn malloc_zone_free
perform the same task on
.Fa zone
as their non-prefixed variants,
.Xr malloc 3 ,
.Xr calloc 3 ,
.Xr valloc 3 ,
.Xr realloc 3 ,
.Xr posix_memalign 3 ,
and
.Xr free 3 perform on the default system malloc zone.
.Sh RETURN VALUES
The
.Fn malloc_create_zone ,
.Fn malloc_default_zone ,
and
.Fn malloc_zone_from_ptr
functions return a pointer to a malloc_zone_t structure, or NULL if there was
an error.
.Pp
The
.Fn malloc_zone_malloc ,
.Fn malloc_zone_calloc ,
.Fn malloc_zone_valloc ,
.Fn malloc_zone_realloc ,
and
.Fn malloc_zone_memalign
functions return a pointer to allocated memory. If there is an error, they
return a NULL pointer. They are not required to set
.Va errno .
.Sh SEE ALSO
.Xr malloc 3 ,
.Xr posix_memalign 3
================================================
FILE: InterView-obj-isa-class/libmalloc-166.220.1/man/manpages.lst
================================================
# manpage tables
# [ ...]
# man3
malloc.3 malloc.3 calloc.3 free.3 realloc.3 reallocf.3 valloc.3
malloc_size.3 malloc_size.3 malloc_good_size.3
malloc_zone_malloc.3 malloc_zone_malloc.3 malloc_create_zone.3 malloc_destroy_zone.3 malloc_default_zone.3 malloc_zone_from_ptr.3 malloc_zone_calloc.3 malloc_zone_valloc.3 malloc_zone_realloc.3 malloc_zone_memalign.3 malloc_zone_free.3
================================================
FILE: InterView-obj-isa-class/libmalloc-166.220.1/private/malloc_private.h
================================================
/*
* Copyright (c) 1999-2016 Apple Inc. All rights reserved.
*
* @APPLE_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apple Public Source License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. Please obtain a copy of the License at
* http://www.opensource.apple.com/apsl/ and read it before using this
* file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPLE_LICENSE_HEADER_END@
*/
#ifndef _MALLOC_PRIVATE_H_
#define _MALLOC_PRIVATE_H_
/* Here be dragons (SPIs) */
#include
#include
#include
#include
#include
/********* Callbacks ************/
API_AVAILABLE(macos(10.12), ios(10.0), tvos(10.0), watchos(3.0))
void malloc_enter_process_memory_limit_warn_mode(void);
/* A callback invoked once the process receives a warning for approaching
* memory limit. */
__OSX_AVAILABLE(10.12) __IOS_AVAILABLE(10.0)
__TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0)
void malloc_memory_event_handler(unsigned long);
/* A function invoked when malloc needs to handle any flavor of
* memory pressure notification or process memory limit notification. */
API_AVAILABLE(macos(10.12), ios(10.0), tvos(10.0), watchos(3.0))
void * reallocarray(void * in_ptr, size_t nmemb, size_t size) __DARWIN_EXTSN(reallocarray) __result_use_check;
API_AVAILABLE(macos(10.12), ios(10.0), tvos(10.0), watchos(3.0))
void * reallocarrayf(void * in_ptr, size_t nmemb, size_t size) __DARWIN_EXTSN(reallocarrayf) __result_use_check;
/*
* Checks whether an address might belong to any registered zone. False positives
* are allowed (e.g. the memory was freed, or it's in a part of the address
* space used by malloc that has not yet been allocated.) False negatives are
* not allowed.
*/
API_AVAILABLE(macos(10.14), ios(12.0), tvos(12.0), watchos(5.0))
boolean_t malloc_claimed_address(void *ptr) __result_use_check;
/*
* Checks whether an address might belong to a given zone. False positives are
* allowed (e.g. the memory was freed, or it's in a part of the address space
* used by malloc that has not yet been allocated.) False negatives are not
* allowed.
*/
API_AVAILABLE(macos(10.14), ios(12.0), tvos(12.0), watchos(5.0))
boolean_t malloc_zone_claimed_address(malloc_zone_t *zone, void *ptr) __result_use_check;
/**
* Returns whether the nano allocator is engaged. The return value is 0 if Nano
* is not engaged and the allocator version otherwise.
*/
API_AVAILABLE(macos(10.14), ios(12.0), tvos(12.0), watchos(5.0))
int malloc_engaged_nano(void) __result_use_check;
#endif /* _MALLOC_PRIVATE_H_ */
================================================
FILE: InterView-obj-isa-class/libmalloc-166.220.1/private/stack_logging.h
================================================
/*
* Copyright (c) 1999-2007 Apple Inc. All rights reserved.
*
* @APPLE_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apple Public Source License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. Please obtain a copy of the License at
* http://www.opensource.apple.com/apsl/ and read it before using this
* file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPLE_LICENSE_HEADER_END@
*/
#import
#import
#import
#import
#import
#define STACK_LOGGING_MAX_STACK_SIZE 512
#define stack_logging_type_free 0
#define stack_logging_type_generic 1 /* anything that is not allocation/deallocation */
#define stack_logging_type_alloc 2 /* malloc, realloc, etc... */
#define stack_logging_type_dealloc 4 /* free, realloc, etc... */
#define stack_logging_type_vm_allocate 16 /* vm_allocate or mmap */
#define stack_logging_type_vm_deallocate 32 /* vm_deallocate or munmap */
#define stack_logging_type_mapped_file_or_shared_mem 128
// The valid flags include those from VM_FLAGS_ALIAS_MASK, which give the user_tag of allocated VM regions.
#define stack_logging_valid_type_flags ( \
stack_logging_type_generic | \
stack_logging_type_alloc | \
stack_logging_type_dealloc | \
stack_logging_type_vm_allocate | \
stack_logging_type_vm_deallocate | \
stack_logging_type_mapped_file_or_shared_mem | \
VM_FLAGS_ALIAS_MASK);
// Following flags are absorbed by stack_logging_log_stack()
#define stack_logging_flag_zone 8 /* NSZoneMalloc, etc... */
#define stack_logging_flag_cleared 64 /* for NewEmptyHandle */
#define STACK_LOGGING_VM_USER_TAG(flags) (((flags) & VM_FLAGS_ALIAS_MASK) >> 24)
/* Macro used to disguise addresses so that leak finding can work */
#define STACK_LOGGING_DISGUISE(address) ((address) ^ 0x00005555) /* nicely idempotent */
typedef enum {
stack_logging_mode_none = 0,
stack_logging_mode_all,
stack_logging_mode_malloc,
stack_logging_mode_vm,
stack_logging_mode_lite,
stack_logging_mode_vmlite
} stack_logging_mode_type;
extern boolean_t turn_on_stack_logging(stack_logging_mode_type mode);
extern void turn_off_stack_logging();
/* constants for enabling/disabling malloc stack logging via the memorystatus_vm_pressure_send sysctl */
#define MEMORYSTATUS_ENABLE_MSL_MALLOC 0x10000000
#define MEMORYSTATUS_ENABLE_MSL_VM 0x20000000
#define MEMORYSTATUS_ENABLE_MSL_LITE 0x40000000
#define MEMORYSTATUS_DISABLE_MSL 0x80000000
#define MEMORYSTATUS_ENABLE_MSL_LITE_FULL (MEMORYSTATUS_ENABLE_MSL_LITE | MEMORYSTATUS_ENABLE_MSL_VM | MEMORYSTATUS_ENABLE_MSL_MALLOC)
#define MEMORYSTATUS_ENABLE_MSL_LITE_VM (MEMORYSTATUS_ENABLE_MSL_LITE | MEMORYSTATUS_ENABLE_MSL_VM)
extern void __disk_stack_logging_log_stack(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);
/* Fits as the malloc_logger; logs malloc/free/realloc events and can log custom events if called directly */
/* 64-bit-aware stack log access. As new SPI, these routines are prefixed with double-underscore to avoid conflict with Libsystem clients. */
typedef struct mach_stack_logging_record {
uint32_t type_flags;
uint64_t stack_identifier;
uint64_t argument;
mach_vm_address_t address;
} mach_stack_logging_record_t;
extern kern_return_t __mach_stack_logging_start_reading(task_t task, vm_address_t shared_memory_address, boolean_t *uses_lite_mode);
extern kern_return_t __mach_stack_logging_stop_reading(task_t task);
/* Clients *should* call these start/stop functions to properly initialize stack logging data
* structures and fully clean them up when they're done looking at a process. If the client does *not*
* call these then currently it should still work but some data structures will still remain after
* reading the stack logs (e.g., an extra shared memory segment, an open stack log file, etc).
* NULL can be passed for uses_lite_mode if the client doesn’t need them.
*
* It is recommended that the client suspend the task before actually reading the stacks, and resume the task when done,
* if the task uses lite mode.
*/
extern kern_return_t __mach_stack_logging_set_file_path(task_t task, char* file_path);
extern kern_return_t __mach_stack_logging_get_frames(task_t task, mach_vm_address_t address, mach_vm_address_t *stack_frames_buffer, uint32_t max_stack_frames, uint32_t *count);
/* Gets the last allocation record (malloc, realloc, or free) about address */
extern kern_return_t __mach_stack_logging_enumerate_records(task_t task, mach_vm_address_t address, void enumerator(mach_stack_logging_record_t, void *), void *context);
/* Applies enumerator to all records involving address sending context as enumerator's second parameter; if !address, applies enumerator to all records */
extern kern_return_t __mach_stack_logging_frames_for_uniqued_stack(task_t task, uint64_t stack_identifier, mach_vm_address_t *stack_frames_buffer, uint32_t max_stack_frames, uint32_t *count)
API_DEPRECATED("use __mach_stack_logging_get_frames_for_stackid instead", macos(10.9, 10.13), ios(7.0, 11.0), watchos(1.0, 4.0), tvos(9.0, 11.0));
/* Given a uniqued_stack fills stack_frames_buffer. */
extern kern_return_t __mach_stack_logging_get_frames_for_stackid(task_t task, uint64_t stack_identifier, mach_vm_address_t *stack_frames_buffer, uint32_t max_stack_frames, uint32_t *count,
bool *last_frame_is_threadid)
API_AVAILABLE(macos(10.13), ios(11.0), watchos(4.0), tvos(11.0));
/* Given a uniqued_stack fills stack_frames_buffer. */
extern uint64_t __mach_stack_logging_stackid_for_vm_region(task_t task, mach_vm_address_t address);
/* given the address of a vm region, lookup it's stackid */
struct backtrace_uniquing_table;
extern kern_return_t
__mach_stack_logging_uniquing_table_read_stack(struct backtrace_uniquing_table *uniquing_table,
uint64_t stackid,
mach_vm_address_t *out_frames_buffer,
uint32_t *out_frames_count,
uint32_t max_frames);
extern
struct backtrace_uniquing_table *
__mach_stack_logging_copy_uniquing_table(task_t task);
/* returns a retained pointer to copy of the task's uniquing table */
extern
void
__mach_stack_logging_uniquing_table_release(struct backtrace_uniquing_table *);
extern
void
__mach_stack_logging_uniquing_table_retain(struct backtrace_uniquing_table *);
extern
size_t
__mach_stack_logging_uniquing_table_sizeof(struct backtrace_uniquing_table *);
/* returns the serialized size of a uniquing talbe in bytes */
extern
void *
__mach_stack_logging_uniquing_table_serialize(struct backtrace_uniquing_table *table, mach_vm_size_t *size);
/* Writes out a serialized representation of the table. Free it with mach_vm_deallocate. */
extern
struct backtrace_uniquing_table *
__mach_stack_logging_uniquing_table_copy_from_serialized(void *buffer, size_t size);
/* creates a malloc uniquing table from a serialized representation */
extern void thread_stack_pcs(vm_address_t *buffer, unsigned max, unsigned *num);
/* Convenience to fill buffer with the PCs of the frames, starting with the hot frames;
num: returned number of frames
*/
================================================
FILE: InterView-obj-isa-class/libmalloc-166.220.1/resolver/resolver.c
================================================
/*
* Copyright (c) 2018 Apple Inc. All rights reserved.
*
* @APPLE_APACHE_LICENSE_HEADER_START@
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @APPLE_APACHE_LICENSE_HEADER_END@
*/
================================================
FILE: InterView-obj-isa-class/libmalloc-166.220.1/resolver/resolver.h
================================================
/*
* Copyright (c) 2018 Apple Inc. All rights reserved.
*
* @APPLE_APACHE_LICENSE_HEADER_START@
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @APPLE_APACHE_LICENSE_HEADER_END@
*/
#ifndef __MALLOC_RESOLVER_H__
#define __MALLOC_RESOLVER_H__
#include "resolver_internal.h"
#endif // __MALLOC_RESOLVER_H__
================================================
FILE: InterView-obj-isa-class/libmalloc-166.220.1/resolver/resolver_internal.h
================================================
/*
* Copyright (c) 2018 Apple Inc. All rights reserved.
*
* @APPLE_APACHE_LICENSE_HEADER_START@
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @APPLE_APACHE_LICENSE_HEADER_END@
*/
#ifndef __MALLOC_RESOLVER_INTERNAL_H__
#define __MALLOC_RESOLVER_INTERNAL_H__
#define OS_RESOLVED_VARIANT_ADDR(s) (void *)(&s)
#endif // __MALLOC_RESOLVER_INTERNAL_H__
================================================
FILE: InterView-obj-isa-class/libmalloc-166.220.1/src/base.h
================================================
/*
* Copyright (c) 2015 Apple Inc. All rights reserved.
*
* @APPLE_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apple Public Source License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. Please obtain a copy of the License at
* http://www.opensource.apple.com/apsl/ and read it before using this
* file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPLE_LICENSE_HEADER_END@
*/
#ifndef __BASE_H
#define __BASE_H
#ifndef __has_extension
#define __has_extension(x) 0
#endif
#if __has_extension(c_static_assert)
#define MALLOC_STATIC_ASSERT(x, y) _Static_assert((x), y)
#else
#define MALLOC_STATIC_ASSERT(x, y)
#endif
#define MALLOC_ASSERT(e) ({ \
if (__builtin_expect(!(e), 0)) { \
__asm__ __volatile__ (""); \
__builtin_trap(); \
} \
})
#define MALLOC_FATAL_ERROR(cause, message) ({ \
_os_set_crash_log_cause_and_message((cause), "FATAL ERROR - " message); \
__asm__ __volatile__ (""); \
__builtin_trap(); \
})
#define MALLOC_REPORT_FATAL_ERROR(cause, message) ({ \
malloc_report(ASL_LEVEL_ERR, "*** FATAL ERROR - " message ".\n"); \
MALLOC_FATAL_ERROR((cause), message); \
})
#if defined(__i386__) || defined(__x86_64__) || defined(__arm__) || defined(__arm64__)
# define __APPLE_API_PRIVATE
# include
# if defined(__i386__) || defined(__x86_64__)
# define _COMM_PAGE_VERSION_REQD 9
# else
# define _COMM_PAGE_VERSION_REQD 3
# endif
# undef __APPLE_API_PRIVATE
#else
# include
#endif
#if defined(__i386__) || defined(__x86_64__)
// nano vs. magazine have different definitions
// for this cache-line size.
# define MALLOC_CACHE_LINE 128
# define MALLOC_NANO_CACHE_LINE 64
#elif defined(__arm__) || defined(__arm64__)
# define MALLOC_CACHE_LINE 64
# define MALLOC_NANO_CACHE_LINE 64
#else
# define MALLOC_CACHE_LINE 32
# define MALLOC_NANO_CACHE_LINE 32
#endif
#define MALLOC_CACHE_ALIGN __attribute__ ((aligned (MALLOC_CACHE_LINE) ))
#define MALLOC_NANO_CACHE_ALIGN __attribute__ ((aligned (MALLOC_NANO_CACHE_LINE) ))
#define MALLOC_EXPORT extern __attribute__((visibility("default")))
#define MALLOC_NOEXPORT __attribute__((visibility("hidden")))
#define MALLOC_NOINLINE __attribute__((noinline))
#define MALLOC_INLINE __inline__
#define MALLOC_ALWAYS_INLINE __attribute__((always_inline))
#define MALLOC_PACKED __attribute__((packed))
#define MALLOC_USED __attribute__((used))
#define MALLOC_UNUSED __attribute__((unused))
#define CHECK_MAGAZINE_PTR_LOCKED(szone, mag_ptr, fun) {}
#define SCRIBBLE_BYTE 0xaa /* allocated scribble */
#define SCRABBLE_BYTE 0x55 /* free()'d scribble */
#define SCRUBBLE_BYTE 0xdd /* madvise(..., MADV_FREE) scriblle */
#define NDEBUG 1
#define trunc_page_quanta(x) trunc_page((x))
#define round_page_quanta(x) round_page((x))
#define vm_page_quanta_size (vm_page_size)
#define vm_page_quanta_shift (vm_page_shift)
// add a guard page before and after each VM region to help debug
#define MALLOC_ADD_GUARD_PAGES (1 << 0)
// do not protect prelude page
#define MALLOC_DONT_PROTECT_PRELUDE (1 << 1)
// do not protect postlude page
#define MALLOC_DONT_PROTECT_POSTLUDE (1 << 2)
// write 0x55 onto free blocks
#define MALLOC_DO_SCRIBBLE (1 << 3)
// call abort() on any malloc error, such as double free or out of memory.
#define MALLOC_ABORT_ON_ERROR (1 << 4)
// allocate objects such that they may be used with VM purgability APIs
#define MALLOC_PURGEABLE (1 << 5)
// call abort() on malloc errors, but not on out of memory.
#define MALLOC_ABORT_ON_CORRUPTION (1 << 6)
// expanded small-zone free list size (256 slots)
#define MALLOC_EXTENDED_SMALL_SLOTS (1 << 7)
/*
* msize - a type to refer to the number of quanta of a tiny or small
* allocation. A tiny block with an msize of 3 would be 3 << SHIFT_TINY_QUANTUM
* bytes in size.
*/
typedef unsigned short msize_t;
typedef unsigned int grain_t; // N.B. wide enough to index all free slots
typedef struct large_entry_s large_entry_t;
typedef struct szone_s szone_t;
typedef struct rack_s rack_t;
typedef struct magazine_s magazine_t;
typedef int mag_index_t;
typedef void *region_t;
#endif // __BASE_H
================================================
FILE: InterView-obj-isa-class/libmalloc-166.220.1/src/bitarray.c
================================================
/*
* Copyright (c) 1999, 2000, 2003, 2005, 2008, 2012 Apple Inc. All rights reserved.
*
* @APPLE_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apple Public Source License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. Please obtain a copy of the License at
* http://www.opensource.apple.com/apsl/ and read it before using this
* file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPLE_LICENSE_HEADER_END@
*/
//
// bitarray.c
// bitarray
//
// Created by Bertrand Serlet on 9/26/10.
// Copyright (c) 2010 Apple. All rights reserved.
//
#include "internal.h"
/******************************** Utilities ***************************/
#define STATIC_INLINE static __inline
STATIC_INLINE unsigned
__ffsll(uint64_t xx)
{
#if defined(__LP64__)
return __builtin_ffsl(xx);
#else
return __builtin_ffsll(xx);
#endif
}
#define BIT_SET(old, bit) ((old) | (1ULL << (bit)))
#define BIT_GET(old, bit) ((old) & (1ULL << (bit)))
#define BIT_ZAP(old, bit) ((old) & ~(1ULL << (bit)))
// several variants below of bit setting or zapping to generate minimal code
// All these do 1 memory read and (maybe) 1 memory write
STATIC_INLINE bool
word_get_bit_simple(uint64_t *word, unsigned bit)
{
uint64_t old = *word;
return BIT_GET(old, bit) != 0;
}
STATIC_INLINE void
word_set_bit_simple(uint64_t *word, unsigned bit)
{
uint64_t old = *word;
*word = BIT_SET(old, bit);
}
STATIC_INLINE bool
word_set_bit_changed(uint64_t *word, unsigned bit)
{
// returns 1 iff word has changed
uint64_t old = *word;
uint64_t new = BIT_SET(old, bit);
if (old == new) {
return 0;
}
*word = new;
return 1;
}
STATIC_INLINE bool
word_set_bit_changed_go_down(uint64_t *word, unsigned bit, bool *was_non_zero)
{
// returns 1 iff word changed
// sets was_non_zero (when something changed)
uint64_t old = *word;
uint64_t new = BIT_SET(old, bit);
if (old == new) {
return 0;
}
*word = new;
*was_non_zero = old != 0;
return 1;
}
STATIC_INLINE bool
word_set_bit_go_down(uint64_t *word, unsigned bit)
{
// returns 1 iff level below should be set too
uint64_t old = *word;
uint64_t new = BIT_SET(old, bit);
if (old == new) {
return 0;
}
*word = new;
return !old;
}
STATIC_INLINE void
word_zap_bit_simple(uint64_t *word, unsigned bit)
{
uint64_t old = *word;
*word = BIT_ZAP(old, bit);
}
STATIC_INLINE bool
word_zap_bit_changed(uint64_t *word, unsigned bit)
{
// returns 1 iff word changed
uint64_t old = *word;
uint64_t new = BIT_ZAP(old, bit);
if (old == new) {
return 0;
}
*word = new;
return 1;
}
STATIC_INLINE bool
word_zap_bit_changed_go_down(uint64_t *word, unsigned bit, bool *is_now_zero)
{
// returns 1 iff word changed
// sets is_now_zero (when something changed)
uint64_t old = *word;
uint64_t new = BIT_ZAP(old, bit);
if (old == new) {
return 0;
}
*word = new;
*is_now_zero = !new;
return 1;
}
STATIC_INLINE bool
word_zap_bit_go_down(uint64_t *word, unsigned bit)
{
// returns 1 iff level below might require a bit-zeroing
uint64_t old = *word;
uint64_t new = BIT_ZAP(old, bit);
if (old == new) {
return 0;
}
*word = new;
return !new;
}
/******************************** Helpers ***************************/
#define NB 9 // number of bits we process at once
// must be at least 6 (64-bit) and 9 seems the best on x86
#define MASKNB ((1 << NB) - 1) // to just keep these bits
#define NUM_64b (1 << (NB - 6)) // number of 64-bit words we process at once
// number of uint64_t of summaries
#define LEVEL0 (NUM_64b)
#define LEVEL1 (LEVEL0 + (1 << NB) * NUM_64b)
#define LEVEL2 (LEVEL1 + (1 << (NB + NB)) * NUM_64b)
#define LEVEL3 (LEVEL2 + (1 << (NB + NB + NB)) * NUM_64b)
#define MAX_LEVEL 5
static const unsigned levels_num_words[] = {
LEVEL0, LEVEL1, LEVEL2, LEVEL3}; // this encodes the number of words reserved for the bitmap summaries at various levels
STATIC_INLINE bool
GET_SIMPLE(uint64_t *word, unsigned bit)
{
return word_get_bit_simple(word + (bit >> 6), bit & 63);
}
STATIC_INLINE void
SET_SIMPLE(uint64_t *word, unsigned bit)
{
word_set_bit_simple(word + (bit >> 6), bit & 63);
}
STATIC_INLINE bool
SET_CHANGED(uint64_t *word, unsigned bit)
{
// returns 1 iff word changed
return word_set_bit_changed(word + (bit >> 6), bit & 63);
}
STATIC_INLINE bool
SET_CHANGED_GO_DOWN(uint64_t *word, unsigned bit, bool *was_non_zero)
{
// returns 1 iff word changed
// sets was_non_zero (when something changed)
return word_set_bit_changed_go_down(word + (bit >> 6), bit & 63, was_non_zero);
}
STATIC_INLINE bool
SET_GO_DOWN(uint64_t *word, unsigned bit)
{
// returns 1 iff level below should be set too
return word_set_bit_go_down(word + (bit >> 6), bit & 63);
}
STATIC_INLINE void
ZAP_SIMPLE(uint64_t *word, unsigned bit)
{
return word_zap_bit_simple(word + (bit >> 6), bit & 63);
}
STATIC_INLINE bool
ZAP_CHANGED(uint64_t *word, unsigned bit)
{
// returns 1 iff word changed
return word_zap_bit_changed(word + (bit >> 6), bit & 63);
}
STATIC_INLINE bool
all_zeros(uint64_t *words)
{
for (unsigned w = 0; w < NUM_64b; w++) {
if (words[w]) {
return 0;
}
}
return 1;
}
STATIC_INLINE bool
ZAP_CHANGED_GO_DOWN(uint64_t *word, unsigned bit, bool *is_now_zero)
{
// returns 1 iff word changed
// sets is_now_zero (when something changed)
bool changed = word_zap_bit_changed_go_down(word + (bit >> 6), bit & 63, is_now_zero);
if (changed && (NUM_64b != 1)) {
// One component went entirely zero, now examine all components in the level
if (!all_zeros(word)) {
*is_now_zero = 0;
}
}
return changed;
}
STATIC_INLINE bool
ZAP_GO_DOWN(uint64_t *word, unsigned bit)
{
// returns 1 iff level below should be changed too
bool changed = word_zap_bit_go_down(word + (bit >> 6), bit & 63);
if (changed && (NUM_64b != 1)) {
// One component went entirely zero, now examine all components in the level
if (!all_zeros(word)) {
return 0;
}
}
return changed;
}
STATIC_INLINE unsigned
FFS(uint64_t *word)
{
// does NUM_64b memory reads, at most
#if NB == 6
return __ffsll(*word);
#else
for (unsigned w = 0; w < NUM_64b; w++) {
unsigned f = __ffsll(word[w]);
if (f) {
return f + (w << 6);
}
}
return 0;
#endif
}
/******************************** Entry Points ***************************/
size_t
bitarray_size(unsigned log_size)
{
assert(log_size <= MAX_LEVEL * NB);
unsigned num = NUM_64b;
if (log_size > NB) {
unsigned level = (log_size - NB - 1) / NB;
num = levels_num_words[level] + (1 << (log_size - 6));
}
return num * sizeof(uint64_t);
}
bitarray_t
bitarray_create(unsigned log_size)
{
return calloc(1, bitarray_size(log_size));
}
bool
bitarray_get(bitarray_t bits, unsigned log_size, index_t index)
{
assert(log_size <= MAX_LEVEL * NB);
assert(index < (1 << log_size));
if (log_size <= NB) {
return GET_SIMPLE(bits, index);
}
unsigned level = (log_size - NB - 1) / NB;
unsigned bit;
bit = index & MASKNB;
index >>= NB;
return GET_SIMPLE(bits + levels_num_words[level] + index * NUM_64b, bit);
}
bool
bitarray_set(bitarray_t bits, unsigned log_size, index_t index)
{
// returns whether changed
assert(log_size <= MAX_LEVEL * NB);
assert(index < (1 << log_size));
if (log_size <= NB) {
return SET_CHANGED(bits, index);
}
unsigned level = (log_size - NB - 1) / NB;
bool was_non_zero;
unsigned bit;
bit = index & MASKNB;
index >>= NB;
// printf("SET_CHANGED_GO_DOWN(bits + %d, %d,…)\n", levels_num_words[level] + index, bit);
if (!SET_CHANGED_GO_DOWN(bits + levels_num_words[level] + index * NUM_64b, bit, &was_non_zero)) {
return 0;
}
if (was_non_zero) {
return 1;
}
switch (level) {
case 3:
bit = index & MASKNB;
index >>= NB;
if (!SET_GO_DOWN(bits + LEVEL2 + index * NUM_64b, bit)) {
return 1;
}
/* no break */
case 2:
bit = index & MASKNB;
index >>= NB;
if (!SET_GO_DOWN(bits + LEVEL1 + index * NUM_64b, bit)) {
return 1;
}
/* no break */
case 1:
bit = index & MASKNB;
index >>= NB;
if (!SET_GO_DOWN(bits + LEVEL0 + index * NUM_64b, bit)) {
return 1;
}
/* no break */
case 0:
SET_SIMPLE(bits, index & MASKNB);
return 1;
default:
MALLOC_FATAL_ERROR(level, "invalid bitarray level");
}
}
bool
bitarray_zap(bitarray_t bits, unsigned log_size, index_t index)
{
assert(log_size <= MAX_LEVEL * NB);
assert(index < (1 << log_size));
if (log_size <= NB) {
return ZAP_CHANGED(bits, index);
}
unsigned level = (log_size - NB - 1) / NB;
bool is_now_zero;
unsigned bit;
bit = index & MASKNB;
index >>= NB;
if (!ZAP_CHANGED_GO_DOWN(bits + levels_num_words[level] + index * NUM_64b, bit, &is_now_zero)) {
return 0;
}
if (!is_now_zero) {
return 1;
}
switch (level) {
case 3:
bit = index & MASKNB;
index >>= NB;
if (!ZAP_GO_DOWN(bits + LEVEL2 + index * NUM_64b, bit)) {
return 1;
}
/* no break */
case 2:
bit = index & MASKNB;
index >>= NB;
if (!ZAP_GO_DOWN(bits + LEVEL1 + index * NUM_64b, bit)) {
return 1;
}
/* no break */
case 1:
bit = index & MASKNB;
index >>= NB;
if (!ZAP_GO_DOWN(bits + LEVEL0 + index * NUM_64b, bit)) {
return 1;
}
/* no break */
case 0:
ZAP_SIMPLE(bits, index & MASKNB);
return 1;
default:
MALLOC_FATAL_ERROR(level, "invalid bitarray level");
}
}
// Note in the following macro that "words" and "base" are variables being written
#define ADJUST_OFFSET_FOR_FFS(words, base, current_level) \
{ \
words += (1 << (NB * current_level)) * NUM_64b; \
base = (base << NB) + FFS(words + base * NUM_64b) - 1; \
}
// Note in the following macro that "words" and "base" are variables being written
#define ADJUST_OFFSET_FOR_FFS_ACROSS_SUMMARIES(words, base, level) \
{ \
switch (level) { \
case 4: \
ADJUST_OFFSET_FOR_FFS(words, base, 0); \
ADJUST_OFFSET_FOR_FFS(words, base, 1); \
ADJUST_OFFSET_FOR_FFS(words, base, 2); \
break; \
case 3: \
ADJUST_OFFSET_FOR_FFS(words, base, 0); \
ADJUST_OFFSET_FOR_FFS(words, base, 1); \
break; \
case 2: \
ADJUST_OFFSET_FOR_FFS(words, base, 0); \
break; \
case 1: \
break; \
default: \
MALLOC_FATAL_ERROR(level, "invalid bitarray level"); \
} \
}
// Note in the following macro that "ix" and "bit" are variables being written
#define ZAP_SUMMARIES(bits, ix, level) \
{ \
unsigned bit; \
switch (level) { \
case 3: \
bit = ix & MASKNB; \
ix >>= NB; \
if (!ZAP_GO_DOWN(bits + LEVEL2 + ix * NUM_64b, bit)) { \
break; \
} \
case 2: \
bit = ix & MASKNB; \
ix >>= NB; \
if (!ZAP_GO_DOWN(bits + LEVEL1 + ix * NUM_64b, bit)) { \
break; \
} \
case 1: \
bit = ix & MASKNB; \
ix >>= NB; \
if (!ZAP_GO_DOWN(bits + LEVEL0 + ix * NUM_64b, bit)) { \
break; \
} \
case 0: \
ZAP_SIMPLE(bits, ix &MASKNB); \
break; \
default: \
MALLOC_FATAL_ERROR(level, "invalid bitarray level"); \
} \
}
index_t
bitarray_first_set(const bitarray_t bits, unsigned log_size)
{
// return 0 if none set
assert(log_size <= MAX_LEVEL * NB);
uint64_t *words = bits;
unsigned bit = FFS(words);
if (log_size <= NB) {
return bit;
}
if (!bit) {
return 0;
}
unsigned level = (log_size - 1) / NB;
index_t base = bit - 1; // offset, in number of uin64_t words
ADJUST_OFFSET_FOR_FFS_ACROSS_SUMMARIES(words, base, level);
words += (1 << (NB * (level - 1))) * NUM_64b;
base = (base << NB) + FFS(words + base * NUM_64b) - 1;
return base + 1; //+1 because bit N is encoded as N+1
}
bool
bitarray_zap_first_set(bitarray_t bits, unsigned log_size, index_t *index)
{
assert(log_size <= MAX_LEVEL * NB);
uint64_t *words = bits;
index_t ix = FFS(words);
if (!ix) {
return 0;
}
unsigned level = (log_size - 1) / NB;
if (!level) {
ix--;
*index = ix;
ZAP_SIMPLE(bits, ix);
return 1;
}
index_t base = ix - 1; // offset, in number of uin64_t words
ADJUST_OFFSET_FOR_FFS_ACROSS_SUMMARIES(words, base, level);
words += (1 << (NB * (level - 1))) * NUM_64b;
base = (base << NB) + FFS(words + base * NUM_64b) - 1;
ix = base;
*index = ix;
assert(ix < (1 << log_size));
level--;
bool is_now_zero;
unsigned bit;
bit = ix & MASKNB;
ix >>= NB;
if (!ZAP_CHANGED_GO_DOWN(bits + levels_num_words[level] + ix * NUM_64b, bit, &is_now_zero)) {
return 1;
}
if (!is_now_zero) {
return 1;
}
ZAP_SUMMARIES(bits, ix, level);
return 1;
}
static unsigned
FFS_and_zap_word(uint64_t *words, unsigned max, index_t *indices, index_t to_be_added)
{
// returns the number of bits zapped
unsigned zapped = 0;
for (unsigned w = 0; w < NUM_64b; w++) {
uint64_t word = words[w];
if (!word) {
continue;
}
while (1) {
unsigned f = __ffsll(word);
assert(f);
f--;
// printf("%d ", f);
indices[zapped++] = f + (w << 6) + to_be_added;
word = BIT_ZAP(word, f);
if (!word) {
break;
}
if (zapped >= max) {
break;
}
}
words[w] = word;
// printf("word=%lld \n", word);
if (zapped >= max) {
break;
}
}
return zapped;
}
unsigned
bitarray_zap_first_set_multiple(bitarray_t bits, unsigned log_size, unsigned max, index_t *indices)
{
assert(log_size <= MAX_LEVEL * NB);
if (log_size <= NB) {
return FFS_and_zap_word(bits, max, indices, 0);
}
unsigned zapped = 0;
unsigned level = (log_size - 1) / NB;
while (zapped < max) {
/*
* the lines in loop could be written just as:
* if (! bitarray_zap_first_set(bits, log_size, indices + zapped)) break;
* zapped++;
* but the code is faster because it wont go up and down in the summaries
*/
uint64_t *words = bits;
index_t ix = FFS(words);
if (!ix) {
return zapped; // if the top level summary is 0, no bit is set
}
index_t base = ix - 1; // offset, in number of uin64_t words
ADJUST_OFFSET_FOR_FFS_ACROSS_SUMMARIES(words, base, level);
words += (1 << (NB * (level - 1))) * NUM_64b; // the beginning of the non-summarized bitarray
uint64_t *word = words + base * NUM_64b; // the first non-zero word
ix = base;
// the idea here is that we zap a whole bunch of bits at once
unsigned z = FFS_and_zap_word(word, max - zapped, indices + zapped, base << NB);
assert(z);
zapped += z;
if ((zapped < max) /* entire word was zapped */ || all_zeros(word) /* partial zap, a priori */) {
// adjust summaries to reflect all zeros in the bitarray
ZAP_SUMMARIES(bits, ix, level - 1);
}
}
return zapped;
}
#if 0
/******************************** Test and debug utilities ***************************/
static void print_ones(const uint64_t *bits, unsigned num_big_words) {
unsigned base = 0;
unsigned num = num_big_words * NUM_64b;
// printf("In print_ones; num=%d, num_big=%d \n", num, num_big_words);
while (num--) {
uint64_t word = *(bits++);
if (word) {
for (unsigned bit = 0; bit < 64; bit++) {
if (word & (1ULL << bit)) { printf("%d ", base + bit); }
}
}
base += 64;
}
}
void bitarray_print(bitarray_t bits, unsigned log_size) {
assert(log_size <= MAX_LEVEL * NB);
printf("bitarray %p log_size=%d\n", bits, log_size);
if (log_size > 4 * NB) {
printf("Level 4: "); print_ones(bits, 1); printf("\n");
printf("Level 3: "); print_ones(bits + LEVEL0, 1 << NB); printf("\n");
printf("Level 2: "); print_ones(bits + LEVEL1, 1 << NB); printf("\n");
printf("Level 1: "); print_ones(bits + LEVEL2, 1 << NB); printf("\n");
printf("Level 0: "); print_ones(bits + LEVEL3, 1 << (log_size - NB)); printf("\n");
} else if (log_size > 3 * NB) {
printf("Level 3: "); print_ones(bits, 1); printf("\n");
printf("Level 2: "); print_ones(bits + LEVEL0, 1 << NB); printf("\n");
printf("Level 1: "); print_ones(bits + LEVEL1, 1 << NB); printf("\n");
printf("Level 0: "); print_ones(bits + LEVEL2, 1 << (log_size - NB)); printf("\n");
} else if (log_size > 2 * NB) {
printf("Level 2: "); print_ones(bits, 1); printf("\n");
printf("Level 1: "); print_ones(bits + LEVEL0, 1 << NB); printf("\n");
printf("Level 0: "); print_ones(bits + LEVEL1, 1 << (log_size - NB)); printf("\n");
} else if (log_size > NB) {
printf("Level 1: "); print_ones(bits, 1); printf("\n");
printf("Level 0: "); print_ones(bits + LEVEL0, 1 << (log_size - NB)); printf("\n");
} else {
printf("Level 0: "); print_ones(bits, 1); printf("\n");
}
}
bool compare_to_truth(bitarray_t bits, unsigned nbits, const bool *truth) {
uint64_t *start = bits;
if (nbits > NB) {
unsigned level = (nbits - NB - 1) / NB;
start += levels_num_words[level];
}
bool ok = 1;
for (unsigned bit = 0; bit < (1 << nbits); bit++) {
bool expected = truth[bit];
uint64_t word = start[bit >> 6];
bool actual = (word >> (bit & 63)) & 1;
if (actual != expected) {
printf("*** # for bit %d, expected=%d actual=%d\n", bit, expected, actual);
ok = 0;
}
}
return ok;
}
unsigned first_set_in_truth(const bool *truth, unsigned log_size) {
for (unsigned bit = 0; bit < (1 << log_size); bit++) {
if (truth[bit]) { return bit + 1; }
}
return 0;
}
void truth_print(const bool *truth, unsigned log_size) {
printf("Truth: ");
for (unsigned bit = 0; bit < (1 << log_size); bit++) {
if (truth[bit]) { printf("%d ", bit); }
}
printf("\n");
}
#endif
/* vim: set noet:ts=4:sw=4:cindent: */
================================================
FILE: InterView-obj-isa-class/libmalloc-166.220.1/src/bitarray.h
================================================
/*
* Copyright (c) 1999, 2000, 2003, 2005, 2008, 2012 Apple Inc. All rights reserved.
*
* @APPLE_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apple Public Source License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. Please obtain a copy of the License at
* http://www.opensource.apple.com/apsl/ and read it before using this
* file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPLE_LICENSE_HEADER_END@
*/
#ifndef __BITARRAY_H
#define __BITARRAY_H
typedef uint64_t *bitarray_t; // array of bits, assumed to be mostly 0
typedef uint32_t index_t; // we limit the number of bits to be a 32-bit quantity
/* A bitarray uses a summarization to be able to quickly say what's the first bit that is set to 1;
All together each of the entry points will do a very small number of memory access (exact number depends on log_size) */
extern size_t bitarray_size(unsigned log_size);
// For a bitarray with 1<> 5 identifies the uint32_t to manipulate in the conceptually contiguous bits array
// (index >> 5) << 1 identifies the uint32_t allowing for the actual interleaving
bits[(index >> 5) << 1] |= (1 << (index & 31));
}
static MALLOC_INLINE MALLOC_ALWAYS_INLINE void
BITARRAY_CLR(uint32_t *bits, msize_t index)
{
bits[(index >> 5) << 1] &= ~(1 << (index & 31));
}
static MALLOC_INLINE MALLOC_ALWAYS_INLINE boolean_t
BITARRAY_BIT(uint32_t *bits, msize_t index)
{
return ((bits[(index >> 5) << 1]) >> (index & 31)) & 1;
}
/* Macros used to manipulate the uint32_t quantity mag_bitmap. */
/* BITMAPV variants are used by tiny. */
#if defined(__LP64__)
// assert(NUM_SLOTS == 64) in which case (slot >> 5) is either 0 or 1
#define BITMAPV_SET(bitmap, slot) (bitmap[(slot) >> 5] |= 1 << ((slot)&31))
#define BITMAPV_CLR(bitmap, slot) (bitmap[(slot) >> 5] &= ~(1 << ((slot)&31)))
#define BITMAPV_BIT(bitmap, slot) ((bitmap[(slot) >> 5] >> ((slot)&31)) & 1)
#define BITMAPV_CTZ(bitmap) (__builtin_ctzl(bitmap))
#else
// assert(NUM_SLOTS == 32) in which case (slot >> 5) is always 0, so code it that way
#define BITMAPV_SET(bitmap, slot) (bitmap[0] |= 1 << (slot))
#define BITMAPV_CLR(bitmap, slot) (bitmap[0] &= ~(1 << (slot)))
#define BITMAPV_BIT(bitmap, slot) ((bitmap[0] >> (slot)) & 1)
#define BITMAPV_CTZ(bitmap) (__builtin_ctz(bitmap))
#endif
/* BITMAPN is used by small. (slot >> 5) takes on values from 0 to 7. */
#define BITMAPN_SET(bitmap, slot) (bitmap[(slot) >> 5] |= 1 << ((slot)&31))
#define BITMAPN_CLR(bitmap, slot) (bitmap[(slot) >> 5] &= ~(1 << ((slot)&31)))
#define BITMAPN_BIT(bitmap, slot) ((bitmap[(slot) >> 5] >> ((slot)&31)) & 1)
/* returns bit # of least-significant one bit, starting at 0 (undefined if !bitmap) */
#define BITMAP32_CTZ(bitmap) (__builtin_ctz(bitmap[0]))
#endif // __BITARRAY_H
================================================
FILE: InterView-obj-isa-class/libmalloc-166.220.1/src/debug.h
================================================
/*
* Copyright (c) 2015 Apple Inc. All rights reserved.
*
* @APPLE_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apple Public Source License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. Please obtain a copy of the License at
* http://www.opensource.apple.com/apsl/ and read it before using this
* file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPLE_LICENSE_HEADER_END@
*/
#ifndef __DEBUG_H
#define __DEBUG_H
// set to one to debug malloc itself
#define DEBUG_MALLOC 0
// set to one to debug malloc client
#define DEBUG_CLIENT 0
#define DEBUG_MADVISE 0
#if DEBUG_MALLOC
# warning DEBUG_MALLOC ENABLED
# undef MALLOC_INLINE
# undef MALLOC_UNUSED
# undef MALLOC_ALWAYS_INLINE
# undef CHECK_MAGAZINE_PTR_LOCKED
# define MALLOC_INLINE
# define MALLOC_UNUSED
# define MALLOC_ALWAYS_INLINE
# define CHECK_MAGAZINE_PTR_LOCKED(szone, mag_ptr, fun) \
do { \
if (TRY_LOCK(mag_ptr->magazine_lock)) { \
malloc_report(ASL_LEVEL_ERR, "*** magazine_lock was not set %p in %s\n", \
mag_ptr->magazine_lock, fun); \
} \
} while (0)
#endif // DEBUG_MALLOC
#if DEBUG_MALLOC || DEBUG_CLIENT
# define CHECK(szone, fun) \
if ((szone)->debug_flags & CHECK_REGIONS) { \
szone_check_all(szone, fun) \
}
#else // DEBUG_MALLOC || DEBUG_CLIENT
# define CHECK(szone, fun) \
do {} while (0)
#endif // DEBUG_MALLOC || DEBUG_CLIENT
#endif // __DEBUG_H
================================================
FILE: InterView-obj-isa-class/libmalloc-166.220.1/src/dtrace.h
================================================
/*
* Copyright (c) 2016 Apple Inc. All rights reserved.
*
* @APPLE_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apple Public Source License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. Please obtain a copy of the License at
* http://www.opensource.apple.com/apsl/ and read it before using this
* file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPLE_LICENSE_HEADER_END@
*/
#ifndef __DTRACE_H
#define __DTRACE_H
#ifndef DARWINTEST
#include "magmallocProvider.h"
#else
#define MAGMALLOC_ALLOCREGION(arg0, arg1, arg2, arg3)
#define MAGMALLOC_ALLOCREGION_ENABLED() (0)
#define MAGMALLOC_DEALLOCREGION(arg0, arg1, arg2)
#define MAGMALLOC_DEALLOCREGION_ENABLED() (0)
#define MAGMALLOC_DEPOTREGION(arg0, arg1, arg2, arg3, arg4)
#define MAGMALLOC_DEPOTREGION_ENABLED() (0)
#define MAGMALLOC_MADVFREEREGION(arg0, arg1, arg2, arg3)
#define MAGMALLOC_MADVFREEREGION_ENABLED() (0)
#define MAGMALLOC_MALLOCERRORBREAK()
#define MAGMALLOC_MALLOCERRORBREAK_ENABLED() (0)
#define MAGMALLOC_PRESSURERELIEFBEGIN(arg0, arg1, arg2)
#define MAGMALLOC_PRESSURERELIEFBEGIN_ENABLED() (0)
#define MAGMALLOC_PRESSURERELIEFEND(arg0, arg1, arg2, arg3)
#define MAGMALLOC_PRESSURERELIEFEND_ENABLED() (0)
#define MAGMALLOC_RECIRCREGION(arg0, arg1, arg2, arg3, arg4)
#define MAGMALLOC_RECIRCREGION_ENABLED() (0)
#define MAGMALLOC_REFRESHINDEX(arg0, arg1, arg2)
#define MAGMALLOC_REFRESHINDEX_ENABLED() (0)
#endif
#endif // __DTRACE_H
================================================
FILE: InterView-obj-isa-class/libmalloc-166.220.1/src/empty.s
================================================
/*
* Copyright (c) 2015 Apple Inc. All rights reserved.
*
* @APPLE_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apple Public Source License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. Please obtain a copy of the License at
* http://www.opensource.apple.com/apsl/ and read it before using this
* file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPLE_LICENSE_HEADER_END@
*/
/*
* This file exists to force clang+ld to produce an link-time optimised
* master object file that contains no bitcode when it is laid down on
* disk.
*
* Adding a non-LTO assembly file to the link step forces ld to perform
* LTO and produce the master object file.
*/
empty:
nop
.subsections_via_symbols
================================================
FILE: InterView-obj-isa-class/libmalloc-166.220.1/src/frozen_malloc.c
================================================
/*
* Copyright (c) 2015 Apple Inc. All rights reserved.
*
* @APPLE_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apple Public Source License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. Please obtain a copy of the License at
* http://www.opensource.apple.com/apsl/ and read it before using this
* file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPLE_LICENSE_HEADER_END@
*/
#include "internal.h"
/********* Support code for emacs unexec ************/
/* History of freezedry version numbers:
*
* 1) Old malloc (before the scalable malloc implementation in this file
* existed).
* 2) Original freezedrying code for scalable malloc. This code was apparently
* based on the old freezedrying code and was fundamentally flawed in its
* assumption that tracking allocated memory regions was adequate to fake
* operations on freezedried memory. This doesn't work, since scalable
* malloc does not store flags in front of large page-aligned allocations.
* 3) Original szone-based freezedrying code.
* 4) Fresher malloc with tiny zone
* 5) 32/64bit compatible malloc
* 6) Metadata within 1MB and 8MB region for tiny and small
*
* No version backward compatibility is provided, but the version number does
* make it possible for malloc_jumpstart() to return an error if the application
* was freezedried with an older version of malloc.
*/
#define MALLOC_FREEZEDRY_VERSION 6
typedef struct {
unsigned version;
unsigned nszones;
szone_t *szones;
} malloc_frozen;
static void *
frozen_malloc(szone_t *zone, size_t new_size)
{
return malloc(new_size);
}
static void *
frozen_calloc(szone_t *zone, size_t num_items, size_t size)
{
return calloc(num_items, size);
}
static void *
frozen_valloc(szone_t *zone, size_t new_size)
{
return valloc(new_size);
}
static void *
frozen_realloc(szone_t *zone, void *ptr, size_t new_size)
{
size_t old_size = szone_size(zone, ptr);
void *new_ptr;
if (new_size <= old_size) {
return ptr;
}
new_ptr = malloc(new_size);
if (old_size > 0) {
memcpy(new_ptr, ptr, old_size);
}
return new_ptr;
}
static void
frozen_free(szone_t *zone, void *ptr)
{
}
static void
frozen_destroy(szone_t *zone)
{
}
/********* Pseudo-private API for emacs unexec ************/
/*
* malloc_freezedry() records all of the szones in use, so that they can be
* partially reconstituted by malloc_jumpstart(). Due to the differences
* between reconstituted memory regions and those created by the szone code,
* care is taken not to reallocate from the freezedried memory, except in the
* case of a non-growing realloc().
*
* Due to the flexibility provided by the zone registration mechanism, it is
* impossible to implement generic freezedrying for any zone type. This code
* only handles applications that use the szone allocator, so malloc_freezedry()
* returns 0 (error) if any non-szone zones are encountered.
*/
uintptr_t
malloc_freezedry(void)
{
extern unsigned malloc_num_zones;
extern malloc_zone_t **malloc_zones;
malloc_frozen *data;
unsigned i;
/* Allocate space in which to store the freezedry state. */
data = (malloc_frozen *)malloc(sizeof(malloc_frozen));
/* Set freezedry version number so that malloc_jumpstart() can check for compatibility. */
data->version = MALLOC_FREEZEDRY_VERSION;
/* Allocate the array of szone pointers. */
data->nszones = malloc_num_zones;
data->szones = (szone_t *)calloc(malloc_num_zones, sizeof(szone_t));
/*
* Fill in the array of szone structures. They are copied rather than
* referenced, since the originals are likely to be clobbered during malloc
* initialization.
*/
for (i = 0; i < malloc_num_zones; i++) {
if (strcmp(malloc_zones[i]->zone_name, "DefaultMallocZone")) {
/* Unknown zone type. */
free(data->szones);
free(data);
return 0;
}
memcpy(&data->szones[i], malloc_zones[i], sizeof(szone_t));
}
return ((uintptr_t)data);
}
int
malloc_jumpstart(uintptr_t cookie)
{
malloc_frozen *data = (malloc_frozen *)cookie;
unsigned i;
if (data->version != MALLOC_FREEZEDRY_VERSION) {
/* Unsupported freezedry version. */
return 1;
}
for (i = 0; i < data->nszones; i++) {
/* Set function pointers. Even the functions that stay the same must be
* set, since there are no guarantees that they will be mapped to the
* same addresses. */
data->szones[i].basic_zone.size = (void *)szone_size;
data->szones[i].basic_zone.malloc = (void *)frozen_malloc;
data->szones[i].basic_zone.calloc = (void *)frozen_calloc;
data->szones[i].basic_zone.valloc = (void *)frozen_valloc;
data->szones[i].basic_zone.free = (void *)frozen_free;
data->szones[i].basic_zone.realloc = (void *)frozen_realloc;
data->szones[i].basic_zone.destroy = (void *)frozen_destroy;
data->szones[i].basic_zone.introspect = (struct malloc_introspection_t *)&szone_introspect;
/* Register the freezedried zone. */
malloc_zone_register(&data->szones[i].basic_zone);
}
return 0;
}
================================================
FILE: InterView-obj-isa-class/libmalloc-166.220.1/src/frozen_malloc.h
================================================
/*
* Copyright (c) 2015 Apple Inc. All rights reserved.
*
* @APPLE_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apple Public Source License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. Please obtain a copy of the License at
* http://www.opensource.apple.com/apsl/ and read it before using this
* file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPLE_LICENSE_HEADER_END@
*/
#ifndef __FROZEN_MALLOC_H
#define __FROZEN_MALLOC_H
MALLOC_EXPORT
uintptr_t
malloc_freezedry(void);
MALLOC_EXPORT
int
malloc_jumpstart(uintptr_t cookie);
#endif // __FROZEN_MALLOC_H
================================================
FILE: InterView-obj-isa-class/libmalloc-166.220.1/src/internal.h
================================================
/*
* Copyright (c) 2015 Apple Inc. All rights reserved.
*
* @APPLE_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apple Public Source License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. Please obtain a copy of the License at
* http://www.opensource.apple.com/apsl/ and read it before using this
* file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPLE_LICENSE_HEADER_END@
*/
#ifndef __INTERNAL_H
#define __INTERNAL_H
#define __OS_EXPOSE_INTERNALS__ 1
#include
#include
#include <_simple.h>
#include
#undef memcpy
#define memcpy _platform_memmove
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include "dtrace.h"
#include "base.h"
#include "trace.h"
#include "platform.h"
#include "debug.h"
#include "locking.h"
#include "bitarray.h"
#include "malloc.h"
#include "printf.h"
#include "frozen_malloc.h"
#include "legacy_malloc.h"
#include "magazine_malloc.h"
#include "malloc_common.h"
#include "nano_malloc_common.h"
#include "nano_malloc.h"
#include "nanov2_malloc.h"
#include "purgeable_malloc.h"
#include "malloc_private.h"
#include "stack_logging.h"
#include "stack_logging_internal.h"
#include "thresholds.h"
#include "vm.h"
#include "magazine_rack.h"
#include "magazine_zone.h"
#include "nano_zone_common.h"
#include "nano_zone.h"
#include "nanov2_zone.h"
#include "magazine_inline.h"
extern uint64_t malloc_entropy[2];
MALLOC_NOEXPORT
extern boolean_t malloc_tracing_enabled;
MALLOC_NOEXPORT
extern unsigned malloc_debug_flags;
MALLOC_NOEXPORT MALLOC_NOINLINE
void
malloc_error_break(void);
MALLOC_NOEXPORT MALLOC_NOINLINE MALLOC_USED
int
malloc_gdb_po_unsafe(void);
MALLOC_NOEXPORT
extern uint64_t max_lite_mallocs;
#endif // __INTERNAL_H
================================================
FILE: InterView-obj-isa-class/libmalloc-166.220.1/src/legacy_malloc.c
================================================
/*
* Copyright (c) 2015 Apple Inc. All rights reserved.
*
* @APPLE_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apple Public Source License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. Please obtain a copy of the License at
* http://www.opensource.apple.com/apsl/ and read it before using this
* file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPLE_LICENSE_HEADER_END@
*/
#include "internal.h"
/*
* For use by CheckFix: create a new zone whose behavior is, apart from
* the use of death-row and per-CPU magazines, that of Leopard.
*/
static MALLOC_NOINLINE void *
legacy_valloc(szone_t *szone, size_t size)
{
void *ptr;
size_t num_kernel_pages;
num_kernel_pages = round_page_quanta(size) >> vm_page_quanta_shift;
ptr = large_malloc(szone, num_kernel_pages, 0, TRUE);
#if DEBUG_MALLOC
if (LOG(szone, ptr)) {
malloc_report(ASL_LEVEL_INFO, "legacy_valloc returned %p\n", ptr);
}
#endif
return ptr;
}
malloc_zone_t *
create_legacy_scalable_zone(size_t initial_size, unsigned debug_flags)
{
// legacy always uses 32 small slots
malloc_zone_t *mzone = create_scalable_zone(initial_size, debug_flags & ~MALLOC_EXTENDED_SMALL_SLOTS);
szone_t *szone = (szone_t *)mzone;
if (!szone) {
return NULL;
}
szone->is_largemem = 0;
szone->large_threshold = (15 * 1024);
szone->vm_copy_threshold = (40 * 1024);
mprotect(szone, sizeof(szone->basic_zone), PROT_READ | PROT_WRITE);
szone->basic_zone.valloc = (void *)legacy_valloc;
szone->basic_zone.free_definite_size = NULL;
mprotect(szone, sizeof(szone->basic_zone), PROT_READ);
return mzone;
}
================================================
FILE: InterView-obj-isa-class/libmalloc-166.220.1/src/legacy_malloc.h
================================================
/*
* Copyright (c) 1999 Apple Computer, Inc. All rights reserved.
*
* @APPLE_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apple Public Source License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. Please obtain a copy of the License at
* http://www.opensource.apple.com/apsl/ and read it before using this
* file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPLE_LICENSE_HEADER_END@
*/
#ifndef __LEGACY_MALLOC_H
#define __LEGACY_MALLOC_H
MALLOC_NOEXPORT
malloc_zone_t *
create_legacy_scalable_zone(size_t initial_size, unsigned debug_flags);
#endif // __LEGACY_MALLOC_H
================================================
FILE: InterView-obj-isa-class/libmalloc-166.220.1/src/locking.h
================================================
/*
* Copyright (c) 2015 Apple Inc. All rights reserved.
*
* @APPLE_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apple Public Source License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. Please obtain a copy of the License at
* http://www.opensource.apple.com/apsl/ and read it before using this
* file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPLE_LICENSE_HEADER_END@
*/
#ifndef __LOCKING_H
#define __LOCKING_H
#if OS_UNFAIR_LOCK_INLINE
#define os_unfair_lock_lock_with_options(lock, options) \
os_unfair_lock_lock_with_options_inline(lock, options)
#define os_unfair_lock_trylock(lock) \
os_unfair_lock_trylock_inline(lock)
#define os_unfair_lock_unlock(lock) \
os_unfair_lock_unlock_inline(lock)
#endif // OS_UNFAIR_LOCK_INLINE
typedef os_unfair_lock _malloc_lock_s;
#define _MALLOC_LOCK_INIT OS_UNFAIR_LOCK_INIT
__attribute__((always_inline))
static inline void
_malloc_lock_init(_malloc_lock_s *lock) {
*lock = OS_UNFAIR_LOCK_INIT;
}
MALLOC_ALWAYS_INLINE
static inline void
_malloc_lock_lock(_malloc_lock_s *lock) {
return os_unfair_lock_lock_with_options(lock,
OS_UNFAIR_LOCK_DATA_SYNCHRONIZATION);
}
MALLOC_ALWAYS_INLINE
static inline bool
_malloc_lock_trylock(_malloc_lock_s *lock) {
return os_unfair_lock_trylock(lock);
}
MALLOC_ALWAYS_INLINE
static inline void
_malloc_lock_unlock(_malloc_lock_s *lock) {
return os_unfair_lock_unlock(lock);
}
MALLOC_ALWAYS_INLINE
static inline void
_malloc_lock_assert_owner(_malloc_lock_s *lock) {
os_unfair_lock_assert_owner(lock);
}
#endif // __LOCKING_H
================================================
FILE: InterView-obj-isa-class/libmalloc-166.220.1/src/magazine_inline.h
================================================
/*
* Copyright (c) 2015 Apple Inc. All rights reserved.
*
* @APPLE_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apple Public Source License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. Please obtain a copy of the License at
* http://www.opensource.apple.com/apsl/ and read it before using this
* file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPLE_LICENSE_HEADER_END@
*/
#ifndef __MAGAZINE_INLINE_H
#define __MAGAZINE_INLINE_H
extern unsigned int _os_cpu_number_override;
/*
* MALLOC_ABSOLUTE_MAX_SIZE - There are many instances of addition to a
* user-specified size_t, which can cause overflow (and subsequent crashes)
* for values near SIZE_T_MAX. Rather than add extra "if" checks everywhere
* this occurs, it is easier to just set an absolute maximum request size,
* and immediately return an error if the requested size exceeds this maximum.
* Of course, values less than this absolute max can fail later if the value
* is still too large for the available memory. The largest value added
* seems to be PAGE_SIZE (in the macro round_page()), so to be safe, we set
* the maximum to be 2 * PAGE_SIZE less than SIZE_T_MAX.
*/
#define MALLOC_ABSOLUTE_MAX_SIZE (SIZE_T_MAX - (2 * PAGE_SIZE))
// Gets the allocation size for a calloc(). Multiples size by num_items and adds
// extra_size, storing the result in *total_size. Returns 0 on success, -1 (with
// errno set to ENOMEM) on overflow.
static int MALLOC_INLINE MALLOC_ALWAYS_INLINE
calloc_get_size(size_t num_items, size_t size, size_t extra_size, size_t *total_size)
{
size_t alloc_size = size;
if (num_items != 1 && (os_mul_overflow(num_items, size, &alloc_size)
|| alloc_size > MALLOC_ABSOLUTE_MAX_SIZE)) {
errno = ENOMEM;
return -1;
}
if (extra_size && (os_add_overflow(alloc_size, extra_size, &alloc_size)
|| alloc_size > MALLOC_ABSOLUTE_MAX_SIZE)) {
errno = ENOMEM;
return -1;
}
*total_size = alloc_size;
return 0;
}
/********************* FREE LIST UTILITIES ************************/
// A free list entry is comprised of a pair of pointers, previous and next.
// These are used to implement a doubly-linked list, which permits efficient
// extraction.
//
// Because the free list entries are previously freed objects, a misbehaved
// program may write to a pointer after it has called free() on that pointer,
// either by dereference or buffer overflow from an adjacent pointer. This write
// would then corrupt the free list's previous and next pointers, leading to a
// crash. In order to detect this case, we take advantage of the fact that
// malloc'd pointers are known to be at least 16 byte aligned, and thus have
// at least 4 trailing zero bits.
//
// When an entry is added to the free list, a checksum of the previous and next
// pointers is calculated and written to the high four bits of the respective
// pointers. Upon detection of an invalid checksum, an error is logged and NULL
// is returned. Since all code which un-checksums pointers checks for a NULL
// return, a potentially crashing or malicious dereference is avoided at the
// cost of leaking the corrupted block, and any subsequent blocks on the free
// list of that size.
#pragma mark forward decls
static MALLOC_INLINE uintptr_t free_list_gen_checksum(uintptr_t ptr) MALLOC_ALWAYS_INLINE;
static MALLOC_INLINE uintptr_t free_list_checksum_ptr(rack_t *rack, void *p) MALLOC_ALWAYS_INLINE;
static MALLOC_INLINE void *free_list_unchecksum_ptr(rack_t *rack, inplace_union *ptr) MALLOC_ALWAYS_INLINE;
static MALLOC_INLINE unsigned free_list_count(rack_t *rack, free_list_t ptr);
static MALLOC_INLINE void recirc_list_extract(rack_t *rack, magazine_t *mag_ptr, region_trailer_t *node) MALLOC_ALWAYS_INLINE;
static MALLOC_INLINE void recirc_list_splice_last(rack_t *rack, magazine_t *mag_ptr, region_trailer_t *node) MALLOC_ALWAYS_INLINE;
static MALLOC_INLINE void recirc_list_splice_first(rack_t *rack, magazine_t *mag_ptr, region_trailer_t *node) MALLOC_ALWAYS_INLINE;
static MALLOC_INLINE void
yield(void)
{
thread_switch(MACH_PORT_NULL, SWITCH_OPTION_DEPRESS, 1);
}
static MALLOC_INLINE kern_return_t
_szone_default_reader(task_t task, vm_address_t address, vm_size_t size, void **ptr)
{
*ptr = (void *)address;
return 0;
}
#pragma mark helpers
static MALLOC_INLINE MALLOC_ALWAYS_INLINE
uint64_t
platform_hw_memsize(void)
{
#if CONFIG_HAS_COMMPAGE_MEMSIZE
return *(uint64_t *)(uintptr_t)_COMM_PAGE_MEMORY_SIZE;
#else
uint64_t hw_memsize = 0;
size_t uint64_t_size = sizeof(hw_memsize);
// hw_memsize was always 0 if sysctlbyname failed, so preserve that behaviour
(void)sysctlbyname("hw.memsize", &hw_memsize, &uint64_t_size, 0, 0);
return hw_memsize;
#endif
}
static MALLOC_INLINE MALLOC_ALWAYS_INLINE
uint32_t
platform_cpu_count(void)
{
#if CONFIG_HAS_COMMPAGE_NCPUS
return *(uint8_t *)(uintptr_t)_COMM_PAGE_NCPUS;
#else
return sysconf(_SC_NPROCESSORS_CONF);
#endif
}
#pragma mark szone locking
static MALLOC_INLINE MALLOC_ALWAYS_INLINE void
SZONE_LOCK(szone_t *szone)
{
_malloc_lock_lock(&szone->large_szone_lock);
}
static MALLOC_INLINE MALLOC_ALWAYS_INLINE void
SZONE_UNLOCK(szone_t *szone)
{
_malloc_lock_unlock(&szone->large_szone_lock);
}
static MALLOC_INLINE MALLOC_ALWAYS_INLINE bool
SZONE_TRY_LOCK(szone_t *szone)
{
return _malloc_lock_trylock(&szone->large_szone_lock);
}
static MALLOC_INLINE MALLOC_ALWAYS_INLINE void
SZONE_REINIT_LOCK(szone_t *szone)
{
_malloc_lock_init(&szone->large_szone_lock);
}
static MALLOC_INLINE MALLOC_ALWAYS_INLINE void
SZONE_MAGAZINE_PTR_LOCK(magazine_t *mag_ptr)
{
_malloc_lock_lock(&mag_ptr->magazine_lock);
}
static MALLOC_INLINE MALLOC_ALWAYS_INLINE void
SZONE_MAGAZINE_PTR_UNLOCK(magazine_t *mag_ptr)
{
_malloc_lock_unlock(&mag_ptr->magazine_lock);
}
static MALLOC_INLINE MALLOC_ALWAYS_INLINE bool
SZONE_MAGAZINE_PTR_TRY_LOCK(magazine_t *mag_ptr)
{
return _malloc_lock_trylock(&mag_ptr->magazine_lock);
}
static MALLOC_INLINE MALLOC_ALWAYS_INLINE void
SZONE_MAGAZINE_PTR_REINIT_LOCK(magazine_t *mag_ptr)
{
_malloc_lock_init(&mag_ptr->magazine_lock);
}
#pragma mark free list
static MALLOC_NOINLINE void
free_list_checksum_botch(rack_t *rack, void *ptr, void *value)
{
malloc_zone_error(rack->debug_flags, true,
"Incorrect checksum for freed object %p: "
"probably modified after being freed.\n"
"Corrupt value: %p\n", ptr, value);
}
static MALLOC_INLINE uintptr_t
free_list_gen_checksum(uintptr_t ptr)
{
uint8_t chk;
chk = (unsigned char)(ptr >> 0);
chk += (unsigned char)(ptr >> 8);
chk += (unsigned char)(ptr >> 16);
chk += (unsigned char)(ptr >> 24);
#if __LP64__
chk += (unsigned char)(ptr >> 32);
chk += (unsigned char)(ptr >> 40);
chk += (unsigned char)(ptr >> 48);
chk += (unsigned char)(ptr >> 56);
#endif
return chk;
}
static unsigned
free_list_count(rack_t *rack, free_list_t ptr)
{
unsigned count = 0;
while (ptr.p) {
count++;
ptr.p = free_list_unchecksum_ptr(rack, &ptr.inplace->next);
}
return count;
}
#define NYBBLE 4
#if __LP64__
#define ANTI_NYBBLE (64 - NYBBLE)
#else
#define ANTI_NYBBLE (32 - NYBBLE)
#endif
static MALLOC_INLINE uintptr_t
free_list_checksum_ptr(rack_t *rack, void *ptr)
{
uintptr_t p = (uintptr_t)ptr;
return (p >> NYBBLE) | ((free_list_gen_checksum(p ^ rack->cookie) & (uintptr_t)0xF) << ANTI_NYBBLE); // compiles to rotate instruction
}
static MALLOC_INLINE void *
free_list_unchecksum_ptr(rack_t *rack, inplace_union *ptr)
{
inplace_union p;
uintptr_t t = ptr->u;
t = (t << NYBBLE) | (t >> ANTI_NYBBLE); // compiles to rotate instruction
p.u = t & ~(uintptr_t)0xF;
if ((t ^ free_list_gen_checksum(p.u ^ rack->cookie)) & (uintptr_t)0xF) {
free_list_checksum_botch(rack, ptr, (void *)ptr->u);
__builtin_trap();
}
return p.p;
}
#undef ANTI_NYBBLE
#undef NYBBLE
#pragma mark recirc helpers
static MALLOC_INLINE void
recirc_list_extract(rack_t *rack, magazine_t *mag_ptr, region_trailer_t *node)
{
// excise node from list
if (NULL == node->prev) {
mag_ptr->firstNode = node->next;
} else {
node->prev->next = node->next;
}
if (NULL == node->next) {
mag_ptr->lastNode = node->prev;
} else {
node->next->prev = node->prev;
}
mag_ptr->recirculation_entries--;
}
static MALLOC_INLINE void
recirc_list_splice_last(rack_t *rack, magazine_t *mag_ptr, region_trailer_t *node)
{
if (NULL == mag_ptr->lastNode) {
mag_ptr->firstNode = node;
node->prev = NULL;
} else {
node->prev = mag_ptr->lastNode;
mag_ptr->lastNode->next = node;
}
mag_ptr->lastNode = node;
node->next = NULL;
node->recirc_suitable = FALSE;
mag_ptr->recirculation_entries++;
}
static MALLOC_INLINE void
recirc_list_splice_first(rack_t *rack, magazine_t *mag_ptr, region_trailer_t *node)
{
if (NULL == mag_ptr->firstNode) {
mag_ptr->lastNode = node;
node->next = NULL;
} else {
node->next = mag_ptr->firstNode;
mag_ptr->firstNode->prev = node;
}
mag_ptr->firstNode = node;
node->prev = NULL;
node->recirc_suitable = FALSE;
mag_ptr->recirculation_entries++;
}
/*******************************************************************************
* Region hash implementation
*
* This is essentially a duplicate of the existing Large allocator hash, minus
* the ability to remove entries. The two should be combined eventually.
******************************************************************************/
#pragma mark region hash
/*
* hash_lookup_region_no_lock - Scan a hash ring looking for an entry for a
* given region.
*
* FIXME: If consecutive queries of the same region are likely, a one-entry
* cache would likely be a significant performance win here.
*/
static MALLOC_INLINE rgnhdl_t
hash_lookup_region_no_lock(region_t *regions, size_t num_entries, size_t shift, region_t r)
{
size_t index, hash_index;
rgnhdl_t entry;
if (!num_entries) {
return 0;
}
// Multiplicative hash where the multiplier is a prime near (ULONG_MAX / phi). [phi = 1.618033...]
// Since the values of (((uintptr_t)r >> HASH_BLOCKS_ALIGN) are (roughly) an ascending sequence of integers,
// this hash works really well. See Knuth TAOCP, Vol. 3.
#if __LP64__
index = hash_index = (((uintptr_t)r >> HASH_BLOCKS_ALIGN) * 11400714819323198549ULL) >> (64 - shift);
#else
index = hash_index = (((uintptr_t)r >> HASH_BLOCKS_ALIGN) * 2654435761UL) >> (32 - shift);
#endif
do {
entry = regions + index;
if (*entry == 0) {
return 0;
}
if (*entry == r) {
return entry;
}
if (++index == num_entries) {
index = 0;
}
} while (index != hash_index);
return 0;
}
/*
* hash_region_insert_no_lock - Insert a region into the hash ring.
*/
static void
hash_region_insert_no_lock(region_t *regions, size_t num_entries, size_t shift, region_t r)
{
size_t index, hash_index;
rgnhdl_t entry;
// Multiplicative hash where the multiplier is a prime near (ULONG_MAX / phi). [phi = 1.618033...]
// Since the values of (((uintptr_t)r >> HASH_BLOCKS_ALIGN) are (roughly) an ascending sequence of integers,
// this hash works really well. See Knuth TAOCP, Vol. 3.
#if __LP64__
index = hash_index = (((uintptr_t)r >> HASH_BLOCKS_ALIGN) * 11400714819323198549ULL) >> (64 - shift);
#else
index = hash_index = (((uintptr_t)r >> HASH_BLOCKS_ALIGN) * 2654435761UL) >> (32 - shift);
#endif
do {
entry = regions + index;
if (*entry == HASHRING_OPEN_ENTRY || *entry == HASHRING_REGION_DEALLOCATED) {
*entry = r;
return;
}
if (++index == num_entries) {
index = 0;
}
} while (index != hash_index);
}
/*
* hash_regions_alloc_no_lock - Allocate space for a number of entries. This
* must be a VM allocation as to avoid recursing between allocating a new small
* region, and asking the small region to allocate space for the new list of
* regions.
*/
static region_t *
hash_regions_alloc_no_lock(size_t num_entries)
{
size_t size = num_entries * sizeof(region_t);
return mvm_allocate_pages(round_page_quanta(size), 0, 0, VM_MEMORY_MALLOC);
}
/*
* hash_regions_grow_no_lock - Grow the hash ring, and rehash the entries.
* Return the new region and new size to update the szone. Do not deallocate
* the old entries since someone may still be allocating them.
*/
static MALLOC_INLINE region_t *
hash_regions_grow_no_lock(region_t *regions, size_t old_size, size_t *mutable_shift, size_t *new_size)
{
// double in size and allocate memory for the regions
*new_size = old_size + old_size;
*mutable_shift = *mutable_shift + 1;
region_t *new_regions = hash_regions_alloc_no_lock(*new_size);
// rehash the entries into the new list
size_t index;
for (index = 0; index < old_size; ++index) {
region_t r = regions[index];
if (r != HASHRING_OPEN_ENTRY && r != HASHRING_REGION_DEALLOCATED) {
hash_region_insert_no_lock(new_regions, *new_size, *mutable_shift, r);
}
}
return new_regions;
}
#pragma mark mag index
/*
* These commpage routines provide fast access to the logical cpu number
* of the calling processor assuming no pre-emption occurs.
*/
extern unsigned int hyper_shift;
extern unsigned int phys_ncpus;
extern unsigned int logical_ncpus;
static MALLOC_INLINE MALLOC_ALWAYS_INLINE
unsigned int
mag_max_magazines(void)
{
return max_magazines;
}
#pragma mark mag lock
static MALLOC_INLINE magazine_t *
mag_lock_zine_for_region_trailer(magazine_t *magazines, region_trailer_t *trailer, mag_index_t mag_index)
{
mag_index_t refreshed_index;
magazine_t *mag_ptr = &(magazines[mag_index]);
// Take the lock on entry.
SZONE_MAGAZINE_PTR_LOCK(mag_ptr);
// Now in the time it took to acquire the lock, the region may have migrated
// from one magazine to another. In which case the magazine lock we obtained
// (namely magazines[mag_index].mag_lock) is stale. If so, keep on tryin' ...
while (mag_index != (refreshed_index = trailer->mag_index)) { // Note assignment
SZONE_MAGAZINE_PTR_UNLOCK(mag_ptr);
mag_index = refreshed_index;
mag_ptr = &(magazines[mag_index]);
SZONE_MAGAZINE_PTR_LOCK(mag_ptr);
}
return mag_ptr;
}
#pragma mark tiny allocator
/*
* tiny_region_for_ptr_no_lock - Returns the tiny region containing the pointer,
* or NULL if not found.
*/
static MALLOC_INLINE region_t
tiny_region_for_ptr_no_lock(rack_t *rack, const void *ptr)
{
rgnhdl_t r = hash_lookup_region_no_lock(rack->region_generation->hashed_regions,
rack->region_generation->num_regions_allocated,
rack->region_generation->num_regions_allocated_shift,
TINY_REGION_FOR_PTR(ptr));
return r ? *r : r;
}
/*
* Obtain the size of a free tiny block (in msize_t units).
*/
static msize_t
get_tiny_free_size(const void *ptr)
{
void *next_block = (void *)((uintptr_t)ptr + TINY_QUANTUM);
void *region_end = TINY_REGION_END(TINY_REGION_FOR_PTR(ptr));
// check whether the next block is outside the tiny region or a block header
// if so, then the size of this block is one, and there is no stored size.
if (next_block < region_end) {
uint32_t *next_header = TINY_BLOCK_HEADER_FOR_PTR(next_block);
msize_t next_index = TINY_INDEX_FOR_PTR(next_block);
if (!BITARRAY_BIT(next_header, next_index)) {
return TINY_FREE_SIZE(ptr);
}
}
return 1;
}
static MALLOC_INLINE msize_t
get_tiny_meta_header(const void *ptr, boolean_t *is_free)
{
// returns msize and is_free
// may return 0 for the msize component (meaning 65536)
uint32_t *block_header;
msize_t index;
block_header = TINY_BLOCK_HEADER_FOR_PTR(ptr);
index = TINY_INDEX_FOR_PTR(ptr);
msize_t midx = (index >> 5) << 1;
uint32_t mask = 1 << (index & 31);
*is_free = 0;
if (0 == (block_header[midx] & mask)) { // if (!BITARRAY_BIT(block_header, index))
return 0;
}
if (0 == (block_header[midx + 1] & mask)) { // if (!BITARRAY_BIT(in_use, index))
*is_free = 1;
return get_tiny_free_size(ptr);
}
// index >> 5 identifies the uint32_t to manipulate in the conceptually contiguous bits array
// (index >> 5) << 1 identifies the uint32_t allowing for the actual interleaving
#if defined(__LP64__)
// The return value, msize, is computed as the distance to the next 1 bit in block_header.
// That's guaranteed to be somewhere in the next 64 bits. And those bits could span three
// uint32_t block_header elements. Collect the bits into a single uint64_t and measure up with ffsl.
uint32_t *addr = ((uint32_t *)block_header) + ((index >> 5) << 1);
uint32_t bitidx = index & 31;
uint64_t word_lo = addr[0];
uint64_t word_mid = addr[2];
uint64_t word_hi = addr[4];
uint64_t word_lomid = (word_lo >> bitidx) | (word_mid << (32 - bitidx));
uint64_t word = bitidx ? word_lomid | (word_hi << (64 - bitidx)) : word_lomid;
uint32_t result = __builtin_ffsl(word >> 1);
#else
// The return value, msize, is computed as the distance to the next 1 bit in block_header.
// That's guaranteed to be somewhere in the next 32 bits. And those bits could span two
// uint32_t block_header elements. Collect the bits into a single uint32_t and measure up with ffs.
uint32_t *addr = ((uint32_t *)block_header) + ((index >> 5) << 1);
uint32_t bitidx = index & 31;
uint32_t word = bitidx ? (addr[0] >> bitidx) | (addr[2] << (32 - bitidx)) : addr[0];
uint32_t result = __builtin_ffs(word >> 1);
#endif
return result;
}
#pragma mark small allocator
/*
* small_region_for_ptr_no_lock - Returns the small region containing the pointer,
* or NULL if not found.
*/
static MALLOC_INLINE region_t
small_region_for_ptr_no_lock(rack_t *rack, const void *ptr)
{
rgnhdl_t r = hash_lookup_region_no_lock(rack->region_generation->hashed_regions,
rack->region_generation->num_regions_allocated, rack->region_generation->num_regions_allocated_shift,
SMALL_REGION_FOR_PTR(ptr));
return r ? *r : r;
}
#endif // __MAGAZINE_INLINE_H
================================================
FILE: InterView-obj-isa-class/libmalloc-166.220.1/src/magazine_large.c
================================================
/*
* Copyright (c) 2015 Apple Inc. All rights reserved.
*
* @APPLE_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apple Public Source License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. Please obtain a copy of the License at
* http://www.opensource.apple.com/apsl/ and read it before using this
* file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPLE_LICENSE_HEADER_END@
*/
#include "internal.h"
#if DEBUG_MALLOC
static void
large_debug_print(szone_t *szone)
{
unsigned index;
large_entry_t *range;
_SIMPLE_STRING b = _simple_salloc();
if (b) {
for (index = 0, range = szone->large_entries; index < szone->num_large_entries; index++, range++) {
if (range->address) {
_simple_sprintf(b, "%d: %p(%y); ", index, range->address, range->size);
}
}
malloc_report(MALLOC_REPORT_NOLOG | MALLOC_REPORT_NOPREFIX, "%s\n", _simple_string(b));
_simple_sfree(b);
}
}
#endif
/*
* Scan the hash ring looking for an entry containing a given pointer.
*/
static large_entry_t *
large_entry_containing_pointer_no_lock(szone_t *szone, const void *ptr)
{
// result only valid with lock held
unsigned num_large_entries = szone->num_large_entries;
unsigned hash_index;
unsigned index;
large_entry_t *range;
if (!num_large_entries) {
return NULL;
}
hash_index = ((uintptr_t)ptr >> vm_page_quanta_shift) % num_large_entries;
index = hash_index;
do {
range = szone->large_entries + index;
if (range->address == (vm_address_t)ptr) {
return range;
} else if ((vm_address_t)ptr >= range->address
&& (vm_address_t)ptr < range->address + range->size) {
return range;
}
// Since we may be looking for an inner pointer, we might not get an
// exact match on the address, so we need to scan further and to skip
// over empty entries. It will usually be faster to scan backwards.
index = index == 0 ? num_large_entries - 1 : index - 1;
} while (index != hash_index);
return NULL;
}
/*
* Scan the hash ring looking for an entry for the given pointer.
*/
large_entry_t *
large_entry_for_pointer_no_lock(szone_t *szone, const void *ptr)
{
// result only valid with lock held
unsigned num_large_entries = szone->num_large_entries;
unsigned hash_index;
unsigned index;
large_entry_t *range;
if (!num_large_entries) {
return NULL;
}
hash_index = ((uintptr_t)ptr >> vm_page_quanta_shift) % num_large_entries;
index = hash_index;
do {
range = szone->large_entries + index;
if (range->address == (vm_address_t)ptr) {
return range;
}
if (0 == range->address) {
return NULL; // end of chain
}
index++;
if (index == num_large_entries) {
index = 0;
}
} while (index != hash_index);
return NULL;
}
static void
large_entry_insert_no_lock(szone_t *szone, large_entry_t range)
{
unsigned num_large_entries = szone->num_large_entries;
unsigned hash_index = (((uintptr_t)(range.address)) >> vm_page_quanta_shift) % num_large_entries;
unsigned index = hash_index;
large_entry_t *entry;
// assert(szone->num_large_objects_in_use < szone->num_large_entries); /* must be called with room to spare */
do {
entry = szone->large_entries + index;
if (0 == entry->address) {
*entry = range;
return; // end of chain
}
index++;
if (index == num_large_entries) {
index = 0;
}
} while (index != hash_index);
// assert(0); /* must not fallthrough! */
}
// FIXME: can't we simply swap the (now empty) entry with the last entry on the collision chain for this hash slot?
static MALLOC_INLINE void
large_entries_rehash_after_entry_no_lock(szone_t *szone, large_entry_t *entry)
{
unsigned num_large_entries = szone->num_large_entries;
uintptr_t hash_index = entry - szone->large_entries;
uintptr_t index = hash_index;
large_entry_t range;
// assert(entry->address == 0) /* caller must have cleared *entry */
do {
index++;
if (index == num_large_entries) {
index = 0;
}
range = szone->large_entries[index];
if (0 == range.address) {
return;
}
szone->large_entries[index].address = (vm_address_t)0;
szone->large_entries[index].size = 0;
szone->large_entries[index].did_madvise_reusable = FALSE;
large_entry_insert_no_lock(szone, range); // this will reinsert in the
// proper place
} while (index != hash_index);
// assert(0); /* since entry->address == 0, must not fallthrough! */
}
// FIXME: num should probably be a size_t, since you can theoretically allocate
// more than 2^32-1 large_threshold objects in 64 bit.
static MALLOC_INLINE large_entry_t *
large_entries_alloc_no_lock(unsigned num)
{
size_t size = num * sizeof(large_entry_t);
// Note that we allocate memory (via a system call) under a spin lock
// That is certainly evil, however it's very rare in the lifetime of a process
// The alternative would slow down the normal case
return mvm_allocate_pages(round_page_quanta(size), 0, 0, VM_MEMORY_MALLOC_LARGE);
}
void
large_entries_free_no_lock(szone_t *szone, large_entry_t *entries, unsigned num, vm_range_t *range_to_deallocate)
{
size_t size = num * sizeof(large_entry_t);
range_to_deallocate->address = (vm_address_t)entries;
range_to_deallocate->size = round_page_quanta(size);
}
static large_entry_t *
large_entries_grow_no_lock(szone_t *szone, vm_range_t *range_to_deallocate)
{
// sets range_to_deallocate
unsigned old_num_entries = szone->num_large_entries;
large_entry_t *old_entries = szone->large_entries;
// always an odd number for good hashing
unsigned new_num_entries =
(old_num_entries) ? old_num_entries * 2 + 1 : (unsigned)((vm_page_quanta_size / sizeof(large_entry_t)) - 1);
large_entry_t *new_entries = large_entries_alloc_no_lock(new_num_entries);
unsigned index = old_num_entries;
large_entry_t oldRange;
// if the allocation of new entries failed, bail
if (new_entries == NULL) {
return NULL;
}
szone->num_large_entries = new_num_entries;
szone->large_entries = new_entries;
/* rehash entries into the new list */
while (index--) {
oldRange = old_entries[index];
if (oldRange.address) {
large_entry_insert_no_lock(szone, oldRange);
}
}
if (old_entries) {
large_entries_free_no_lock(szone, old_entries, old_num_entries, range_to_deallocate);
} else {
range_to_deallocate->address = (vm_address_t)0;
range_to_deallocate->size = 0;
}
return new_entries;
}
// frees the specific entry in the size table
// returns a range to truly deallocate
static vm_range_t
large_entry_free_no_lock(szone_t *szone, large_entry_t *entry)
{
vm_range_t range;
MALLOC_TRACE(TRACE_large_free, (uintptr_t)szone, (uintptr_t)entry->address, entry->size, 0);
range.address = entry->address;
range.size = entry->size;
if (szone->debug_flags & MALLOC_ADD_GUARD_PAGES) {
mvm_protect((void *)range.address, range.size, PROT_READ | PROT_WRITE, szone->debug_flags);
range.address -= vm_page_quanta_size;
range.size += 2 * vm_page_quanta_size;
}
entry->address = 0;
entry->size = 0;
entry->did_madvise_reusable = FALSE;
large_entries_rehash_after_entry_no_lock(szone, entry);
#if DEBUG_MALLOC
if (large_entry_for_pointer_no_lock(szone, (void *)range.address)) {
malloc_report(ASL_LEVEL_ERR, "*** freed entry %p still in use; num_large_entries=%d\n", range.address, szone->num_large_entries);
large_debug_print(szone);
szone_sleep();
}
#endif
return range;
}
kern_return_t
large_in_use_enumerator(task_t task,
void *context,
unsigned type_mask,
vm_address_t large_entries_address,
unsigned num_entries,
memory_reader_t reader,
vm_range_recorder_t recorder)
{
unsigned index = 0;
vm_range_t buffer[MAX_RECORDER_BUFFER];
unsigned count = 0;
large_entry_t *entries;
kern_return_t err;
vm_range_t range;
large_entry_t entry;
err = reader(task, large_entries_address, sizeof(large_entry_t) * num_entries, (void **)&entries);
if (err) {
return err;
}
index = num_entries;
if (type_mask & MALLOC_ADMIN_REGION_RANGE_TYPE) {
range.address = large_entries_address;
range.size = round_page_quanta(num_entries * sizeof(large_entry_t));
recorder(task, context, MALLOC_ADMIN_REGION_RANGE_TYPE, &range, 1);
}
if (type_mask & (MALLOC_PTR_IN_USE_RANGE_TYPE | MALLOC_PTR_REGION_RANGE_TYPE)) {
while (index--) {
entry = entries[index];
if (entry.address) {
range.address = entry.address;
range.size = entry.size;
buffer[count++] = range;
if (count >= MAX_RECORDER_BUFFER) {
recorder(task, context, MALLOC_PTR_IN_USE_RANGE_TYPE | MALLOC_PTR_REGION_RANGE_TYPE, buffer, count);
count = 0;
}
}
}
}
if (count) {
recorder(task, context, MALLOC_PTR_IN_USE_RANGE_TYPE | MALLOC_PTR_REGION_RANGE_TYPE, buffer, count);
}
return 0;
}
void *
large_malloc(szone_t *szone, size_t num_kernel_pages, unsigned char alignment, boolean_t cleared_requested)
{
void *addr;
vm_range_t range_to_deallocate;
size_t size;
large_entry_t large_entry;
MALLOC_TRACE(TRACE_large_malloc, (uintptr_t)szone, num_kernel_pages, alignment, cleared_requested);
if (!num_kernel_pages) {
num_kernel_pages = 1; // minimal allocation size for this szone
}
size = (size_t)num_kernel_pages << vm_page_quanta_shift;
range_to_deallocate.size = 0;
range_to_deallocate.address = 0;
#if CONFIG_LARGE_CACHE
if (size < LARGE_CACHE_SIZE_ENTRY_LIMIT) { // Look for a large_entry_t on the death-row cache?
SZONE_LOCK(szone);
int i, best = -1, idx = szone->large_entry_cache_newest, stop_idx = szone->large_entry_cache_oldest;
size_t best_size = SIZE_T_MAX;
while (1) { // Scan large_entry_cache for best fit, starting with most recent entry
size_t this_size = szone->large_entry_cache[idx].size;
addr = (void *)szone->large_entry_cache[idx].address;
if (0 == alignment || 0 == (((uintptr_t)addr) & (((uintptr_t)1 << alignment) - 1))) {
if (size == this_size) { // size match!
best = idx;
best_size = this_size;
break;
}
if (size <= this_size && this_size < best_size) { // improved fit?
best = idx;
best_size = this_size;
}
}
if (idx == stop_idx) { // exhausted live ring?
break;
}
if (idx) {
idx--; // bump idx down
} else {
idx = LARGE_ENTRY_CACHE_SIZE - 1; // wrap idx
}
}
if (best > -1 && (best_size - size) < size) { // limit fragmentation to 50%
addr = (void *)szone->large_entry_cache[best].address;
boolean_t was_madvised_reusable = szone->large_entry_cache[best].did_madvise_reusable;
// Compact live ring to fill entry now vacated at large_entry_cache[best]
// while preserving time-order
if (szone->large_entry_cache_oldest < szone->large_entry_cache_newest) {
// Ring hasn't wrapped. Fill in from right.
for (i = best; i < szone->large_entry_cache_newest; ++i) {
szone->large_entry_cache[i] = szone->large_entry_cache[i + 1];
}
szone->large_entry_cache_newest--; // Pull in right endpoint.
} else if (szone->large_entry_cache_newest < szone->large_entry_cache_oldest) {
// Ring has wrapped. Arrange to fill in from the contiguous side.
if (best <= szone->large_entry_cache_newest) {
// Fill from right.
for (i = best; i < szone->large_entry_cache_newest; ++i) {
szone->large_entry_cache[i] = szone->large_entry_cache[i + 1];
}
if (0 < szone->large_entry_cache_newest) {
szone->large_entry_cache_newest--;
} else {
szone->large_entry_cache_newest = LARGE_ENTRY_CACHE_SIZE - 1;
}
} else {
// Fill from left.
for (i = best; i > szone->large_entry_cache_oldest; --i) {
szone->large_entry_cache[i] = szone->large_entry_cache[i - 1];
}
if (szone->large_entry_cache_oldest < LARGE_ENTRY_CACHE_SIZE - 1) {
szone->large_entry_cache_oldest++;
} else {
szone->large_entry_cache_oldest = 0;
}
}
} else {
// By trichotomy, large_entry_cache_newest == large_entry_cache_oldest.
// That implies best == large_entry_cache_newest == large_entry_cache_oldest
// and the ring is now empty.
szone->large_entry_cache[best].address = 0;
szone->large_entry_cache[best].size = 0;
szone->large_entry_cache[best].did_madvise_reusable = FALSE;
}
if ((szone->num_large_objects_in_use + 1) * 4 > szone->num_large_entries) {
// density of hash table too high; grow table
// we do that under lock to avoid a race
large_entry_t *entries = large_entries_grow_no_lock(szone, &range_to_deallocate);
if (entries == NULL) {
SZONE_UNLOCK(szone);
return NULL;
}
}
large_entry.address = (vm_address_t)addr;
large_entry.size = best_size;
large_entry.did_madvise_reusable = FALSE;
large_entry_insert_no_lock(szone, large_entry);
szone->num_large_objects_in_use++;
szone->num_bytes_in_large_objects += best_size;
if (!was_madvised_reusable) {
szone->large_entry_cache_reserve_bytes -= best_size;
}
szone->large_entry_cache_bytes -= best_size;
if (szone->flotsam_enabled && szone->large_entry_cache_bytes < SZONE_FLOTSAM_THRESHOLD_LOW) {
szone->flotsam_enabled = FALSE;
}
SZONE_UNLOCK(szone);
if (range_to_deallocate.size) {
// we deallocate outside the lock
mvm_deallocate_pages((void *)range_to_deallocate.address, range_to_deallocate.size, 0);
}
if (cleared_requested) {
memset(addr, 0, size);
}
return addr;
} else {
SZONE_UNLOCK(szone);
}
}
range_to_deallocate.size = 0;
range_to_deallocate.address = 0;
#endif /* CONFIG_LARGE_CACHE */
addr = mvm_allocate_pages(size, alignment, szone->debug_flags, VM_MEMORY_MALLOC_LARGE);
if (addr == NULL) {
return NULL;
}
SZONE_LOCK(szone);
if ((szone->num_large_objects_in_use + 1) * 4 > szone->num_large_entries) {
// density of hash table too high; grow table
// we do that under lock to avoid a race
large_entry_t *entries = large_entries_grow_no_lock(szone, &range_to_deallocate);
if (entries == NULL) {
SZONE_UNLOCK(szone);
return NULL;
}
}
large_entry.address = (vm_address_t)addr;
large_entry.size = size;
large_entry.did_madvise_reusable = FALSE;
large_entry_insert_no_lock(szone, large_entry);
szone->num_large_objects_in_use++;
szone->num_bytes_in_large_objects += size;
SZONE_UNLOCK(szone);
if (range_to_deallocate.size) {
// we deallocate outside the lock
mvm_deallocate_pages((void *)range_to_deallocate.address, range_to_deallocate.size, 0);
}
return addr;
}
void
free_large(szone_t *szone, void *ptr)
{
// We have established ptr is page-aligned and neither tiny nor small
large_entry_t *entry;
vm_range_t vm_range_to_deallocate;
SZONE_LOCK(szone);
entry = large_entry_for_pointer_no_lock(szone, ptr);
if (entry) {
#if CONFIG_LARGE_CACHE
if (entry->size < LARGE_CACHE_SIZE_ENTRY_LIMIT &&
-1 != madvise((void *)(entry->address), entry->size,
MADV_CAN_REUSE)) { // Put the large_entry_t on the death-row cache?
int idx = szone->large_entry_cache_newest, stop_idx = szone->large_entry_cache_oldest;
large_entry_t this_entry = *entry; // Make a local copy, "entry" is volatile when lock is let go.
boolean_t reusable = TRUE;
boolean_t should_madvise =
szone->large_entry_cache_reserve_bytes + this_entry.size > szone->large_entry_cache_reserve_limit;
// Already freed?
// [Note that repeated entries in death-row risk vending the same entry subsequently
// to two different malloc() calls. By checking here the (illegal) double free
// is accommodated, matching the behavior of the previous implementation.]
while (1) { // Scan large_entry_cache starting with most recent entry
if (szone->large_entry_cache[idx].address == entry->address) {
malloc_zone_error(szone->debug_flags, true, "pointer %p being freed already on death-row\n", ptr);
SZONE_UNLOCK(szone);
return;
}
if (idx == stop_idx) { // exhausted live ring?
break;
}
if (idx) {
idx--; // bump idx down
} else {
idx = LARGE_ENTRY_CACHE_SIZE - 1; // wrap idx
}
}
SZONE_UNLOCK(szone);
if (szone->debug_flags & MALLOC_PURGEABLE) { // Are we a purgable zone?
int state = VM_PURGABLE_NONVOLATILE; // restore to default condition
if (KERN_SUCCESS != vm_purgable_control(mach_task_self(), this_entry.address, VM_PURGABLE_SET_STATE, &state)) {
malloc_report(ASL_LEVEL_ERR, "*** can't vm_purgable_control(..., VM_PURGABLE_SET_STATE) for large freed block at %p\n",
(void *)this_entry.address);
reusable = FALSE;
}
}
if (szone->large_legacy_reset_mprotect) { // Linked for Leopard?
// Accomodate Leopard apps that (illegally) mprotect() their own guard pages on large malloc'd allocations
int err = mprotect((void *)(this_entry.address), this_entry.size, PROT_READ | PROT_WRITE);
if (err) {
malloc_report(ASL_LEVEL_ERR, "*** can't reset protection for large freed block at %p\n", (void *)this_entry.address);
reusable = FALSE;
}
}
// madvise(..., MADV_REUSABLE) death-row arrivals if hoarding would exceed large_entry_cache_reserve_limit
if (should_madvise) {
// Issue madvise to avoid paging out the dirtied free()'d pages in "entry"
MAGMALLOC_MADVFREEREGION((void *)szone, (void *)0, (void *)(this_entry.address), (int)this_entry.size); // DTrace USDT Probe
// Ok to do this madvise on embedded because we won't call MADV_FREE_REUSABLE on a large
// cache block twice without MADV_FREE_REUSE in between.
if (-1 == madvise((void *)(this_entry.address), this_entry.size, MADV_FREE_REUSABLE)) {
/* -1 return: VM map entry change makes this unfit for reuse. */
#if DEBUG_MADVISE
malloc_zone_error(szone->debug_flags, false,
"free_large madvise(..., MADV_FREE_REUSABLE) failed for %p, length=%d\n",
(void *)this_entry.address, this_entry.size);
#endif
reusable = FALSE;
}
}
SZONE_LOCK(szone);
// Re-acquire "entry" after interval just above where we let go the lock.
entry = large_entry_for_pointer_no_lock(szone, ptr);
if (NULL == entry) {
malloc_zone_error(szone->debug_flags, true, "entry for pointer %p being freed from death-row vanished\n", ptr);
SZONE_UNLOCK(szone);
return;
}
// Add "entry" to death-row ring
if (reusable) {
int idx = szone->large_entry_cache_newest; // Most recently occupied
vm_address_t addr;
size_t adjsize;
if (szone->large_entry_cache_newest == szone->large_entry_cache_oldest &&
0 == szone->large_entry_cache[idx].address) {
// Ring is empty, idx is good as it stands
addr = 0;
adjsize = 0;
} else {
// Extend the queue to the "right" by bumping up large_entry_cache_newest
if (idx == LARGE_ENTRY_CACHE_SIZE - 1) {
idx = 0; // Wrap index
} else {
idx++; // Bump index
}
if (idx == szone->large_entry_cache_oldest) { // Fully occupied
// Drop this entry from the cache and deallocate the VM
addr = szone->large_entry_cache[idx].address;
adjsize = szone->large_entry_cache[idx].size;
szone->large_entry_cache_bytes -= adjsize;
if (!szone->large_entry_cache[idx].did_madvise_reusable) {
szone->large_entry_cache_reserve_bytes -= adjsize;
}
} else {
// Using an unoccupied cache slot
addr = 0;
adjsize = 0;
}
}
if ((szone->debug_flags & MALLOC_DO_SCRIBBLE)) {
memset((void *)(entry->address), should_madvise ? SCRUBBLE_BYTE : SCRABBLE_BYTE, entry->size);
}
entry->did_madvise_reusable = should_madvise; // Was madvise()'d above?
if (!should_madvise) { // Entered on death-row without madvise() => up the hoard total
szone->large_entry_cache_reserve_bytes += entry->size;
}
szone->large_entry_cache_bytes += entry->size;
if (!szone->flotsam_enabled && szone->large_entry_cache_bytes > SZONE_FLOTSAM_THRESHOLD_HIGH) {
szone->flotsam_enabled = TRUE;
}
szone->large_entry_cache[idx] = *entry;
szone->large_entry_cache_newest = idx;
szone->num_large_objects_in_use--;
szone->num_bytes_in_large_objects -= entry->size;
(void)large_entry_free_no_lock(szone, entry);
if (0 == addr) {
SZONE_UNLOCK(szone);
return;
}
// Fall through to drop large_entry_cache_oldest from the cache,
// and then deallocate its pages.
// Trim the queue on the "left" by bumping up large_entry_cache_oldest
if (szone->large_entry_cache_oldest == LARGE_ENTRY_CACHE_SIZE - 1) {
szone->large_entry_cache_oldest = 0;
} else {
szone->large_entry_cache_oldest++;
}
// we deallocate_pages, including guard pages, outside the lock
SZONE_UNLOCK(szone);
mvm_deallocate_pages((void *)addr, (size_t)adjsize, 0);
return;
} else {
/* fall through to discard an allocation that is not reusable */
}
}
#endif /* CONFIG_LARGE_CACHE */
szone->num_large_objects_in_use--;
szone->num_bytes_in_large_objects -= entry->size;
vm_range_to_deallocate = large_entry_free_no_lock(szone, entry);
} else {
#if DEBUG_MALLOC
large_debug_print(szone);
#endif
malloc_zone_error(szone->debug_flags, true, "pointer %p being freed was not allocated\n", ptr);
SZONE_UNLOCK(szone);
return;
}
SZONE_UNLOCK(szone); // we release the lock asap
CHECK(szone, __PRETTY_FUNCTION__);
// we deallocate_pages, including guard pages, outside the lock
if (vm_range_to_deallocate.address) {
#if DEBUG_MALLOC
// FIXME: large_entry_for_pointer_no_lock() needs the lock held ...
if (large_entry_for_pointer_no_lock(szone, (void *)vm_range_to_deallocate.address)) {
malloc_report(ASL_LEVEL_ERR, "*** invariant broken: %p still in use num_large_entries=%d\n",
vm_range_to_deallocate.address, szone->num_large_entries);
large_debug_print(szone);
szone_sleep();
}
#endif
mvm_deallocate_pages((void *)vm_range_to_deallocate.address, (size_t)vm_range_to_deallocate.size, 0);
}
}
void *
large_try_shrink_in_place(szone_t *szone, void *ptr, size_t old_size, size_t new_good_size)
{
size_t shrinkage = old_size - new_good_size;
if (shrinkage) {
SZONE_LOCK(szone);
/* contract existing large entry */
large_entry_t *large_entry = large_entry_for_pointer_no_lock(szone, ptr);
if (!large_entry) {
malloc_zone_error(szone->debug_flags, true, "large entry %p reallocated is not properly in table\n", ptr);
SZONE_UNLOCK(szone);
return ptr;
}
large_entry->address = (vm_address_t)ptr;
large_entry->size = new_good_size;
szone->num_bytes_in_large_objects -= shrinkage;
boolean_t guarded = szone->debug_flags & MALLOC_ADD_GUARD_PAGES;
SZONE_UNLOCK(szone); // we release the lock asap
if (guarded) {
// Keep the page above the new end of the allocation as the
// postlude guard page.
kern_return_t err;
err = mprotect((void *)((uintptr_t)ptr + new_good_size), vm_page_quanta_size, 0);
if (err) {
malloc_report(ASL_LEVEL_ERR, "*** can't mvm_protect(0x0) region for new postlude guard page at %p\n",
ptr + new_good_size);
}
new_good_size += vm_page_quanta_size;
shrinkage -= vm_page_quanta_size;
}
mvm_deallocate_pages((void *)((uintptr_t)ptr + new_good_size), shrinkage, 0);
}
return ptr;
}
int
large_try_realloc_in_place(szone_t *szone, void *ptr, size_t old_size, size_t new_size)
{
vm_address_t addr = (vm_address_t)ptr + old_size;
large_entry_t *large_entry;
kern_return_t err;
SZONE_LOCK(szone);
large_entry = large_entry_for_pointer_no_lock(szone, (void *)addr);
SZONE_UNLOCK(szone);
if (large_entry) { // check if "addr = ptr + old_size" is already spoken for
return 0; // large pointer already exists in table - extension is not going to work
}
new_size = round_page_quanta(new_size);
/*
* Ask for allocation at a specific address, and mark as realloc
* to request coalescing with previous realloc'ed extensions.
*/
err = vm_allocate(mach_task_self(), &addr, new_size - old_size, VM_MAKE_TAG(VM_MEMORY_REALLOC));
if (err != KERN_SUCCESS) {
return 0;
}
SZONE_LOCK(szone);
/* extend existing large entry */
large_entry = large_entry_for_pointer_no_lock(szone, ptr);
if (!large_entry) {
malloc_zone_error(szone->debug_flags, true, "large entry %p reallocated is not properly in table\n", ptr);
SZONE_UNLOCK(szone);
return 0; // Bail, leaking "addr"
}
large_entry->address = (vm_address_t)ptr;
large_entry->size = new_size;
szone->num_bytes_in_large_objects += new_size - old_size;
SZONE_UNLOCK(szone); // we release the lock asap
return 1;
}
boolean_t
large_claimed_address(szone_t *szone, void *ptr)
{
SZONE_LOCK(szone);
boolean_t result = large_entry_containing_pointer_no_lock(szone,
(void *)trunc_page((uintptr_t)ptr)) != NULL;
SZONE_UNLOCK(szone);
return result;
}
================================================
FILE: InterView-obj-isa-class/libmalloc-166.220.1/src/magazine_lite.c
================================================
/*
* Copyright (c) 2016, Apple Inc. All rights reserved.
*
* @APPLE_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apple Public Source License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. Please obtain a copy of the License at
* http://www.opensource.apple.com/apsl/ and read it before using this
* file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPLE_LICENSE_HEADER_END@
*/
#include "internal.h"
typedef uint64_t malloc_stack_id;
uint64_t max_lite_mallocs = 0;
static malloc_stack_id
get_stack_id_from_ptr(void *ptr, size_t ptr_size)
{
void *idptr = ptr + ptr_size - sizeof(malloc_stack_id);
return * (malloc_stack_id *) idptr;
}
static void
set_stack_id_in_ptr(void *ptr, size_t requested_size, size_t ptr_size, malloc_stack_id stack_id)
{
void *idptr = ptr + ptr_size - sizeof(malloc_stack_id);
* (malloc_stack_id *) idptr = stack_id;
void *padding = ptr + requested_size;
bzero(padding, ptr_size - requested_size - sizeof(malloc_stack_id));
}
static void
add_stack_to_ptr(szone_t *szone, size_t requested_size, void *ptr)
{
// enter the stack into the unique table
vm_address_t self_thread = (vm_address_t)_os_tsd_get_direct(__TSD_THREAD_SELF);
size_t ptr_size = szone_size(szone, ptr);
__malloc_lock_stack_logging();
// if stack logging was turned off behind our backs
if (!is_stack_logging_lite_enabled()) {
__malloc_unlock_stack_logging();
return;
}
malloc_stack_id stack_id = __enter_stack_into_table_while_locked(self_thread, 0, false, ptr_size);
__malloc_unlock_stack_logging();
if (stack_id == __invalid_stack_id) {
malloc_report(ASL_LEVEL_ERR, "bad stack id. turning off stack logging\n");
turn_off_stack_logging();
} else {
set_stack_id_in_ptr(ptr, requested_size, ptr_size, stack_id);
}
}
static boolean_t stack_logging_lite_enabled = false;
boolean_t is_stack_logging_lite_enabled(void) {
return stack_logging_lite_enabled;
}
void
enable_stack_logging_lite()
{
stack_logging_lite_enabled = true;
}
void
disable_stack_logging_lite()
{
stack_logging_lite_enabled = false;
}
static void *
stack_logging_lite_malloc(malloc_zone_t *zone, size_t size)
{
szone_t *szone = (szone_t *) zone;
void* p = NULL;
static uint64_t num_mallocs = 0;
if (stack_logging_lite_enabled) {
__prepare_to_log_stacks(true); // do this again in case stack logging was postponed
p = szone_malloc(szone, size + sizeof(malloc_stack_id));
if (p) {
add_stack_to_ptr(szone, size, p);
}
// this value doesn't need to be exact, so no need for atomic operations
num_mallocs++;
if (max_lite_mallocs > 0 && num_mallocs > max_lite_mallocs) {
malloc_report(ASL_LEVEL_ERR, "lite allocations exceeded limit. disabling lite mode\n");
disable_stack_logging_lite();
}
} else {
p = szone->helper_zone->basic_zone.malloc((malloc_zone_t *) szone->helper_zone, size);
}
return p;
}
static void *
stack_logging_lite_calloc(struct _malloc_zone_t *zone, size_t num_items, size_t size)
{
szone_t *szone = (szone_t *) zone;
void *p = NULL;
if (stack_logging_lite_enabled) {
size_t total_bytes;
if (calloc_get_size(num_items, size, sizeof(malloc_stack_id), &total_bytes)) {
return NULL;
}
p = szone_malloc_should_clear(szone, total_bytes, 1);
if (p) {
add_stack_to_ptr(szone, total_bytes - sizeof(malloc_stack_id), p);
}
} else {
p = szone->helper_zone->basic_zone.calloc((malloc_zone_t *) szone->helper_zone, num_items, size);
}
return p;
}
static void *
stack_logging_lite_valloc(malloc_zone_t *zone, size_t size)
{
szone_t *szone = (szone_t *) zone;
void *p = NULL;
if (stack_logging_lite_enabled) {
p = szone_valloc(szone, size + sizeof(malloc_stack_id));
if (p) {
add_stack_to_ptr(szone, size, p);
}
} else {
p = szone->helper_zone->basic_zone.valloc((malloc_zone_t *) szone->helper_zone, size);
}
return p;
}
static void
stack_logging_lite_free(malloc_zone_t *zone, void *ptr)
{
szone_t *szone = (szone_t *) zone;
size_t size = szone_size(szone, ptr);
// see if it's in our zone
if (size) {
malloc_stack_id stack_id = get_stack_id_from_ptr(ptr, size);
__decrement_table_slot_refcount(stack_id, size);
szone_free(szone, ptr);
} else {
szone->helper_zone->basic_zone.free((malloc_zone_t *) szone->helper_zone, ptr);
}
}
static void
stack_logging_lite_free_definite_size(malloc_zone_t *zone, void *ptr, size_t size)
{
// because we've messed with the size, don't try to be fancy and just call free
stack_logging_lite_free(zone, ptr);
}
// Three paths:
// 1. do a szone_realloc with padding and add stack id
// 2. do a szone_realloc on the helper zone
// 3. do a manual free / malloc
static void *
stack_logging_lite_realloc(malloc_zone_t *zone, void *ptr, size_t new_size)
{
szone_t *szone = (szone_t *) zone;
void *new_ptr = NULL;
size_t old_size = szone_size(szone, ptr);
// if we own the ptr and lite enabled do our thing
if (old_size && stack_logging_lite_enabled) {
// need to get the old stackid and decrement
malloc_stack_id stack_id = get_stack_id_from_ptr(ptr, old_size);
new_ptr = szone_realloc(szone, ptr, new_size + sizeof(malloc_stack_id));
if (new_ptr) {
__decrement_table_slot_refcount(stack_id, old_size);
add_stack_to_ptr(szone, new_size, new_ptr);
}
} else if (!old_size && !stack_logging_lite_enabled) {
// we don't own the pointer and lite mode is disabled, so just pass the realloc on to the helper zone
return szone->helper_zone->basic_zone.realloc((malloc_zone_t *) szone->helper_zone, ptr, new_size);
} else {
// otherwise perform the realloc by hand:
// 1. malloc new ptr
// 2. copy existing data to new ptr
// 3. free old ptr
// this will add the stack id if needed
new_ptr = stack_logging_lite_malloc(zone, new_size);
if (new_ptr) {
size_t old_size = malloc_size(ptr);
size_t new_size = malloc_size(new_ptr);
// copy as much old data as possible
size_t copy_size = MIN(old_size, new_size);
memcpy(new_ptr, ptr, copy_size);
}
stack_logging_lite_free(zone, ptr);
}
return new_ptr;
}
static void * MALLOC_NOINLINE
stack_logging_lite_memalign(malloc_zone_t *zone, size_t alignment, size_t size)
{
szone_t *szone = (szone_t *) zone;
void *ptr = NULL;
if (stack_logging_lite_enabled) {
ptr = szone_memalign(szone, alignment, size + sizeof(malloc_stack_id));
if (ptr) {
add_stack_to_ptr(szone, size, ptr);
}
} else {
ptr = szone->helper_zone->basic_zone.memalign((malloc_zone_t *) szone->helper_zone, alignment, size);
}
return ptr;
}
static size_t
stack_logging_lite_size(malloc_zone_t *zone, const void *ptr)
{
szone_t *szone = (szone_t *) zone;
size_t size = szone_size(szone, ptr);
if (size) {
size -= sizeof(malloc_stack_id);
} else {
size = szone->helper_zone->basic_zone.size((malloc_zone_t *) szone->helper_zone, ptr);
}
return size;
}
unsigned
stack_logging_lite_batch_malloc(szone_t *szone, size_t size, void **results, unsigned count)
{
unsigned num_allocated = 0;
if (stack_logging_lite_enabled) {
num_allocated = szone_batch_malloc(szone, size + sizeof(malloc_stack_id), results, count);
for (unsigned i = 0; i < num_allocated; i++) {
add_stack_to_ptr(szone, size, results[i]);
}
} else {
num_allocated = szone->helper_zone->basic_zone.batch_malloc((malloc_zone_t *) szone->helper_zone, size, results, count);
}
return num_allocated;
}
void
stack_logging_lite_batch_free(szone_t *szone, void **to_be_freed, unsigned count)
{
for (unsigned i = 0; i < count; i++) {
void *p = to_be_freed[i];
if (p) {
size_t size = szone_size(szone, p);
// see if it's in our zone
if (size) {
malloc_stack_id stack_id = get_stack_id_from_ptr(p, size);
__decrement_table_slot_refcount(stack_id, size);
szone_free(szone, p);
} else {
szone->helper_zone->basic_zone.free((malloc_zone_t *) szone->helper_zone, p);
}
}
}
}
malloc_zone_t *
create_stack_logging_lite_zone(size_t initial_size, malloc_zone_t *helper_zone, unsigned debug_flags)
{
szone_t* zone = create_scalable_szone(initial_size, debug_flags);
// unprotect function pointers
mprotect(zone, sizeof(zone->basic_zone), PROT_READ | PROT_WRITE);
// set the function pointers
zone->basic_zone.malloc = stack_logging_lite_malloc;
zone->basic_zone.calloc = stack_logging_lite_calloc;
zone->basic_zone.valloc = stack_logging_lite_valloc;
zone->basic_zone.realloc = stack_logging_lite_realloc;
zone->basic_zone.batch_malloc = (void *) stack_logging_lite_batch_malloc;
zone->basic_zone.batch_free = (void *) stack_logging_lite_batch_free;
zone->basic_zone.memalign = stack_logging_lite_memalign;
zone->basic_zone.free = stack_logging_lite_free;
zone->basic_zone.free_definite_size = stack_logging_lite_free_definite_size;
zone->basic_zone.size = stack_logging_lite_size;
// protect function pointers
mprotect(zone, sizeof(zone->basic_zone), PROT_READ);
// set helper zone
zone->helper_zone = (szone_t*) helper_zone;
return (malloc_zone_t*) zone;
}
================================================
FILE: InterView-obj-isa-class/libmalloc-166.220.1/src/magazine_malloc.c
================================================
/*
* Copyright (c) 1999, 2006, 2008 Apple Inc. All rights reserved.
*
* @APPLE_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apple Public Source License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. Please obtain a copy of the License at
* http://www.opensource.apple.com/apsl/ and read it before using this
* file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPLE_LICENSE_HEADER_END@
*/
/* Author: Bertrand Serlet, August 1999 */
/*
* Multithread enhancements for "tiny" allocations introduced February 2008.
* These are in the spirit of "Hoard". See:
* Berger, E.D.; McKinley, K.S.; Blumofe, R.D.; Wilson, P.R. (2000).
* "Hoard: a scalable memory allocator for multithreaded applications".
* ACM SIGPLAN Notices 35 (11): 117-128. Berger2000.
*
* Retrieved on 2008-02-22.
*/
#include "internal.h"
#if DEBUG_MALLOC
#define LOG(szone, ptr) (szone->log_address && (((uintptr_t)szone->log_address == -1) || (szone->log_address == (void *)(ptr))))
#else
#define LOG(szone, ptr) 0
#endif
// Maximum number of magazines, set from the number of logical CPUS and
// possibly limited by the MallocMaxMagazines environment variable.
int max_magazines;
// Number of regions to retain in a recirc depot.
#if CONFIG_RECIRC_DEPOT
int recirc_retained_regions = DEFAULT_RECIRC_RETAINED_REGIONS;
#endif // CONFIG_RECIRC_DEPOT
/********************* Zone call backs ************************/
/*
* Mark these MALLOC_NOINLINE to avoid bloating the purgeable zone call backs
*/
void
szone_free(szone_t *szone, void *ptr)
{
region_t tiny_region;
region_t small_region;
#if DEBUG_MALLOC
if (LOG(szone, ptr)) {
malloc_report(ASL_LEVEL_INFO, "in szone_free with %p\n", ptr);
}
#endif
if (!ptr) {
return;
}
/*
* Try to free to a tiny region.
*/
if ((uintptr_t)ptr & (TINY_QUANTUM - 1)) {
malloc_zone_error(szone->debug_flags, true, "Non-aligned pointer %p being freed\n", ptr);
return;
}
if ((tiny_region = tiny_region_for_ptr_no_lock(&szone->tiny_rack, ptr)) != NULL) {
if (TINY_INDEX_FOR_PTR(ptr) >= NUM_TINY_BLOCKS) {
malloc_zone_error(szone->debug_flags, true, "Pointer %p to metadata being freed\n", ptr);
return;
}
free_tiny(&szone->tiny_rack, ptr, tiny_region, 0);
return;
}
/*
* Try to free to a small region.
*/
if ((uintptr_t)ptr & (SMALL_QUANTUM - 1)) {
malloc_zone_error(szone->debug_flags, true, "Non-aligned pointer %p being freed (2)\n", ptr);
return;
}
if ((small_region = small_region_for_ptr_no_lock(&szone->small_rack, ptr)) != NULL) {
if (SMALL_META_INDEX_FOR_PTR(ptr) >= NUM_SMALL_BLOCKS) {
malloc_zone_error(szone->debug_flags, true, "Pointer %p to metadata being freed (2)\n", ptr);
return;
}
free_small(&szone->small_rack, ptr, small_region, 0);
return;
}
/* check that it's a legal large allocation */
if ((uintptr_t)ptr & (vm_page_quanta_size - 1)) {
malloc_zone_error(szone->debug_flags, true, "non-page-aligned, non-allocated pointer %p being freed\n", ptr);
return;
}
free_large(szone, ptr);
}
void
szone_free_definite_size(szone_t *szone, void *ptr, size_t size)
{
#if DEBUG_MALLOC
if (LOG(szone, ptr)) {
malloc_report(ASL_LEVEL_INFO, "in szone_free_definite_size with %p\n", ptr);
}
if (0 == size) {
malloc_zone_error(szone->debug_flags, true, "pointer %p of size zero being freed\n", ptr);
return;
}
#endif
if (!ptr) {
return;
}
/*
* Try to free to a tiny region.
*/
if ((uintptr_t)ptr & (TINY_QUANTUM - 1)) {
malloc_zone_error(szone->debug_flags, true, "Non-aligned pointer %p being freed\n", ptr);
return;
}
if (size <= SMALL_THRESHOLD) {
if (TINY_INDEX_FOR_PTR(ptr) >= NUM_TINY_BLOCKS) {
malloc_zone_error(szone->debug_flags, true, "Pointer %p to metadata being freed\n", ptr);
return;
}
free_tiny(&szone->tiny_rack, ptr, TINY_REGION_FOR_PTR(ptr), size);
return;
}
/*
* Try to free to a small region.
*/
if ((uintptr_t)ptr & (SMALL_QUANTUM - 1)) {
malloc_zone_error(szone->debug_flags, true, "Non-aligned pointer %p being freed (2)\n", ptr);
return;
}
if (size <= szone->large_threshold) {
if (SMALL_META_INDEX_FOR_PTR(ptr) >= NUM_SMALL_BLOCKS) {
malloc_zone_error(szone->debug_flags, true, "Pointer %p to metadata being freed (2)\n", ptr);
return;
}
free_small(&szone->small_rack, ptr, SMALL_REGION_FOR_PTR(ptr), size);
return;
}
/* check that it's a legal large allocation */
if ((uintptr_t)ptr & (vm_page_quanta_size - 1)) {
malloc_zone_error(szone->debug_flags, true, "non-page-aligned, non-allocated pointer %p being freed\n", ptr);
return;
}
free_large(szone, ptr);
}
MALLOC_NOINLINE void *
szone_malloc_should_clear(szone_t *szone, size_t size, boolean_t cleared_requested)
{
void *ptr;
msize_t msize;
if (size <= SMALL_THRESHOLD) {
// tiny size: <=1008 bytes (64-bit), <=496 bytes (32-bit)
// think tiny
msize = TINY_MSIZE_FOR_BYTES(size + TINY_QUANTUM - 1);
if (!msize) {
msize = 1;
}
ptr = tiny_malloc_should_clear(&szone->tiny_rack, msize, cleared_requested);
} else if (size <= szone->large_threshold) {
// small size: <=15k (iOS), <=64k (large iOS), <=128k (macOS)
// think small
msize = SMALL_MSIZE_FOR_BYTES(size + SMALL_QUANTUM - 1);
if (!msize) {
msize = 1;
}
ptr = small_malloc_should_clear(&szone->small_rack, msize, cleared_requested);
} else {
// large: all other allocations
size_t num_kernel_pages = round_page_quanta(size) >> vm_page_quanta_shift;
if (num_kernel_pages == 0) { /* Overflowed */
ptr = 0;
} else {
ptr = large_malloc(szone, num_kernel_pages, 0, cleared_requested);
}
}
#if DEBUG_MALLOC
if (LOG(szone, ptr)) {
malloc_report(ASL_LEVEL_INFO, "szone_malloc returned %p\n", ptr);
}
#endif
/*
* If requested, scribble on allocated memory.
*/
if ((szone->debug_flags & MALLOC_DO_SCRIBBLE) && ptr && !cleared_requested && size) {
memset(ptr, SCRIBBLE_BYTE, szone_size(szone, ptr));
}
return ptr;
}
void *
szone_malloc(szone_t *szone, size_t size)
{
return szone_malloc_should_clear(szone, size, 0);
}
void *
szone_calloc(szone_t *szone, size_t num_items, size_t size)
{
size_t total_bytes;
if (calloc_get_size(num_items, size, 0, &total_bytes)) {
return NULL;
}
return szone_malloc_should_clear(szone, total_bytes, 1);
}
void *
szone_valloc(szone_t *szone, size_t size)
{
void *ptr;
if (size <= szone->large_threshold) {
ptr = szone_memalign(szone, vm_page_quanta_size, size);
} else {
size_t num_kernel_pages;
num_kernel_pages = round_page_quanta(size) >> vm_page_quanta_shift;
ptr = large_malloc(szone, num_kernel_pages, 0, 0);
}
#if DEBUG_MALLOC
if (LOG(szone, ptr)) {
malloc_report(ASL_LEVEL_INFO, "szone_valloc returned %p\n", ptr);
}
#endif
return ptr;
}
/* Isolate PIC-base load here. */
size_t
szone_size_try_large(szone_t *szone, const void *ptr)
{
size_t size = 0;
large_entry_t *entry;
SZONE_LOCK(szone);
entry = large_entry_for_pointer_no_lock(szone, ptr);
if (entry) {
size = entry->size;
}
SZONE_UNLOCK(szone);
#if DEBUG_MALLOC
if (LOG(szone, ptr)) {
malloc_report(ASL_LEVEL_INFO, "szone_size for %p returned %d\n", ptr, (unsigned)size);
}
#endif
return size;
}
size_t
szone_size(szone_t *szone, const void *ptr)
{
size_t sz = 0;
if (!ptr) {
return 0;
}
#if DEBUG_MALLOC
if (LOG(szone, ptr)) {
malloc_report(ASL_LEVEL_INFO, "in szone_size for %p (szone=%p)\n", ptr, szone);
}
#endif
/*
* Look for it in a tiny region.
*/
if ((uintptr_t)ptr & (TINY_QUANTUM - 1)) {
return 0;
}
sz = tiny_size(&szone->tiny_rack, ptr);
if (sz) {
return sz;
}
/*
* Look for it in a small region.
*/
if ((uintptr_t)ptr & (SMALL_QUANTUM - 1)) {
return 0;
}
sz = small_size(&szone->small_rack, ptr);
if (sz) {
return sz;
}
/*
* If not page-aligned, it cannot have come from a large allocation.
*/
if ((uintptr_t)ptr & (vm_page_quanta_size - 1)) {
return 0;
}
/*
* Look for it in a large entry.
*/
return szone_size_try_large(szone, ptr);
}
void *
szone_realloc(szone_t *szone, void *ptr, size_t new_size)
{
size_t old_size, new_good_size, valid_size;
void *new_ptr;
#if DEBUG_MALLOC
if (LOG(szone, ptr)) {
malloc_report(ASL_LEVEL_INFO, "in szone_realloc for %p, %d\n", ptr, (unsigned)new_size);
}
#endif
if (NULL == ptr) {
// If ptr is a null pointer, realloc() shall be equivalent to malloc() for the specified size.
return szone_malloc(szone, new_size);
} else if (0 == new_size) {
// If size is 0 and ptr is not a null pointer, the object pointed to is freed.
szone_free(szone, ptr);
// If size is 0, either a null pointer or a unique pointer that can be successfully passed
// to free() shall be returned.
return szone_malloc(szone, 1);
}
old_size = szone_size(szone, ptr);
if (!old_size) {
malloc_zone_error(szone->debug_flags, true, "pointer %p being reallocated was not allocated\n", ptr);
return NULL;
}
new_good_size = szone_good_size(szone, new_size);
if (new_good_size == old_size) { // Existing allocation is best fit evar?
return ptr;
}
/*
* If the new size suits the tiny allocator and the pointer being resized
* belongs to a tiny region, try to reallocate in-place.
*/
if (new_good_size <= SMALL_THRESHOLD) {
if (old_size <= SMALL_THRESHOLD) {
if (new_good_size <= (old_size >> 1)) {
/*
* Serious shrinkage (more than half). free() the excess.
*/
return tiny_try_shrink_in_place(&szone->tiny_rack, ptr, old_size, new_good_size);
} else if (new_good_size <= old_size) {
/*
* new_good_size smaller than old_size but not by much (less than half).
* Avoid thrashing at the expense of some wasted storage.
*/
if (szone->debug_flags & MALLOC_DO_SCRIBBLE) {
memset(ptr + new_size, SCRIBBLE_BYTE, old_size - new_size);
}
return ptr;
} else if (tiny_try_realloc_in_place(&szone->tiny_rack, ptr, old_size, new_good_size)) { // try to grow the allocation
if (szone->debug_flags & MALLOC_DO_SCRIBBLE) {
memset(ptr + old_size, SCRIBBLE_BYTE, new_good_size - old_size);
}
return ptr;
}
}
/*
* Else if the new size suits the small allocator and the pointer being resized
* belongs to a small region, and we're not protecting the small allocations
* try to reallocate in-place.
*/
} else if (new_good_size <= szone->large_threshold) {
if (SMALL_THRESHOLD < old_size && old_size <= szone->large_threshold) {
if (new_good_size <= (old_size >> 1)) {
return small_try_shrink_in_place(&szone->small_rack, ptr, old_size, new_good_size);
} else if (new_good_size <= old_size) {
if (szone->debug_flags & MALLOC_DO_SCRIBBLE) {
memset(ptr + new_size, SCRIBBLE_BYTE, old_size - new_size);
}
return ptr;
} else if (small_try_realloc_in_place(&szone->small_rack, ptr, old_size, new_good_size)) {
if (szone->debug_flags & MALLOC_DO_SCRIBBLE) {
memset(ptr + old_size, SCRIBBLE_BYTE, new_good_size - old_size);
}
return ptr;
}
}
/*
* Else if the allocation's a large allocation, try to reallocate in-place there.
*/
} else if (!(szone->debug_flags & MALLOC_PURGEABLE) && // purgeable needs fresh allocation
(old_size > szone->large_threshold) && (new_good_size > szone->large_threshold)) {
if (new_good_size <= (old_size >> 1)) {
return large_try_shrink_in_place(szone, ptr, old_size, new_good_size);
} else if (new_good_size <= old_size) {
if (szone->debug_flags & MALLOC_DO_SCRIBBLE) {
memset(ptr + new_size, SCRIBBLE_BYTE, old_size - new_size);
}
return ptr;
} else if (large_try_realloc_in_place(szone, ptr, old_size, new_good_size)) {
if (szone->debug_flags & MALLOC_DO_SCRIBBLE) {
memset(ptr + old_size, SCRIBBLE_BYTE, new_good_size - old_size);
}
return ptr;
}
}
/*
* Can't reallocate in place for whatever reason; allocate a new buffer and copy.
*/
if (new_good_size <= (old_size >> 1)) {
/* Serious shrinkage (more than half). FALL THROUGH to alloc/copy/free. */
} else if (new_good_size <= old_size) {
if (szone->debug_flags & MALLOC_DO_SCRIBBLE) {
memset(ptr + new_size, SCRIBBLE_BYTE, old_size - new_size);
}
return ptr;
}
new_ptr = szone_malloc(szone, new_size);
if (new_ptr == NULL) {
return NULL;
}
/*
* If the allocation's large enough, try to copy using VM. If that fails, or
* if it's too small, just copy by hand.
*/
valid_size = MIN(old_size, new_size);
if ((valid_size <= szone->vm_copy_threshold) ||
vm_copy(mach_task_self(), (vm_address_t)ptr, valid_size, (vm_address_t)new_ptr)) {
memcpy(new_ptr, ptr, valid_size);
}
szone_free(szone, ptr);
#if DEBUG_MALLOC
if (LOG(szone, ptr)) {
malloc_report(ASL_LEVEL_INFO, "szone_realloc returned %p for %d\n", new_ptr, (unsigned)new_size);
}
#endif
return new_ptr;
}
void *
szone_memalign(szone_t *szone, size_t alignment, size_t size)
{
if (size == 0) {
size = 1; // Ensures we'll return an aligned free()-able pointer
}
if ((size + alignment) < size) { // size_t arithmetic wrapped!
return NULL;
}
// alignment is gauranteed a power of 2 at least as large as sizeof(void *), hence non-zero.
// Since size + alignment didn't wrap, 0 <= size + alignment - 1 < size + alignment
size_t span = size + alignment - 1;
if (alignment <= TINY_QUANTUM) {
return szone_malloc(szone, size); // Trivially satisfied by tiny, small, or large
}
if (span <= SMALL_THRESHOLD) {
return tiny_memalign(szone, alignment, size, span);
}
if (SMALL_THRESHOLD < size && alignment <= SMALL_QUANTUM) {
return szone_malloc(szone, size); // Trivially satisfied by small or large
}
if (size <= SMALL_THRESHOLD) {
// ensure block allocated by small does not have a tiny-possible size
size = SMALL_THRESHOLD + TINY_QUANTUM;
span = size + alignment - 1;
}
if (span <= szone->large_threshold) {
return small_memalign(szone, alignment, size, span);
}
if (szone->large_threshold < size && alignment <= vm_page_quanta_size) {
return szone_malloc(szone, size); // Trivially satisfied by large
}
// ensure block allocated by large does not have a small-possible size
size_t num_kernel_pages = round_page_quanta(MAX(szone->large_threshold + 1,
size)) >> vm_page_quanta_shift;
if (num_kernel_pages == 0) { /* Overflowed */
return NULL;
} else {
return large_malloc(szone, num_kernel_pages,
MAX(vm_page_quanta_shift, __builtin_ctz((unsigned)alignment)), 0);
}
/* NOTREACHED */
}
// Given a size, returns the number of pointers allocated capable of holding
// that size, up to the limit specified by the 'count' argument. These pointers
// are stored in the 'results' array, which must be allocated by the caller.
// May return zero, since this function is only a best attempt at allocating
// the pointers. Clients should be prepared to call malloc for any additional
// blocks they need.
unsigned
szone_batch_malloc(szone_t *szone, size_t size, void **results, unsigned count)
{
// only bother implementing this for tiny
if (size <= SMALL_THRESHOLD) {
return tiny_batch_malloc(szone, size, results, count);
}
return 0;
}
void
szone_batch_free(szone_t *szone, void **to_be_freed, unsigned count)
{
// frees all the pointers in to_be_freed
// note that to_be_freed may be overwritten during the process
if (!count) {
return;
}
CHECK(szone, __PRETTY_FUNCTION__);
// We only support batch malloc in tiny. Let it free all of the pointers
// that belong to it, then let the standard free deal with the rest.
tiny_batch_free(szone, to_be_freed, count);
CHECK(szone, __PRETTY_FUNCTION__);
while (count--) {
void *ptr = to_be_freed[count];
if (ptr) {
szone_free(szone, ptr);
}
}
}
// FIXME: Suppose one of the locks is held?
static void
szone_destroy(szone_t *szone)
{
size_t index;
large_entry_t *large;
vm_range_t range_to_deallocate;
#if CONFIG_LARGE_CACHE
SZONE_LOCK(szone);
/* disable any memory pressure responder */
szone->flotsam_enabled = FALSE;
// stack allocated copy of the death-row cache
int idx = szone->large_entry_cache_oldest, idx_max = szone->large_entry_cache_newest;
large_entry_t local_entry_cache[LARGE_ENTRY_CACHE_SIZE];
memcpy((void *)local_entry_cache, (void *)szone->large_entry_cache, sizeof(local_entry_cache));
szone->large_entry_cache_oldest = szone->large_entry_cache_newest = 0;
szone->large_entry_cache[0].address = 0x0;
szone->large_entry_cache[0].size = 0;
szone->large_entry_cache_bytes = 0;
szone->large_entry_cache_reserve_bytes = 0;
SZONE_UNLOCK(szone);
// deallocate the death-row cache outside the zone lock
while (idx != idx_max) {
mvm_deallocate_pages((void *)local_entry_cache[idx].address, local_entry_cache[idx].size, 0);
if (++idx == LARGE_ENTRY_CACHE_SIZE) {
idx = 0;
}
}
if (0 != local_entry_cache[idx].address && 0 != local_entry_cache[idx].size) {
mvm_deallocate_pages((void *)local_entry_cache[idx].address, local_entry_cache[idx].size, 0);
}
#endif
/* destroy large entries */
index = szone->num_large_entries;
while (index--) {
large = szone->large_entries + index;
if (large->address) {
// we deallocate_pages, including guard pages
mvm_deallocate_pages((void *)(large->address), large->size, szone->debug_flags);
}
}
large_entries_free_no_lock(szone, szone->large_entries, szone->num_large_entries, &range_to_deallocate);
if (range_to_deallocate.size) {
mvm_deallocate_pages((void *)range_to_deallocate.address, (size_t)range_to_deallocate.size, 0);
}
/* destroy allocator regions */
rack_destroy_regions(&szone->tiny_rack, TINY_REGION_SIZE);
rack_destroy_regions(&szone->small_rack, SMALL_REGION_SIZE);
/* destroy rack region hash rings and racks themselves */
rack_destroy(&szone->tiny_rack);
rack_destroy(&szone->small_rack);
mvm_deallocate_pages((void *)szone, SZONE_PAGED_SIZE, 0);
}
size_t
szone_good_size(szone_t *szone, size_t size)
{
msize_t msize;
// Find a good size for this tiny allocation.
if (size <= SMALL_THRESHOLD) {
msize = TINY_MSIZE_FOR_BYTES(size + TINY_QUANTUM - 1);
if (!msize) {
msize = 1;
}
return TINY_BYTES_FOR_MSIZE(msize);
}
// Find a good size for this small allocation.
if (size <= szone->large_threshold) {
msize = SMALL_MSIZE_FOR_BYTES(size + SMALL_QUANTUM - 1);
if (!msize) {
msize = 1;
}
return SMALL_BYTES_FOR_MSIZE(msize);
}
// Check for integer overflow on the size, since unlike the two cases above,
// there is no upper bound on allocation size at this point.
if (size > round_page_quanta(size)) {
return (size_t)(-1LL);
}
#if DEBUG_MALLOC
// It is not acceptable to see a size of zero here, since that means we
// failed to catch a request for zero bytes in the tiny check, or the size
// overflowed to zero during some arithmetic.
if (size == 0) {
malloc_report(ASL_LEVEL_INFO, "szone_good_size() invariant broken %y\n", size);
}
#endif
return round_page_quanta(size);
}
boolean_t
szone_claimed_address(szone_t *szone, void *ptr)
{
return tiny_claimed_address(&szone->tiny_rack, ptr)
|| small_claimed_address(&szone->small_rack, ptr)
|| large_claimed_address(szone, ptr);
}
unsigned szone_check_counter = 0;
unsigned szone_check_start = 0;
unsigned szone_check_modulo = 1;
static MALLOC_NOINLINE boolean_t
szone_check_all(szone_t *szone, const char *function)
{
size_t index;
/* check tiny regions - chould check region count */
for (index = 0; index < szone->tiny_rack.region_generation->num_regions_allocated; ++index) {
region_t tiny = szone->tiny_rack.region_generation->hashed_regions[index];
if (HASHRING_REGION_DEALLOCATED == tiny) {
continue;
}
if (tiny) {
magazine_t *tiny_mag_ptr = mag_lock_zine_for_region_trailer(szone->tiny_rack.magazines,
REGION_TRAILER_FOR_TINY_REGION(tiny),
MAGAZINE_INDEX_FOR_TINY_REGION(tiny));
if (!tiny_check_region(&szone->tiny_rack, tiny, index, szone_check_counter)) {
SZONE_MAGAZINE_PTR_UNLOCK(tiny_mag_ptr);
szone->debug_flags &= ~CHECK_REGIONS;
return 0;
}
SZONE_MAGAZINE_PTR_UNLOCK(tiny_mag_ptr);
}
}
/* check tiny free lists */
for (index = 0; index < NUM_TINY_SLOTS; ++index) {
if (!tiny_free_list_check(&szone->tiny_rack, (grain_t)index, szone_check_counter)) {
szone->debug_flags &= ~CHECK_REGIONS;
return 0;
}
}
/* check small regions - could check region count */
for (index = 0; index < szone->small_rack.region_generation->num_regions_allocated; ++index) {
region_t small = szone->small_rack.region_generation->hashed_regions[index];
if (HASHRING_REGION_DEALLOCATED == small) {
continue;
}
if (small) {
magazine_t *small_mag_ptr = mag_lock_zine_for_region_trailer(szone->small_rack.magazines,
REGION_TRAILER_FOR_SMALL_REGION(small),
MAGAZINE_INDEX_FOR_SMALL_REGION(small));
if (!small_check_region(&szone->small_rack, small, index, szone_check_counter)) {
SZONE_MAGAZINE_PTR_UNLOCK(small_mag_ptr);
szone->debug_flags &= ~CHECK_REGIONS;
return 0;
}
SZONE_MAGAZINE_PTR_UNLOCK(small_mag_ptr);
}
}
/* check small free lists */
for (index = 0; index < SMALL_FREE_SLOT_COUNT(&szone->small_rack); ++index) {
if (!small_free_list_check(&szone->small_rack, (grain_t)index, szone_check_counter)) {
szone->debug_flags &= ~CHECK_REGIONS;
return 0;
}
}
return 1;
}
static boolean_t
szone_check(szone_t *szone)
{
if ((++szone_check_counter % 10000) == 0) {
malloc_report(ASL_LEVEL_NOTICE, "at szone_check counter=%d\n", szone_check_counter);
}
if (szone_check_counter < szone_check_start) {
return 1;
}
if (szone_check_counter % szone_check_modulo) {
return 1;
}
return szone_check_all(szone, "");
}
static kern_return_t
szone_ptr_in_use_enumerator(task_t task,
void *context,
unsigned type_mask,
vm_address_t zone_address,
memory_reader_t reader,
vm_range_recorder_t recorder)
{
szone_t *szone;
kern_return_t err;
if (!reader) {
reader = _szone_default_reader;
}
err = reader(task, zone_address, sizeof(szone_t), (void **)&szone);
if (err) {
return err;
}
err = tiny_in_use_enumerator(task, context, type_mask, szone, reader, recorder);
if (err) {
return err;
}
err = small_in_use_enumerator(task, context, type_mask, szone, reader, recorder);
if (err) {
return err;
}
err = large_in_use_enumerator(
task, context, type_mask, (vm_address_t)szone->large_entries, szone->num_large_entries, reader, recorder);
return err;
}
// Following method is deprecated: use scalable_zone_statistics instead
void
scalable_zone_info(malloc_zone_t *zone, unsigned *info_to_fill, unsigned count)
{
szone_t *szone = (void *)zone;
unsigned info[13];
// We do not lock to facilitate debug
size_t s = 0;
unsigned t = 0;
size_t u = 0;
mag_index_t mag_index;
for (mag_index = -1; mag_index < szone->tiny_rack.num_magazines; mag_index++) {
s += szone->tiny_rack.magazines[mag_index].mag_bytes_free_at_start;
s += szone->tiny_rack.magazines[mag_index].mag_bytes_free_at_end;
t += szone->tiny_rack.magazines[mag_index].mag_num_objects;
u += szone->tiny_rack.magazines[mag_index].mag_num_bytes_in_objects;
}
info[4] = (unsigned)t;
info[5] = (unsigned)u;
for (t = 0, u = 0, mag_index = -1; mag_index < szone->small_rack.num_magazines; mag_index++) {
s += szone->small_rack.magazines[mag_index].mag_bytes_free_at_start;
s += szone->small_rack.magazines[mag_index].mag_bytes_free_at_end;
t += szone->small_rack.magazines[mag_index].mag_num_objects;
u += szone->small_rack.magazines[mag_index].mag_num_bytes_in_objects;
}
info[6] = (unsigned)t;
info[7] = (unsigned)u;
info[8] = (unsigned)szone->num_large_objects_in_use;
info[9] = (unsigned)szone->num_bytes_in_large_objects;
info[10] = 0; // DEPRECATED szone->num_huge_entries;
info[11] = 0; // DEPRECATED szone->num_bytes_in_huge_objects;
info[12] = szone->debug_flags;
info[0] = info[4] + info[6] + info[8] + info[10];
info[1] = info[5] + info[7] + info[9] + info[11];
info[3] = (unsigned)(szone->tiny_rack.num_regions - szone->tiny_rack.num_regions_dealloc) * TINY_REGION_SIZE +
(unsigned)(szone->small_rack.num_regions - szone->small_rack.num_regions_dealloc) * SMALL_REGION_SIZE + info[9] + info[11];
info[2] = info[3] - (unsigned)s;
memcpy(info_to_fill, info, sizeof(unsigned) * count);
}
// FIXME: consistent picture requires locking!
static MALLOC_NOINLINE void
szone_print(szone_t *szone, boolean_t verbose)
{
unsigned info[13];
size_t index;
region_t region;
scalable_zone_info((void *)szone, info, 13);
malloc_report(MALLOC_REPORT_NOLOG | MALLOC_REPORT_NOPREFIX,
"Scalable zone %p: inUse=%u(%y) touched=%y allocated=%y flags=%d\n", szone, info[0], info[1], info[2], info[3],
info[12]);
malloc_report(MALLOC_REPORT_NOLOG | MALLOC_REPORT_NOPREFIX, "\ttiny=%u(%y) small=%u(%y) large=%u(%y) huge=%u(%y)\n", info[4],
info[5], info[6], info[7], info[8], info[9], info[10], info[11]);
// tiny
malloc_report(MALLOC_REPORT_NOLOG | MALLOC_REPORT_NOPREFIX, "%lu tiny regions:\n", szone->tiny_rack.num_regions);
if (szone->tiny_rack.num_regions_dealloc) {
malloc_report(MALLOC_REPORT_NOLOG | MALLOC_REPORT_NOPREFIX, "[%lu tiny regions have been vm_deallocate'd]\n",
szone->tiny_rack.num_regions_dealloc);
}
for (index = 0; index < szone->tiny_rack.region_generation->num_regions_allocated; ++index) {
region = szone->tiny_rack.region_generation->hashed_regions[index];
if (HASHRING_OPEN_ENTRY != region && HASHRING_REGION_DEALLOCATED != region) {
mag_index_t mag_index = MAGAZINE_INDEX_FOR_TINY_REGION(region);
print_tiny_region(verbose, region, (region == szone->tiny_rack.magazines[mag_index].mag_last_region)
? szone->tiny_rack.magazines[mag_index].mag_bytes_free_at_start
: 0,
(region == szone->tiny_rack.magazines[mag_index].mag_last_region)
? szone->tiny_rack.magazines[mag_index].mag_bytes_free_at_end
: 0);
}
}
if (verbose) {
print_tiny_free_list(&szone->tiny_rack);
}
// small
malloc_report(MALLOC_REPORT_NOLOG | MALLOC_REPORT_NOPREFIX, "%lu small regions:\n", szone->small_rack.num_regions);
if (szone->small_rack.num_regions_dealloc) {
malloc_report(MALLOC_REPORT_NOLOG | MALLOC_REPORT_NOPREFIX, "[%lu small regions have been vm_deallocate'd]\n",
szone->small_rack.num_regions_dealloc);
}
for (index = 0; index < szone->small_rack.region_generation->num_regions_allocated; ++index) {
region = szone->small_rack.region_generation->hashed_regions[index];
if (HASHRING_OPEN_ENTRY != region && HASHRING_REGION_DEALLOCATED != region) {
mag_index_t mag_index = MAGAZINE_INDEX_FOR_SMALL_REGION(region);
print_small_region(szone, verbose, region, (region == szone->small_rack.magazines[mag_index].mag_last_region)
? szone->small_rack.magazines[mag_index].mag_bytes_free_at_start
: 0,
(region == szone->small_rack.magazines[mag_index].mag_last_region)
? szone->small_rack.magazines[mag_index].mag_bytes_free_at_end
: 0);
}
}
if (verbose) {
print_small_free_list(&szone->small_rack);
}
}
static void
szone_log(malloc_zone_t *zone, void *log_address)
{
szone_t *szone = (szone_t *)zone;
szone->log_address = log_address;
}
//
// When forcing the lock on the entire zone, make sure we are out of the critical section in each magazine
static MALLOC_INLINE void
szone_force_lock_magazine(szone_t *szone, magazine_t *mag)
{
while (1) {
SZONE_MAGAZINE_PTR_LOCK(mag);
if (!mag->alloc_underway) {
return;
}
SZONE_MAGAZINE_PTR_UNLOCK(mag);
yield();
}
}
static void
szone_force_lock(szone_t *szone)
{
mag_index_t i;
for (i = 0; i < szone->tiny_rack.num_magazines; ++i) {
szone_force_lock_magazine(szone, &szone->tiny_rack.magazines[i]);
}
szone_force_lock_magazine(szone, &szone->tiny_rack.magazines[DEPOT_MAGAZINE_INDEX]);
for (i = 0; i < szone->small_rack.num_magazines; ++i) {
szone_force_lock_magazine(szone, &szone->small_rack.magazines[i]);
}
szone_force_lock_magazine(szone, &szone->small_rack.magazines[DEPOT_MAGAZINE_INDEX]);
SZONE_LOCK(szone);
}
static void
szone_force_unlock(szone_t *szone)
{
mag_index_t i;
SZONE_UNLOCK(szone);
for (i = -1; i < szone->small_rack.num_magazines; ++i) {
SZONE_MAGAZINE_PTR_UNLOCK((&(szone->small_rack.magazines[i])));
}
for (i = -1; i < szone->tiny_rack.num_magazines; ++i) {
SZONE_MAGAZINE_PTR_UNLOCK((&(szone->tiny_rack.magazines[i])));
}
}
static void
szone_reinit_lock(szone_t *szone)
{
mag_index_t i;
SZONE_REINIT_LOCK(szone);
for (i = -1; i < szone->small_rack.num_magazines; ++i) {
SZONE_MAGAZINE_PTR_REINIT_LOCK((&(szone->small_rack.magazines[i])));
}
for (i = -1; i < szone->tiny_rack.num_magazines; ++i) {
SZONE_MAGAZINE_PTR_REINIT_LOCK((&(szone->tiny_rack.magazines[i])));
}
}
static boolean_t
szone_locked(szone_t *szone)
{
mag_index_t i;
int tookLock;
tookLock = SZONE_TRY_LOCK(szone);
if (tookLock == 0) {
return 1;
}
SZONE_UNLOCK(szone);
for (i = -1; i < szone->small_rack.num_magazines; ++i) {
tookLock = SZONE_MAGAZINE_PTR_TRY_LOCK((&(szone->small_rack.magazines[i])));
if (tookLock == 0) {
return 1;
}
SZONE_MAGAZINE_PTR_UNLOCK((&(szone->small_rack.magazines[i])));
}
for (i = -1; i < szone->tiny_rack.num_magazines; ++i) {
tookLock = SZONE_MAGAZINE_PTR_TRY_LOCK((&(szone->tiny_rack.magazines[i])));
if (tookLock == 0) {
return 1;
}
SZONE_MAGAZINE_PTR_UNLOCK((&(szone->tiny_rack.magazines[i])));
}
return 0;
}
size_t
szone_pressure_relief(szone_t *szone, size_t goal)
{
size_t total = 0;
MAGMALLOC_PRESSURERELIEFBEGIN((void *)szone, szone->basic_zone.zone_name, (int)goal); // DTrace USDT Probe
MALLOC_TRACE(TRACE_malloc_memory_pressure | DBG_FUNC_START, (uint64_t)szone, goal, 0, 0);
#if CONFIG_MADVISE_PRESSURE_RELIEF
mag_index_t mag_index;
magazine_t *tiny_depot_ptr = (&szone->tiny_rack.magazines[DEPOT_MAGAZINE_INDEX]);
magazine_t *small_depot_ptr = (&szone->small_rack.magazines[DEPOT_MAGAZINE_INDEX]);
for (mag_index = 0; mag_index < szone->tiny_rack.num_magazines; mag_index++) {
size_t index;
for (index = 0; index < szone->tiny_rack.region_generation->num_regions_allocated; ++index) {
SZONE_LOCK(szone);
region_t tiny = szone->tiny_rack.region_generation->hashed_regions[index];
if (!tiny || tiny == HASHRING_REGION_DEALLOCATED) {
SZONE_UNLOCK(szone);
continue;
}
magazine_t *mag_ptr = mag_lock_zine_for_region_trailer(szone->tiny_rack.magazines,
REGION_TRAILER_FOR_TINY_REGION(tiny),
MAGAZINE_INDEX_FOR_TINY_REGION(tiny));
SZONE_UNLOCK(szone);
/* Ordering is important here, the magazine of a region may potentially change
* during mag_lock_zine_for_region_trailer, so src_mag_index must be taken
* after we've obtained the lock.
*/
mag_index_t src_mag_index = MAGAZINE_INDEX_FOR_TINY_REGION(tiny);
/* We can (and must) ignore magazines that are already in the recirc depot. */
if (src_mag_index == DEPOT_MAGAZINE_INDEX) {
SZONE_MAGAZINE_PTR_UNLOCK(mag_ptr);
continue;
}
if (tiny == mag_ptr->mag_last_region && (mag_ptr->mag_bytes_free_at_end || mag_ptr->mag_bytes_free_at_start)) {
tiny_finalize_region(&szone->tiny_rack, mag_ptr);
}
/* Because this region is currently in use, we can't safely madvise it while
* it's attached to the magazine. For this operation we have to remove it from
* the current mag, attach it to the depot and then madvise.
*/
recirc_list_extract(&szone->tiny_rack, mag_ptr, REGION_TRAILER_FOR_TINY_REGION(tiny));
int objects_in_use = tiny_free_detach_region(&szone->tiny_rack, mag_ptr, tiny);
SZONE_MAGAZINE_PTR_LOCK(tiny_depot_ptr);
MAGAZINE_INDEX_FOR_TINY_REGION(tiny) = DEPOT_MAGAZINE_INDEX;
REGION_TRAILER_FOR_TINY_REGION(tiny)->pinned_to_depot = 0;
size_t bytes_inplay = tiny_free_reattach_region(&szone->tiny_rack, tiny_depot_ptr, tiny);
/* Fix up the metadata of the target magazine while the region is in the depot. */
mag_ptr->mag_num_bytes_in_objects -= bytes_inplay;
mag_ptr->num_bytes_in_magazine -= TINY_REGION_PAYLOAD_BYTES;
mag_ptr->mag_num_objects -= objects_in_use;
/* Now we can drop the magazine lock of the source mag. */
SZONE_MAGAZINE_PTR_UNLOCK(mag_ptr);
tiny_depot_ptr->mag_num_bytes_in_objects += bytes_inplay;
tiny_depot_ptr->num_bytes_in_magazine += TINY_REGION_PAYLOAD_BYTES;
tiny_depot_ptr->mag_num_objects -= objects_in_use;
recirc_list_splice_last(&szone->tiny_rack, tiny_depot_ptr, REGION_TRAILER_FOR_TINY_REGION(tiny));
/* Actually do the scan, done holding the depot lock, the call will drop the lock
* around the actual madvise syscalls.
*/
tiny_free_scan_madvise_free(&szone->tiny_rack, tiny_depot_ptr, tiny);
/* Now the region is in the recirc depot, the next allocations to require more
* blocks will come along and take one of these regions back out of the depot.
* As OS X madvise's reuse on an per-region basis, we leave as many of these
* regions in the depot as possible after memory pressure.
*/
SZONE_MAGAZINE_PTR_UNLOCK(tiny_depot_ptr);
}
}
for (mag_index = 0; mag_index < szone->small_rack.num_magazines; mag_index++) {
size_t index;
for (index = 0; index < szone->small_rack.region_generation->num_regions_allocated; ++index) {
SZONE_LOCK(szone);
region_t small = szone->small_rack.region_generation->hashed_regions[index];
if (!small || small == HASHRING_REGION_DEALLOCATED) {
SZONE_UNLOCK(szone);
continue;
}
magazine_t *mag_ptr = mag_lock_zine_for_region_trailer(szone->small_rack.magazines,
REGION_TRAILER_FOR_SMALL_REGION(small),
MAGAZINE_INDEX_FOR_SMALL_REGION(small));
SZONE_UNLOCK(szone);
/* Ordering is important here, the magazine of a region may potentially change
* during mag_lock_zine_for_region_trailer, so src_mag_index must be taken
* after we've obtained the lock.
*/
mag_index_t src_mag_index = MAGAZINE_INDEX_FOR_SMALL_REGION(small);
/* We can (and must) ignore magazines that are already in the recirc depot. */
if (src_mag_index == DEPOT_MAGAZINE_INDEX) {
SZONE_MAGAZINE_PTR_UNLOCK(mag_ptr);
continue;
}
if (small == mag_ptr->mag_last_region && (mag_ptr->mag_bytes_free_at_end || mag_ptr->mag_bytes_free_at_start)) {
small_finalize_region(&szone->small_rack, mag_ptr);
}
/* Because this region is currently in use, we can't safely madvise it while
* it's attached to the magazine. For this operation we have to remove it from
* the current mag, attach it to the depot and then madvise.
*/
recirc_list_extract(&szone->small_rack, mag_ptr, REGION_TRAILER_FOR_SMALL_REGION(small));
int objects_in_use = small_free_detach_region(&szone->small_rack, mag_ptr, small);
SZONE_MAGAZINE_PTR_LOCK(small_depot_ptr);
MAGAZINE_INDEX_FOR_SMALL_REGION(small) = DEPOT_MAGAZINE_INDEX;
REGION_TRAILER_FOR_SMALL_REGION(small)->pinned_to_depot = 0;
size_t bytes_inplay = small_free_reattach_region(&szone->small_rack, small_depot_ptr, small);
/* Fix up the metadata of the target magazine while the region is in the depot. */
mag_ptr->mag_num_bytes_in_objects -= bytes_inplay;
mag_ptr->num_bytes_in_magazine -= SMALL_REGION_PAYLOAD_BYTES;
mag_ptr->mag_num_objects -= objects_in_use;
/* Now we can drop the magazine lock of the source mag. */
SZONE_MAGAZINE_PTR_UNLOCK(mag_ptr);
small_depot_ptr->mag_num_bytes_in_objects += bytes_inplay;
small_depot_ptr->num_bytes_in_magazine += SMALL_REGION_PAYLOAD_BYTES;
small_depot_ptr->mag_num_objects -= objects_in_use;
recirc_list_splice_last(&szone->small_rack, small_depot_ptr, REGION_TRAILER_FOR_SMALL_REGION(small));
/* Actually do the scan, done holding the depot lock, the call will drop the lock
* around the actual madvise syscalls.
*/
small_free_scan_madvise_free(&szone->small_rack, small_depot_ptr, small);
/* Now the region is in the recirc depot, the next allocations to require more
* blocks will come along and take one of these regions back out of the depot.
* As OS X madvise's reuse on an per-region basis, we leave as many of these
* regions in the depot as possible after memory pressure.
*/
SZONE_MAGAZINE_PTR_UNLOCK(small_depot_ptr);
}
}
#endif
#if CONFIG_LARGE_CACHE
if (szone->flotsam_enabled) {
SZONE_LOCK(szone);
// stack allocated copy of the death-row cache
int idx = szone->large_entry_cache_oldest, idx_max = szone->large_entry_cache_newest;
large_entry_t local_entry_cache[LARGE_ENTRY_CACHE_SIZE];
memcpy((void *)local_entry_cache, (void *)szone->large_entry_cache, sizeof(local_entry_cache));
szone->large_entry_cache_oldest = szone->large_entry_cache_newest = 0;
szone->large_entry_cache[0].address = 0x0;
szone->large_entry_cache[0].size = 0;
szone->large_entry_cache_bytes = 0;
szone->large_entry_cache_reserve_bytes = 0;
szone->flotsam_enabled = FALSE;
SZONE_UNLOCK(szone);
// deallocate the death-row cache outside the zone lock
size_t total = 0;
while (idx != idx_max) {
mvm_deallocate_pages((void *)local_entry_cache[idx].address, local_entry_cache[idx].size, 0);
total += local_entry_cache[idx].size;
if (++idx == LARGE_ENTRY_CACHE_SIZE) {
idx = 0;
}
}
if (0 != local_entry_cache[idx].address && 0 != local_entry_cache[idx].size) {
mvm_deallocate_pages((void *)local_entry_cache[idx].address, local_entry_cache[idx].size, 0);
total += local_entry_cache[idx].size;
}
}
#endif
MAGMALLOC_PRESSURERELIEFEND((void *)szone, szone->basic_zone.zone_name, (int)goal, (int)total); // DTrace USDT Probe
MALLOC_TRACE(TRACE_malloc_memory_pressure | DBG_FUNC_END, (uint64_t)szone, goal, total, 0);
return total;
}
boolean_t
scalable_zone_statistics(malloc_zone_t *zone, malloc_statistics_t *stats, unsigned subzone)
{
szone_t *szone = (szone_t *)zone;
switch (subzone) {
case 0: {
size_t s = 0;
unsigned t = 0;
size_t u = 0;
mag_index_t mag_index;
for (mag_index = -1; mag_index < szone->tiny_rack.num_magazines; mag_index++) {
s += szone->tiny_rack.magazines[mag_index].mag_bytes_free_at_start;
s += szone->tiny_rack.magazines[mag_index].mag_bytes_free_at_end;
t += szone->tiny_rack.magazines[mag_index].mag_num_objects;
u += szone->tiny_rack.magazines[mag_index].mag_num_bytes_in_objects;
}
stats->blocks_in_use = t;
stats->size_in_use = u;
stats->size_allocated = (szone->tiny_rack.num_regions - szone->tiny_rack.num_regions_dealloc) * TINY_REGION_SIZE;
stats->max_size_in_use = stats->size_allocated - s;
return 1;
}
case 1: {
size_t s = 0;
unsigned t = 0;
size_t u = 0;
mag_index_t mag_index;
for (mag_index = -1; mag_index < szone->small_rack.num_magazines; mag_index++) {
s += szone->small_rack.magazines[mag_index].mag_bytes_free_at_start;
s += szone->small_rack.magazines[mag_index].mag_bytes_free_at_end;
t += szone->small_rack.magazines[mag_index].mag_num_objects;
u += szone->small_rack.magazines[mag_index].mag_num_bytes_in_objects;
}
stats->blocks_in_use = t;
stats->size_in_use = u;
stats->size_allocated = (szone->small_rack.num_regions - szone->small_rack.num_regions_dealloc) * SMALL_REGION_SIZE;
stats->max_size_in_use = stats->size_allocated - s;
return 1;
}
case 2:
stats->blocks_in_use = szone->num_large_objects_in_use;
stats->size_in_use = szone->num_bytes_in_large_objects;
stats->max_size_in_use = stats->size_allocated = stats->size_in_use;
return 1;
case 3:
stats->blocks_in_use = 0; // DEPRECATED szone->num_huge_entries;
stats->size_in_use = 0; // DEPRECATED szone->num_bytes_in_huge_objects;
stats->max_size_in_use = stats->size_allocated = 0;
return 1;
}
return 0;
}
static void
szone_statistics(szone_t *szone, malloc_statistics_t *stats)
{
size_t large;
size_t s = 0;
unsigned t = 0;
size_t u = 0;
mag_index_t mag_index;
for (mag_index = -1; mag_index < szone->tiny_rack.num_magazines; mag_index++) {
s += szone->tiny_rack.magazines[mag_index].mag_bytes_free_at_start;
s += szone->tiny_rack.magazines[mag_index].mag_bytes_free_at_end;
t += szone->tiny_rack.magazines[mag_index].mag_num_objects;
u += szone->tiny_rack.magazines[mag_index].mag_num_bytes_in_objects;
}
for (mag_index = -1; mag_index < szone->small_rack.num_magazines; mag_index++) {
s += szone->small_rack.magazines[mag_index].mag_bytes_free_at_start;
s += szone->small_rack.magazines[mag_index].mag_bytes_free_at_end;
t += szone->small_rack.magazines[mag_index].mag_num_objects;
u += szone->small_rack.magazines[mag_index].mag_num_bytes_in_objects;
}
large = szone->num_bytes_in_large_objects + 0; // DEPRECATED szone->num_bytes_in_huge_objects;
stats->blocks_in_use = t + szone->num_large_objects_in_use + 0; // DEPRECATED szone->num_huge_entries;
stats->size_in_use = u + large;
stats->max_size_in_use = stats->size_allocated =
(szone->tiny_rack.num_regions - szone->tiny_rack.num_regions_dealloc) * TINY_REGION_SIZE +
(szone->small_rack.num_regions - szone->small_rack.num_regions_dealloc) * SMALL_REGION_SIZE + large;
// Now we account for the untouched areas
stats->max_size_in_use -= s;
}
const struct malloc_introspection_t szone_introspect = {
(void *)szone_ptr_in_use_enumerator, (void *)szone_good_size, (void *)szone_check, (void *)szone_print, szone_log,
(void *)szone_force_lock, (void *)szone_force_unlock, (void *)szone_statistics, (void *)szone_locked, NULL, NULL, NULL,
NULL, /* Zone enumeration version 7 and forward. */
(void *)szone_reinit_lock, // reinit_lock version 9 and foward
}; // marked as const to spare the DATA section
szone_t *
create_scalable_szone(size_t initial_size, unsigned debug_flags)
{
szone_t *szone;
#if defined(__i386__) || defined(__x86_64__)
if (_COMM_PAGE_VERSION_REQD > (*((uint16_t *)_COMM_PAGE_VERSION))) {
MALLOC_REPORT_FATAL_ERROR((*((uint16_t *)_COMM_PAGE_VERSION)), "comm page version mismatch");
}
#endif
/* get memory for the zone. */
szone = mvm_allocate_pages(SZONE_PAGED_SIZE, 0, 0, VM_MEMORY_MALLOC);
if (!szone) {
return NULL;
}
/* set up the szone structure */
#if 0
#warning CHECK_REGIONS enabled
debug_flags |= CHECK_REGIONS;
#endif
#if 0
#warning LOG enabled
szone->log_address = ~0;
#endif
if (mvm_aslr_enabled()) {
debug_flags &= ~DISABLE_ASLR;
} else {
debug_flags |= DISABLE_ASLR;
}
#if CONFIG_SMALL_CUTOFF_DYNAMIC || CONFIG_LARGE_CACHE
uint64_t memsize = platform_hw_memsize();
#endif
bool is_largemem = false;
#if CONFIG_SMALL_CUTOFF_LARGEMEM
is_largemem = true;
#elif CONFIG_SMALL_CUTOFF_DYNAMIC
// TODO: rdar://problem/35395572
// switch to largemem thresholds on devices with > 2 cores and > 2gb of memory
uint32_t nproc = platform_cpu_count();
is_largemem = (nproc > 2) && (memsize > (2ull << 30));
#endif
if (is_largemem) {
debug_flags |= MALLOC_EXTENDED_SMALL_SLOTS;
szone->is_largemem = 1;
szone->large_threshold = LARGE_THRESHOLD_LARGEMEM;
szone->vm_copy_threshold = VM_COPY_THRESHOLD_LARGEMEM;
} else {
debug_flags &= ~MALLOC_EXTENDED_SMALL_SLOTS;
szone->is_largemem = 0;
szone->large_threshold = LARGE_THRESHOLD;
szone->vm_copy_threshold = VM_COPY_THRESHOLD;
}
// Query the number of configured processors.
// Uniprocessor case gets just one tiny and one small magazine (whose index is zero). This gives
// the same behavior as the original scalable malloc. MP gets per-CPU magazines
// that scale (way) better.
unsigned int max_mags = mag_max_magazines();
uint32_t num_magazines = (max_mags > 1) ? MIN(max_mags, TINY_MAX_MAGAZINES) : 1;
rack_init(&szone->tiny_rack, RACK_TYPE_TINY, num_magazines, debug_flags);
rack_init(&szone->small_rack, RACK_TYPE_SMALL, num_magazines, debug_flags);
#if CONFIG_LARGE_CACHE
// madvise(..., MADV_REUSABLE) death-row arrivals above this threshold [~0.1%]
szone->large_entry_cache_reserve_limit = (size_t)(memsize >> 10);
/* Reset protection when returning a previous large allocation? */
int32_t libSystemVersion = NSVersionOfLinkTimeLibrary("System");
if ((-1 != libSystemVersion) && ((libSystemVersion >> 16) < 112) /* CFSystemVersionSnowLeopard */) {
szone->large_legacy_reset_mprotect = TRUE;
} else {
szone->large_legacy_reset_mprotect = FALSE;
}
#endif
// Initialize the security token.
szone->cookie = (uintptr_t)malloc_entropy[0];
szone->basic_zone.version = 10;
szone->basic_zone.size = (void *)szone_size;
szone->basic_zone.malloc = (void *)szone_malloc;
szone->basic_zone.calloc = (void *)szone_calloc;
szone->basic_zone.valloc = (void *)szone_valloc;
szone->basic_zone.free = (void *)szone_free;
szone->basic_zone.realloc = (void *)szone_realloc;
szone->basic_zone.destroy = (void *)szone_destroy;
szone->basic_zone.batch_malloc = (void *)szone_batch_malloc;
szone->basic_zone.batch_free = (void *)szone_batch_free;
szone->basic_zone.introspect = (struct malloc_introspection_t *)&szone_introspect;
szone->basic_zone.memalign = (void *)szone_memalign;
szone->basic_zone.free_definite_size = (void *)szone_free_definite_size;
szone->basic_zone.pressure_relief = (void *)szone_pressure_relief;
szone->basic_zone.claimed_address = (void *)szone_claimed_address;
/* Set to zero once and for all as required by CFAllocator. */
szone->basic_zone.reserved1 = 0;
/* Set to zero once and for all as required by CFAllocator. */
szone->basic_zone.reserved2 = 0;
/* Prevent overwriting the function pointers in basic_zone. */
mprotect(szone, sizeof(szone->basic_zone), PROT_READ);
szone->debug_flags = debug_flags;
_malloc_lock_init(&szone->large_szone_lock);
szone->cpu_id_key = -1UL; // Unused.
CHECK(szone, __PRETTY_FUNCTION__);
return szone;
}
malloc_zone_t *
create_scalable_zone(size_t initial_size, unsigned debug_flags) {
return (malloc_zone_t *) create_scalable_szone(initial_size, debug_flags);
}
/* vim: set noet:ts=4:sw=4:cindent: */
================================================
FILE: InterView-obj-isa-class/libmalloc-166.220.1/src/magazine_malloc.h
================================================
/*
* Copyright (c) 2015 Apple Inc. All rights reserved.
*
* @APPLE_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apple Public Source License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. Please obtain a copy of the License at
* http://www.opensource.apple.com/apsl/ and read it before using this
* file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPLE_LICENSE_HEADER_END@
*/
#ifndef __MAGAZINE_MALLOC_H
#define __MAGAZINE_MALLOC_H
// MARK: magazine_malloc
MALLOC_NOEXPORT
malloc_zone_t *
create_scalable_zone(size_t initial_size, unsigned debug_flags);
MALLOC_NOEXPORT
szone_t *
create_scalable_szone(size_t initial_size, unsigned debug_flags);
MALLOC_EXPORT
boolean_t
scalable_zone_statistics(malloc_zone_t *zone, malloc_statistics_t *stats, unsigned subzone);
MALLOC_NOEXPORT
extern int max_magazines;
MALLOC_NOEXPORT
extern int recirc_retained_regions;
// MARK: magazine_malloc utility functions
MALLOC_NOEXPORT
extern const
struct malloc_introspection_t szone_introspect;
MALLOC_NOEXPORT
void
szone_batch_free(szone_t *szone, void **to_be_freed, unsigned count);
MALLOC_NOEXPORT
unsigned
szone_batch_malloc(szone_t *szone, size_t size, void **results, unsigned count);
MALLOC_NOEXPORT
void *
szone_calloc(szone_t *szone, size_t num_items, size_t size);
MALLOC_NOEXPORT
void
szone_free(szone_t *szone, void *ptr);
MALLOC_NOEXPORT
void
szone_free_definite_size(szone_t *szone, void *ptr, size_t size);
MALLOC_NOEXPORT
size_t
szone_good_size(szone_t *szone, size_t size);
MALLOC_NOEXPORT
void *
szone_malloc(szone_t *szone, size_t size);
MALLOC_NOEXPORT
void *
szone_memalign(szone_t *szone, size_t alignment, size_t size);
MALLOC_NOEXPORT
size_t
szone_pressure_relief(szone_t *szone, size_t goal);
MALLOC_NOEXPORT
boolean_t
szone_claimed_address(szone_t *szone, void *ptr);
MALLOC_NOEXPORT
void *
szone_realloc(szone_t *szone, void *ptr, size_t new_size);
MALLOC_NOEXPORT
size_t
szone_size(szone_t *szone, const void *ptr);
MALLOC_NOEXPORT
size_t
szone_size_try_large(szone_t *szone, const void *ptr);
MALLOC_NOEXPORT
void *
szone_valloc(szone_t *szone, size_t size);
// MARK: tiny region allocator functions
MALLOC_NOEXPORT
boolean_t
tiny_check_region(rack_t *rack, region_t region, size_t region_index,
unsigned counter);
MALLOC_NOEXPORT
void
tiny_finalize_region(rack_t *rack, magazine_t *tiny_mag_ptr);
MALLOC_NOEXPORT
int
tiny_free_detach_region(rack_t *rack, magazine_t *tiny_mag_ptr, region_t r);
MALLOC_NOEXPORT
boolean_t
tiny_free_list_check(rack_t *rack, grain_t slot, unsigned counter);
MALLOC_NOEXPORT
boolean_t
tiny_free_no_lock(rack_t *rack, magazine_t *tiny_mag_ptr, mag_index_t mag_index, region_t region, void *ptr, msize_t msize);
MALLOC_NOEXPORT
size_t
tiny_free_reattach_region(rack_t *rack, magazine_t *tiny_mag_ptr, region_t r);
MALLOC_NOEXPORT
void
tiny_free_scan_madvise_free(rack_t *rack, magazine_t *depot_ptr, region_t r);
MALLOC_NOEXPORT
kern_return_t
tiny_in_use_enumerator(task_t task, void *context, unsigned type_mask, szone_t *szone, memory_reader_t reader,
vm_range_recorder_t recorder);
MALLOC_NOEXPORT
void *
tiny_malloc_from_free_list(rack_t *rack, magazine_t *tiny_mag_ptr, mag_index_t mag_index, msize_t msize);
MALLOC_NOEXPORT
void *
tiny_malloc_should_clear(rack_t *rack, msize_t msize, boolean_t cleared_requested);
MALLOC_NOEXPORT
void *
tiny_memalign(szone_t *szone, size_t alignment, size_t size, size_t span);
MALLOC_NOEXPORT
boolean_t
tiny_claimed_address(rack_t *rack, void *ptr);
MALLOC_NOEXPORT
void *
tiny_try_shrink_in_place(rack_t *rack, void *ptr, size_t old_size, size_t new_good_size);
MALLOC_NOEXPORT
boolean_t
tiny_try_realloc_in_place(rack_t *rack, void *ptr, size_t old_size, size_t new_size);
MALLOC_NOEXPORT
void
free_tiny(rack_t *rack, void *ptr, region_t tiny_region, size_t known_size);
MALLOC_NOEXPORT
size_t
tiny_size(rack_t *rack, const void *ptr);
MALLOC_NOEXPORT
unsigned
tiny_batch_malloc(szone_t *szone, size_t size, void **results, unsigned count);
MALLOC_NOEXPORT
void
tiny_batch_free(szone_t *szone, void **to_be_freed, unsigned count);
MALLOC_NOEXPORT
void
print_tiny_free_list(rack_t *rack);
MALLOC_NOEXPORT
void
print_tiny_region(boolean_t verbose, region_t region, size_t bytes_at_start, size_t bytes_at_end);
// MARK: small region allocation functions
MALLOC_NOEXPORT
boolean_t
small_check_region(rack_t *rack, region_t region, size_t region_index,
unsigned counter);
MALLOC_NOEXPORT
void
small_finalize_region(rack_t *rack, magazine_t *small_mag_ptr);
MALLOC_NOEXPORT
int
small_free_detach_region(rack_t *rack, magazine_t *small_mag_ptr, region_t r);
MALLOC_NOEXPORT
boolean_t
small_free_list_check(rack_t *rack, grain_t slot, unsigned counter);
MALLOC_NOEXPORT
size_t
small_free_reattach_region(rack_t *rack, magazine_t *small_mag_ptr, region_t r);
MALLOC_NOEXPORT
void
small_free_scan_madvise_free(rack_t *rack, magazine_t *depot_ptr, region_t r);
MALLOC_NOEXPORT
kern_return_t
small_in_use_enumerator(task_t task, void *context, unsigned type_mask, szone_t *szone, memory_reader_t reader,
vm_range_recorder_t recorder);
MALLOC_NOEXPORT
void *
small_malloc_should_clear(rack_t *rack, msize_t msize, boolean_t cleared_requested);
MALLOC_NOEXPORT
void *
small_memalign(szone_t *szone, size_t alignment, size_t size, size_t span);
MALLOC_NOEXPORT
boolean_t
small_claimed_address(rack_t *rack, void *ptr);
MALLOC_NOEXPORT
void *
small_try_shrink_in_place(rack_t *rack, void *ptr, size_t old_size, size_t new_good_size);
MALLOC_NOEXPORT
boolean_t
small_try_realloc_in_place(rack_t *rack, void *ptr, size_t old_size, size_t new_size);
MALLOC_NOEXPORT
void
free_small(rack_t *rack, void *ptr, region_t small_region, size_t known_size);
MALLOC_NOEXPORT
size_t
small_size(rack_t *rack, const void *ptr);
MALLOC_NOEXPORT
void
print_small_free_list(rack_t *rack);
MALLOC_NOEXPORT
void
print_small_region(szone_t *szone, boolean_t verbose, region_t region, size_t bytes_at_start, size_t bytes_at_end);
// MARK: large region allocator functions
MALLOC_NOEXPORT
void
free_large(szone_t *szone, void *ptr);
MALLOC_NOEXPORT
void
large_entries_free_no_lock(szone_t *szone, large_entry_t *entries, unsigned num, vm_range_t *range_to_deallocate);
MALLOC_NOEXPORT
large_entry_t *
large_entry_for_pointer_no_lock(szone_t *szone, const void *ptr);
MALLOC_NOEXPORT
kern_return_t
large_in_use_enumerator(task_t task, void *context, unsigned type_mask, vm_address_t large_entries_address, unsigned num_entries,
memory_reader_t reader, vm_range_recorder_t recorder);
MALLOC_NOEXPORT
int
large_try_realloc_in_place(szone_t *szone, void *ptr, size_t old_size, size_t new_size);
MALLOC_NOEXPORT
void *
large_try_shrink_in_place(szone_t *szone, void *ptr, size_t old_size, size_t new_good_size);
MALLOC_NOEXPORT
void *
large_malloc(szone_t *szone, size_t num_kernel_pages, unsigned char alignment, boolean_t cleared_requested);
MALLOC_NOEXPORT
boolean_t
large_claimed_address(szone_t *szone, void *ptr);
MALLOC_NOEXPORT
void *
szone_malloc_should_clear(szone_t *szone, size_t size, boolean_t cleared_requested);
// MARK: stack logging lite functionality
#define MALLOC_STOCK_LOGGING_LITE_ZONE_NAME "MallocStackLoggingLiteZone"
// These enable/disable stack logging lite for malloc allocations, not VM-only lite mode
MALLOC_NOEXPORT
void
enable_stack_logging_lite();
MALLOC_NOEXPORT
void
disable_stack_logging_lite();
MALLOC_NOEXPORT
malloc_zone_t *
create_stack_logging_lite_zone(size_t initial_size, malloc_zone_t *helper_zone, unsigned debug_flags);
#endif // __MAGAZINE_MALLOC_H
================================================
FILE: InterView-obj-isa-class/libmalloc-166.220.1/src/magazine_rack.c
================================================
/*
* Copyright (c) 2016 Apple Inc. All rights reserved.
*
* @APPLE_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apple Public Source License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. Please obtain a copy of the License at
* http://www.opensource.apple.com/apsl/ and read it before using this
* file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPLE_LICENSE_HEADER_END@
*/
#include "internal.h"
void
rack_init(rack_t *rack, rack_type_t type, uint32_t num_magazines, uint32_t debug_flags)
{
rack->type = type;
rack->rg[0].nextgen = &rack->rg[1];
rack->rg[1].nextgen = &rack->rg[0];
rack->region_generation = &rack->rg[0];
rack->region_generation->hashed_regions = rack->initial_regions;
rack->region_generation->num_regions_allocated = INITIAL_NUM_REGIONS;
rack->region_generation->num_regions_allocated_shift = INITIAL_NUM_REGIONS_SHIFT;
memset(rack->initial_regions, '\0', sizeof(region_t) * INITIAL_NUM_REGIONS);
rack->cookie = (uintptr_t)malloc_entropy[0];
if (type == RACK_TYPE_SMALL) {
// Flip the cookie for SMALL regions so that tiny and small free list
// entries will trap when used if used in opposing region types.
rack->cookie = ~rack->cookie;
}
rack->debug_flags = debug_flags;
rack->num_magazines = num_magazines;
rack->num_regions = 0;
rack->num_regions_dealloc = 0;
rack->magazines = NULL;
if (num_magazines > 0) {
// num_magazines + 1, the [-1] index will become the depot magazine
size_t magsize = round_page_quanta(sizeof(magazine_t) * (num_magazines + 1));
magazine_t *magazines = mvm_allocate_pages(magsize, 0, MALLOC_ADD_GUARD_PAGES, VM_MEMORY_MALLOC);
if (!magazines) {
MALLOC_REPORT_FATAL_ERROR(0, "unable to allocate magazine array");
}
rack->magazines = &magazines[1];
rack->num_magazines_mask_shift = 0;
// The magazines are indexed in [0 .. (num_magazines - 1)]
// Find the smallest power of 2 that exceeds (num_magazines - 1)
int i = 1;
while (i <= (num_magazines - 1)) {
rack->num_magazines_mask_shift++;
i <<= 1;
}
// Reduce i by 1 to obtain a mask covering [0 .. (num_tiny_magazines - 1)]
rack->num_magazines_mask = i - 1;
rack->last_madvise = 0;
_malloc_lock_init(&rack->region_lock);
_malloc_lock_init(&rack->magazines[DEPOT_MAGAZINE_INDEX].magazine_lock);
for (int i=0; i < rack->num_magazines; i++) {
_malloc_lock_init(&rack->magazines[i].magazine_lock);
}
}
}
void
rack_destroy_regions(rack_t *rack, size_t region_size)
{
/* destroy regions attached to this rack */
for (int i=0; i < rack->region_generation->num_regions_allocated; i++) {
if ((rack->region_generation->hashed_regions[i] != HASHRING_OPEN_ENTRY) &&
(rack->region_generation->hashed_regions[i] != HASHRING_REGION_DEALLOCATED))
{
mvm_deallocate_pages(rack->region_generation->hashed_regions[i], region_size, 0);
rack->region_generation->hashed_regions[i] = HASHRING_REGION_DEALLOCATED;
}
}
}
void
rack_destroy(rack_t *rack)
{
/* if the rack has additional regions, then deallocate them */
if (rack->region_generation->hashed_regions != rack->initial_regions) {
size_t size = round_page_quanta(rack->region_generation->num_regions_allocated * sizeof(region_t));
mvm_deallocate_pages(rack->region_generation->hashed_regions, size, 0);
}
if (rack->num_magazines > 0) {
size_t size = round_page_quanta(sizeof(magazine_t) * (rack->num_magazines + 1));
mvm_deallocate_pages(&rack->magazines[-1], size, MALLOC_ADD_GUARD_PAGES);
rack->magazines = NULL;
}
}
void
rack_region_insert(rack_t *rack, region_t region)
{
// Here find the only place in rackland that (infrequently) takes the tiny_regions_lock.
// Only one thread at a time should be permitted to assess the density of the hash
// ring and adjust if needed.
// Only one thread at a time should be permitted to insert its new region on
// the hash ring.
// It is safe for all other threads to read the hash ring (hashed_regions) and
// the associated sizes (num_regions_allocated and num_tiny_regions).
_malloc_lock_lock(&rack->region_lock);
// Check to see if the hash ring of tiny regions needs to grow. Try to
// avoid the hash ring becoming too dense.
if (rack->region_generation->num_regions_allocated < (2 * rack->num_regions)) {
region_t *new_regions;
size_t new_size;
size_t new_shift = rack->region_generation->num_regions_allocated_shift; // In/Out parameter
new_regions = hash_regions_grow_no_lock(rack->region_generation->hashed_regions,
rack->region_generation->num_regions_allocated, &new_shift, &new_size);
// Do not deallocate the current hashed_regions allocation since someone may
// be iterating it. Instead, just leak it.
// Prepare to advance to the "next generation" of the hash ring.
rack->region_generation->nextgen->hashed_regions = new_regions;
rack->region_generation->nextgen->num_regions_allocated = new_size;
rack->region_generation->nextgen->num_regions_allocated_shift = new_shift;
// Throw the switch to atomically advance to the next generation.
rack->region_generation = rack->region_generation->nextgen;
// Ensure everyone sees the advance.
OSMemoryBarrier();
}
// Insert the new region into the hash ring, and update malloc statistics
hash_region_insert_no_lock(rack->region_generation->hashed_regions,
rack->region_generation->num_regions_allocated,
rack->region_generation->num_regions_allocated_shift,
region);
rack->num_regions++;
_malloc_lock_unlock(&rack->region_lock);
}
================================================
FILE: InterView-obj-isa-class/libmalloc-166.220.1/src/magazine_rack.h
================================================
/*
* Copyright (c) 2016 Apple Inc. All rights reserved.
*
* @APPLE_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apple Public Source License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. Please obtain a copy of the License at
* http://www.opensource.apple.com/apsl/ and read it before using this
* file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPLE_LICENSE_HEADER_END@
*/
#ifndef __MAGAZINE_RACK_H
#define __MAGAZINE_RACK_H
/*******************************************************************************
* Definitions for region hash
******************************************************************************/
typedef void *region_t;
typedef region_t *rgnhdl_t; /* A pointer into hashed_regions array. */
#define INITIAL_NUM_REGIONS_SHIFT 6 // log2(INITIAL_NUM_REGIONS)
#define INITIAL_NUM_REGIONS (1 << INITIAL_NUM_REGIONS_SHIFT) // Must be a power of 2!
#define HASHRING_OPEN_ENTRY ((region_t)0) // Initial value and sentinel marking end of collision chain
#define HASHRING_REGION_DEALLOCATED ((region_t)-1) // Region at this slot reclaimed by OS
#define HASH_BLOCKS_ALIGN TINY_BLOCKS_ALIGN // MIN( TINY_BLOCKS_ALIGN, SMALL_BLOCKS_ALIGN, ... )
typedef struct region_hash_generation {
size_t num_regions_allocated;
size_t num_regions_allocated_shift; // log2(num_regions_allocated)
region_t *hashed_regions; // hashed by location
struct region_hash_generation *nextgen;
} region_hash_generation_t;
OS_ENUM(rack_type, uint32_t,
RACK_TYPE_NONE = 0,
RACK_TYPE_TINY,
RACK_TYPE_SMALL,
);
/*******************************************************************************
* Per-allocator collection of regions and magazines
******************************************************************************/
typedef struct rack_s {
/* Regions for tiny objects */
_malloc_lock_s region_lock MALLOC_CACHE_ALIGN;
rack_type_t type;
size_t num_regions;
size_t num_regions_dealloc;
region_hash_generation_t *region_generation;
region_hash_generation_t rg[2];
region_t initial_regions[INITIAL_NUM_REGIONS];
int num_magazines;
unsigned num_magazines_mask;
int num_magazines_mask_shift;
uint32_t debug_flags;
// array of per-processor magazines
magazine_t *magazines;
uintptr_t cookie;
uintptr_t last_madvise;
} rack_t;
MALLOC_NOEXPORT
void
rack_init(rack_t *rack, rack_type_t type, uint32_t num_magazines, uint32_t debug_flags);
MALLOC_NOEXPORT
void
rack_destroy_regions(rack_t *rack, size_t region_size);
MALLOC_NOEXPORT
void
rack_destroy(rack_t *rack);
MALLOC_NOEXPORT
void
rack_region_insert(rack_t *rack, region_t region);
#endif // __MAGAZINE_RACK_H
================================================
FILE: InterView-obj-isa-class/libmalloc-166.220.1/src/magazine_small.c
================================================
/*
* Copyright (c) 2015 Apple Inc. All rights reserved.
*
* @APPLE_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apple Public Source License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. Please obtain a copy of the License at
* http://www.opensource.apple.com/apsl/ and read it before using this
* file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPLE_LICENSE_HEADER_END@
*/
#include "internal.h"
/********************* SMALL FREE LIST UTILITIES ************************/
#pragma mark meta header helpers
/*
* Mark a block as free. Only the first quantum of a block is marked thusly,
* the remainder are marked "middle".
*/
static MALLOC_INLINE void
small_meta_header_set_is_free(msize_t *meta_headers, msize_t index, msize_t msize)
{
meta_headers[index] = msize | SMALL_IS_FREE;
}
/*
* Mark a block as not free, preserving its size.
*/
static MALLOC_INLINE void
small_meta_header_set_not_free(msize_t *meta_headers, msize_t index)
{
meta_headers[index] &= ~SMALL_IS_FREE;
}
/*
* Mark a block as in use. Only the first quantum of a block is marked thusly,
* the remainder are marked "middle".
*/
static MALLOC_INLINE void
small_meta_header_set_in_use(msize_t *meta_headers, msize_t index, msize_t msize)
{
meta_headers[index] = msize;
}
/*
* Mark a quantum as being the second or later in a block.
*/
static MALLOC_INLINE void
small_meta_header_set_middle(msize_t *meta_headers, msize_t index)
{
meta_headers[index] = 0;
}
static MALLOC_INLINE MALLOC_ALWAYS_INLINE
mag_index_t
small_mag_get_thread_index(void)
{
#if CONFIG_SMALL_USES_HYPER_SHIFT
if (os_likely(_os_cpu_number_override == -1)) {
return _os_cpu_number() >> hyper_shift;
} else {
return _os_cpu_number_override >> hyper_shift;
}
#else // CONFIG_SMALL_USES_HYPER_SHIFT
if (os_likely(_os_cpu_number_override == -1)) {
return _os_cpu_number();
} else {
return _os_cpu_number_override;
}
#endif // CONFIG_SMALL_USES_HYPER_SHIFT
}
#pragma mark in-place free list
static MALLOC_INLINE void
small_inplace_checksum_ptr(rack_t *rack, inplace_linkage_s *linkage, void *ptr)
{
uintptr_t checksum = free_list_gen_checksum((uintptr_t)ptr ^ rack->cookie ^ (uintptr_t)rack);
linkage->checksum = checksum;
linkage->ptr = ptr;
}
static MALLOC_INLINE free_list_t
small_inplace_unchecksum_ptr(rack_t *rack, inplace_linkage_s *linkage)
{
if (linkage->checksum != (uint8_t)free_list_gen_checksum((uintptr_t)linkage->ptr ^ rack->cookie ^ (uintptr_t)rack)) {
free_list_checksum_botch(rack, linkage, linkage->ptr);
__builtin_trap();
}
return (free_list_t){ .p = linkage->ptr };
}
static MALLOC_INLINE free_list_t
small_inplace_free_entry_get_previous(rack_t *rack, small_inplace_free_entry_t ptr)
{
return small_inplace_unchecksum_ptr(rack, &ptr->previous);
}
static MALLOC_INLINE void
small_inplace_free_entry_set_previous(rack_t *rack, small_inplace_free_entry_t entry, free_list_t previous)
{
small_inplace_checksum_ptr(rack, &entry->previous, previous.p);
}
static MALLOC_INLINE free_list_t
small_inplace_free_entry_get_next(rack_t *rack, small_inplace_free_entry_t ptr)
{
return small_inplace_unchecksum_ptr(rack, &ptr->next);
}
static MALLOC_INLINE void
small_inplace_free_entry_set_next(rack_t *rack, small_inplace_free_entry_t entry, free_list_t next)
{
small_inplace_checksum_ptr(rack, &entry->next, next.p);
}
#pragma mark OOB free list
// Returns true if the address and size of the free list entry would result
// in the free entry being the only data on a given page.
static MALLOC_INLINE boolean_t
small_needs_oob_free_entry(void *ptr, msize_t msize)
{
return ((trunc_page_quanta((uintptr_t)ptr) == (uintptr_t)ptr) && (SMALL_BYTES_FOR_MSIZE(msize) >= vm_kernel_page_size));
}
// Returns true if the address given lies within the region's OOB free
// list entries, rather than a free_list_t in the region's heap space.
static MALLOC_INLINE boolean_t
small_is_oob_free_entry(free_list_t ptr)
{
small_region_t region = SMALL_REGION_FOR_PTR(ptr.p);
return (((uintptr_t)ptr.p >= (uintptr_t)®ion->small_oob_free_entries[0]) &&
((uintptr_t)ptr.p < (uintptr_t)®ion->small_oob_free_entries[SMALL_OOB_COUNT]));
}
static MALLOC_INLINE void
small_oob_free_entry_set_previous(oob_free_entry_t oobe, free_list_t previous)
{
oobe->prev = (uintptr_t)previous.p;
}
static MALLOC_INLINE free_list_t
small_oob_free_entry_get_previous(oob_free_entry_t oobe)
{
return (free_list_t){ .p = (void *)oobe->prev };
}
static MALLOC_INLINE void
small_oob_free_entry_set_next(oob_free_entry_t oobe, free_list_t next)
{
oobe->next = (uintptr_t)next.p;
}
static MALLOC_INLINE free_list_t
small_oob_free_entry_get_next(oob_free_entry_t oobe)
{
return (free_list_t){ .p = (void *)oobe->next };
}
static MALLOC_INLINE void *
small_oob_free_entry_get_ptr(oob_free_entry_t oobe)
{
small_region_t region = SMALL_REGION_FOR_PTR(oobe);
uint16_t block = oobe->ptr & ~SMALL_IS_OOB;
return (void *)((uintptr_t)region + (block << SHIFT_SMALL_QUANTUM));
}
static MALLOC_INLINE void
small_oob_free_entry_set_ptr(oob_free_entry_t oobe, void *ptr)
{
oobe->ptr = SMALL_IS_OOB | (SMALL_OFFSET_FOR_PTR(ptr) >> SHIFT_SMALL_QUANTUM);
}
static MALLOC_INLINE void
small_oob_free_entry_set_free(oob_free_entry_t oobe)
{
oobe->prev = ~0;
oobe->next = ~0;
oobe->ptr = 0;
}
// Finds the first unused OOB free list entry in the pointer's region.
// Returns NULL if all of the OOB entries are used.
static MALLOC_INLINE oob_free_entry_t
small_oob_free_find_empty(void *ptr, msize_t msize)
{
small_region_t region = SMALL_REGION_FOR_PTR(ptr);
// There are 61 of these entries at the end of a small region.
// If this changes, then a linear search through the list may
// become an unsuitable choice.
for (int i=0; i < SMALL_OOB_COUNT; i++) {
if (region->small_oob_free_entries[i].ptr == 0) {
return ®ion->small_oob_free_entries[i];
}
}
#if DEBUG_MALLOC
malloc_report(ASL_LEVEL_INFO, "used all slots of OOB entries\n");
#endif
return NULL;
}
static MALLOC_INLINE oob_free_entry_t
small_oob_free_find_ptr(void *ptr, msize_t msize)
{
small_region_t region = SMALL_REGION_FOR_PTR(ptr);
// There are 61 of these entries at the end of a small region.
// If this changes, then a linear search through the list may
// become an unsuitable choice.
for (int i=0; i < SMALL_OOB_COUNT; i++) {
if (small_oob_free_entry_get_ptr(®ion->small_oob_free_entries[i]) == ptr) {
return ®ion->small_oob_free_entries[i];
}
}
return NULL;
}
#pragma mark generic free list
static MALLOC_INLINE void
small_free_list_set_previous(rack_t *rack, free_list_t entry, free_list_t previous)
{
if (small_is_oob_free_entry(entry)) {
small_oob_free_entry_set_previous(entry.oob, previous);
} else {
small_inplace_free_entry_set_previous(rack, entry.small_inplace, previous);
}
}
static MALLOC_INLINE free_list_t
small_free_list_get_previous(rack_t *rack, free_list_t ptr)
{
MALLOC_ASSERT(ptr.p);
if (small_is_oob_free_entry(ptr)) {
return small_oob_free_entry_get_previous(ptr.oob);
} else {
return small_inplace_free_entry_get_previous(rack, ptr.small_inplace);
}
}
static MALLOC_INLINE void
small_free_list_set_next(rack_t *rack, free_list_t entry, free_list_t next)
{
if (small_is_oob_free_entry(entry)) {
small_oob_free_entry_set_next(entry.oob, next);
} else {
small_inplace_free_entry_set_next(rack, entry.small_inplace, next);
}
}
static MALLOC_INLINE free_list_t
small_free_list_get_next(rack_t *rack, free_list_t ptr)
{
MALLOC_ASSERT(ptr.p);
if (small_is_oob_free_entry(ptr)) {
return small_oob_free_entry_get_next(ptr.oob);
} else {
return small_inplace_free_entry_get_next(rack, ptr.small_inplace);
}
}
static MALLOC_INLINE void *
small_free_list_get_ptr(rack_t *rack, free_list_t ptr)
{
if (!ptr.p) {
return NULL;
} else if (small_is_oob_free_entry(ptr)) {
return small_oob_free_entry_get_ptr(ptr.oob);
} else {
return (void *)ptr.p;
}
}
// Returns a free_list_t that is either inline or not based on the
// pointer and msize.
static MALLOC_INLINE free_list_t
small_free_list_from_ptr(rack_t *rack, void *ptr, msize_t msize)
{
MALLOC_ASSERT(msize);
// The default is to put the free_list_t in the memory that
// the pointer leads to.
free_list_t entry;
entry.p = ptr;
// If the pointer is page aligned, and the msize is greater
// than a whole page, then we try and put the entry in
// the out-of-band area instead.
if (small_needs_oob_free_entry(ptr, msize)) {
oob_free_entry_t oobe = small_oob_free_find_empty(ptr, msize);
if (oobe) {
small_oob_free_entry_set_ptr(oobe, ptr);
entry.oob = oobe;
}
}
return entry;
}
static MALLOC_INLINE void
small_free_mark_free(rack_t *rack, free_list_t entry, msize_t msize)
{
// Marks both the start and end block of a free-list entry as free.
void *ptr = small_free_list_get_ptr(rack, entry);
msize_t *meta_headers = SMALL_META_HEADER_FOR_PTR(ptr);
uintptr_t start_index = SMALL_META_INDEX_FOR_PTR(ptr);
uintptr_t end_index = SMALL_META_INDEX_FOR_PTR(ptr + SMALL_BYTES_FOR_MSIZE(msize) - 1);
MALLOC_ASSERT(start_index <= end_index);
small_meta_header_set_is_free(meta_headers, start_index, msize);
small_meta_header_set_is_free(meta_headers, end_index, msize);
}
static MALLOC_INLINE void
small_free_mark_middle(rack_t *rack, free_list_t entry, msize_t msize)
{
// Marks both the start and end block of a free-list entry as "middle" (unfree).
void *ptr = small_free_list_get_ptr(rack, entry);
msize_t *meta_headers = SMALL_META_HEADER_FOR_PTR(ptr);
uintptr_t start_index = SMALL_META_INDEX_FOR_PTR(ptr);
uintptr_t end_index = SMALL_META_INDEX_FOR_PTR(ptr + SMALL_BYTES_FOR_MSIZE(msize) - 1);
MALLOC_ASSERT(start_index <= end_index);
MALLOC_ASSERT((meta_headers[start_index] & ~SMALL_IS_FREE) == msize);
small_meta_header_set_middle(meta_headers, start_index);
small_meta_header_set_middle(meta_headers, end_index);
}
static MALLOC_INLINE void
small_free_mark_unfree(rack_t *rack, free_list_t entry, msize_t msize)
{
// Marks both the start and end block of a free-list entry as not free.
void *ptr = small_free_list_get_ptr(rack, entry);
msize_t *meta_headers = SMALL_META_HEADER_FOR_PTR(ptr);
uintptr_t start_index = SMALL_META_INDEX_FOR_PTR(ptr);
uintptr_t end_index = SMALL_META_INDEX_FOR_PTR(ptr + SMALL_BYTES_FOR_MSIZE(msize) - 1);
MALLOC_ASSERT(start_index <= end_index);
small_meta_header_set_not_free(meta_headers, start_index);
small_meta_header_set_not_free(meta_headers, end_index);
}
static MALLOC_INLINE unsigned int
small_free_list_count(rack_t *rack, free_list_t ptr)
{
unsigned int count = 0;
while (ptr.p) {
count++;
ptr = small_free_list_get_next(rack, ptr);
}
return count;
}
/*
* Adds an item to the proper free list, and also marks the meta-header of the
* block properly.
* Assumes szone has been locked
*/
static free_list_t
small_free_list_add_ptr(rack_t *rack, magazine_t *small_mag_ptr, void *ptr, msize_t msize)
{
grain_t slot = SMALL_FREE_SLOT_FOR_MSIZE(rack, msize);
free_list_t free_head = small_mag_ptr->mag_free_list[slot];
// This will either return the free_list_t for the current pointer, or attempt
// to reserve an OOB entry for us.
free_list_t free_ptr = small_free_list_from_ptr(rack, ptr, msize);
#if DEBUG_MALLOC
if (LOG(szone, ptr)) {
malloc_report(ASL_LEVEL_INFO, "in %s, ptr=%p, msize=%d\n", __FUNCTION__, ptr, msize);
}
if (((uintptr_t)ptr) & (SMALL_QUANTUM - 1)) {
malloc_zone_error(rack->debug_flags, true, "small_free_list_add_ptr: Unaligned ptr %p\n", ptr);
}
#endif
small_free_list_set_previous(rack, free_ptr, (free_list_t){ .p = NULL });
small_free_list_set_next(rack, free_ptr, free_head);
// Set the start and end blocks of the meta header as "free". Marking the last block
// allows coalescing the regions when we free adjacent regions.
small_free_mark_free(rack, free_ptr, msize);
if (small_free_list_get_ptr(rack, free_head)) {
#if DEBUG_MALLOC
if (small_free_list_get_previous(szone, free_head)) {
malloc_zone_error(rack->debug_flags, true, "small_free_list_add_ptr: Internal invariant broken (free_head->previous != NULL)\n"
"ptr=%p slot=%d free_head=%p previous=%p\n", ptr, slot, (void *)free_head, free_head->previous.p);
}
if (!SMALL_PTR_IS_FREE(small_free_list_get_ptr(szone, free_head))) {
malloc_zone_error(rack->debug_flags, true, "small_free_list_add_ptr: Internal invariant broken (free_head is not a free pointer)\n"
"ptr=%p slot=%d free_head=%p\n", ptr, slot, (void *)small_free_list_get_ptr(szone, free_head));
}
#endif
small_free_list_set_previous(rack, free_head, free_ptr);
} else {
BITMAPN_SET(small_mag_ptr->mag_bitmap, slot);
}
small_mag_ptr->mag_free_list[slot] = free_ptr;
return free_ptr;
}
/*
* Removes the item pointed to by ptr in the proper free list.
* Assumes szone has been locked
*/
static void
small_free_list_remove_ptr_no_clear(rack_t *rack, magazine_t *small_mag_ptr, free_list_t entry, msize_t msize)
{
grain_t slot = SMALL_FREE_SLOT_FOR_MSIZE(rack, msize);
free_list_t next, previous;
#if DEBUG_MALLOC
if (LOG(szone, ptr)) {
malloc_report(ASL_LEVEL_INFO, "In %s, ptr=%p, msize=%d\n", __FUNCTION__, ptr, msize);
}
#endif
previous = small_free_list_get_previous(rack, entry);
next = small_free_list_get_next(rack, entry);
if (!small_free_list_get_ptr(rack, previous)) {
// The block to remove is the head of the free list
#if DEBUG_MALLOC
if (small_mag_ptr->mag_free_list[slot] != ptr) {
malloc_zone_error(rack->debug_flags, true,
"small_free_list_remove_ptr_no_clear: Internal invariant broken (small_mag_ptr->mag_free_list[slot])\n"
"ptr=%p slot=%d msize=%d small_mag_ptr->mag_free_list[slot]=%p\n", ptr, slot, msize,
(void *)small_mag_ptr->mag_free_list[slot]);
return;
}
#endif
small_mag_ptr->mag_free_list[slot] = next;
if (!small_free_list_get_ptr(rack, next)) {
BITMAPN_CLR(small_mag_ptr->mag_bitmap, slot);
}
} else {
// Check that the next pointer of "previous" points to "entry".
free_list_t prev_next = small_free_list_get_next(rack, previous);
if (small_free_list_get_ptr(rack, prev_next) != small_free_list_get_ptr(rack, entry)) {
malloc_zone_error(rack->debug_flags, true,
"small_free_list_remove_ptr_no_clear: Internal invariant broken (next ptr of prev) for %p, prev_next=%p\n",
small_free_list_get_ptr(rack, entry), small_free_list_get_ptr(rack, prev_next));
__builtin_unreachable(); // Always crashes in malloc_zone_error().
}
small_free_list_set_next(rack, previous, next);
}
if (small_free_list_get_ptr(rack, next)) {
// Check that the previous pointer of "next" points to "entry".
free_list_t next_prev = small_free_list_get_previous(rack, next);
if (small_free_list_get_ptr(rack, next_prev) != small_free_list_get_ptr(rack, entry)) {
malloc_zone_error(rack->debug_flags, true,
"small_free_list_remove_ptr_no_clear: Internal invariant broken (prev ptr of next) for %p, next_prev=%p\n",
small_free_list_get_ptr(rack, entry), small_free_list_get_ptr(rack, next_prev));
__builtin_unreachable(); // Always crashes in malloc_zone_error().
}
small_free_list_set_previous(rack, next, previous);
}
if (small_is_oob_free_entry(entry)) {
small_oob_free_entry_set_free(entry.oob);
}
}
static void
small_free_list_remove_ptr(rack_t *rack, magazine_t *small_mag_ptr, free_list_t entry, msize_t msize)
{
// In the general case we want to ensure we marked these entries as "middle"
// while we are in this function. However, when we're moving free list entries
// from/to the recirc depot we rely on the metadata bits being intact to
// reconstruct the free list. In that case we have to be able to skip this
// metadata manipulation.
small_free_mark_middle(rack, entry, msize);
small_free_list_remove_ptr_no_clear(rack, small_mag_ptr, entry, msize);
}
// Find a free list entry by its pointer address. This should only really be used
// by small_finalize_region, or similar, where the free_list_t entry of a known
// pointer is desired. Otherwise it is cheaper to always pull off the free lists.
static free_list_t
small_free_list_find_by_ptr(rack_t *rack, magazine_t *small_mag_ptr, void *ptr, msize_t msize)
{
if (*SMALL_METADATA_FOR_PTR(ptr) == (SMALL_IS_FREE | msize)) {
// If the block is marked free, and of size `msize`, then we first must check
// if the alignment+size is such that we could have use an OOB-entry.
if (small_needs_oob_free_entry(ptr, msize)) {
// Scan the OOB entries looking for this address.
small_region_t region = SMALL_REGION_FOR_PTR(ptr);
for (int i=0; ismall_oob_free_entries[i].ptr) {
continue;
}
if (small_oob_free_entry_get_ptr(®ion->small_oob_free_entries[i]) == ptr) {
return (free_list_t){ .oob = ®ion->small_oob_free_entries[i] };
}
}
}
// Otherwise, the freed pointer will be in place.
return (free_list_t){ .p = ptr };
}
malloc_zone_error(rack->debug_flags, true,
"small_free_list_find_by_ptr: ptr is not free (ptr metadata !SMALL_IS_FREE), "
"ptr=%p msize=%d metadata=0x%x\n", ptr, msize, *SMALL_METADATA_FOR_PTR(ptr));
__builtin_trap();
}
void
small_finalize_region(rack_t *rack, magazine_t *small_mag_ptr)
{
void *last_block, *previous_block;
msize_t last_msize, previous_msize, last_index;
free_list_t previous;
// It is possible that the block prior to the last block in the region has
// been free'd, but was not coalesced with the free bytes at the end of the
// block, since we treat the bytes at the end of the region as "in use" in
// the meta headers. Attempt to coalesce the last block with the previous
// block, so we don't violate the "no consecutive free blocks" invariant.
//
// FIXME: If we could calculate the previous small free size in the same
// manner as tiny_previous_preceding_free, it would eliminate the
// index & previous msize checks, which are a guard against reading
// bogus data out of in-use or written-on-freed memory.
//
// FIXME: Need to investigate how much work would be required to increase
// 'mag_bytes_free_at_end' when freeing the preceding block, rather
// than performing this workaround.
//
if (small_mag_ptr->mag_bytes_free_at_end) {
last_block = SMALL_REGION_END(small_mag_ptr->mag_last_region) - small_mag_ptr->mag_bytes_free_at_end;
last_msize = SMALL_MSIZE_FOR_BYTES(small_mag_ptr->mag_bytes_free_at_end);
last_index = SMALL_META_INDEX_FOR_PTR(last_block);
previous_msize = SMALL_PREVIOUS_MSIZE(last_block);
if (last_index && (previous_msize <= last_index)) {
previous_block = (void *)((uintptr_t)last_block - SMALL_BYTES_FOR_MSIZE(previous_msize));
if (SMALL_PTR_IS_FREE(previous_block)) {
previous = small_free_list_find_by_ptr(rack, small_mag_ptr, previous_block, previous_msize);
small_free_list_remove_ptr(rack, small_mag_ptr, previous, previous_msize);
last_block = previous_block;
last_msize += previous_msize;
}
}
// splice last_block into the free list
small_free_list_add_ptr(rack, small_mag_ptr, last_block, last_msize);
small_mag_ptr->mag_bytes_free_at_end = 0;
}
#if CONFIG_ASLR_INTERNAL
free_list_t next;
if (small_mag_ptr->mag_bytes_free_at_start) {
last_block = SMALL_REGION_ADDRESS(small_mag_ptr->mag_last_region);
last_msize = SMALL_MSIZE_FOR_BYTES(small_mag_ptr->mag_bytes_free_at_start);
void *next_block = (void *)((uintptr_t)last_block + small_mag_ptr->mag_bytes_free_at_start);
if (SMALL_PTR_IS_FREE(next_block)) {
msize_t next_msize = SMALL_PTR_SIZE(next_block);
next = small_free_list_find_by_ptr(rack, small_mag_ptr, next_block, next_msize);
small_free_list_remove_ptr(rack, small_mag_ptr, next, next_msize);
last_msize += next_msize;
}
// splice last_block into the free list
small_free_list_add_ptr(rack, small_mag_ptr, last_block, last_msize);
small_mag_ptr->mag_bytes_free_at_start = 0;
}
#endif
// TODO: Will we ever need to coalesce the blocks at the beginning and end when we finalize?
small_mag_ptr->mag_last_region = NULL;
}
int
small_free_detach_region(rack_t *rack, magazine_t *small_mag_ptr, region_t r)
{
unsigned char *ptr = SMALL_REGION_ADDRESS(r);
msize_t *meta_headers = SMALL_META_HEADER_FOR_PTR(ptr);
uintptr_t start = (uintptr_t)SMALL_REGION_ADDRESS(r);
uintptr_t current = start;
uintptr_t limit = (uintptr_t)SMALL_REGION_END(r);
int total_alloc = 0;
while (current < limit) {
unsigned index = SMALL_META_INDEX_FOR_PTR(current);
msize_t msize_and_free = meta_headers[index];
boolean_t is_free = msize_and_free & SMALL_IS_FREE;
msize_t msize = msize_and_free & ~SMALL_IS_FREE;
if (!msize) {
#if DEBUG_MALLOC
boolean_t is_free = msize_and_free & SMALL_IS_FREE;
malloc_report(ASL_LEVEL_ERR, "*** small_free_detach_region error with %p: msize=%d is_free=%d\n", (void *)current, msize, is_free);
#endif
break;
}
if (is_free) {
free_list_t entry = small_free_list_find_by_ptr(rack, small_mag_ptr, (void *)current, msize);
small_free_list_remove_ptr_no_clear(rack, small_mag_ptr, entry, msize);
} else {
total_alloc++;
}
current += SMALL_BYTES_FOR_MSIZE(msize);
}
return total_alloc;
}
size_t
small_free_reattach_region(rack_t *rack, magazine_t *small_mag_ptr, region_t r)
{
unsigned char *ptr = SMALL_REGION_ADDRESS(r);
msize_t *meta_headers = SMALL_META_HEADER_FOR_PTR(ptr);
uintptr_t start = (uintptr_t)SMALL_REGION_ADDRESS(r);
uintptr_t current = start;
uintptr_t limit = (uintptr_t)SMALL_REGION_END(r);
size_t total_alloc = 0;
while (current < limit) {
unsigned index = SMALL_META_INDEX_FOR_PTR(current);
msize_t msize_and_free = meta_headers[index];
boolean_t is_free = msize_and_free & SMALL_IS_FREE;
msize_t msize = msize_and_free & ~SMALL_IS_FREE;
if (!msize) {
#if DEBUG_MALLOC
malloc_report(ASL_LEVEL_ERR, "*** small_free_reattach_region error with %p: msize=%d is_free=%d\n", (void *)current, msize, is_free);
#endif
break;
}
if (is_free) {
small_free_list_add_ptr(rack, small_mag_ptr, (void *)current, msize);
} else {
total_alloc += SMALL_BYTES_FOR_MSIZE(msize);
}
current += SMALL_BYTES_FOR_MSIZE(msize);
}
return total_alloc;
}
typedef struct {
uint16_t pnum, size;
} small_pg_pair_t;
void
small_free_scan_madvise_free(rack_t *rack, magazine_t *depot_ptr, region_t r)
{
uintptr_t start = (uintptr_t)SMALL_REGION_ADDRESS(r);
uintptr_t current = start;
uintptr_t limit = (uintptr_t)SMALL_REGION_END(r);
msize_t *meta_headers = SMALL_META_HEADER_FOR_PTR(start);
small_pg_pair_t advisory[((SMALL_REGION_PAYLOAD_BYTES + vm_kernel_page_size - 1) >> vm_kernel_page_shift) >>
1]; // 4096bytes stack allocated
int advisories = 0;
// Scan the metadata identifying blocks which span one or more pages. Mark the pages MADV_FREE taking care to preserve free list
// management data.
while (current < limit) {
unsigned index = SMALL_META_INDEX_FOR_PTR(current);
msize_t msize_and_free = meta_headers[index];
boolean_t is_free = msize_and_free & SMALL_IS_FREE;
msize_t msize = msize_and_free & ~SMALL_IS_FREE;
if (is_free && !msize && (current == start)) {
#if DEBUG_MALLOC
// first block is all free
malloc_report(ASL_LEVEL_ERR, "*** small_free_scan_madvise_free first block is all free! %p: msize=%d is_free=%d\n", (void *)current,
msize, is_free);
#endif
uintptr_t pgLo = round_page_kernel(start + sizeof(free_list_t) + sizeof(msize_t));
uintptr_t pgHi = trunc_page_kernel(start + SMALL_REGION_SIZE - sizeof(msize_t));
if (pgLo < pgHi) {
advisory[advisories].pnum = (pgLo - start) >> vm_kernel_page_shift;
advisory[advisories].size = (pgHi - pgLo) >> vm_kernel_page_shift;
advisories++;
}
break;
}
if (!msize) {
#if DEBUG_MALLOC
malloc_report(ASL_LEVEL_ERR,
"*** small_free_scan_madvise_free error with %p: msize=%d is_free=%d\n", (void *)current, msize, is_free);
#endif
break;
}
if (is_free) {
uintptr_t pgLo = round_page_kernel(current + sizeof(free_list_t) + sizeof(msize_t));
uintptr_t pgHi = trunc_page_kernel(current + SMALL_BYTES_FOR_MSIZE(msize) - sizeof(msize_t));
if (pgLo < pgHi) {
advisory[advisories].pnum = (pgLo - start) >> vm_kernel_page_shift;
advisory[advisories].size = (pgHi - pgLo) >> vm_kernel_page_shift;
advisories++;
}
}
current += SMALL_BYTES_FOR_MSIZE(msize);
}
if (advisories > 0) {
int i;
OSAtomicIncrement32Barrier(&(REGION_TRAILER_FOR_SMALL_REGION(r)->pinned_to_depot));
SZONE_MAGAZINE_PTR_UNLOCK(depot_ptr);
for (i = 0; i < advisories; ++i) {
uintptr_t addr = (advisory[i].pnum << vm_page_quanta_shift) + start;
size_t size = advisory[i].size << vm_page_quanta_shift;
mvm_madvise_free(rack, r, addr, addr + size, NULL, rack->debug_flags & MALLOC_DO_SCRIBBLE);
}
SZONE_MAGAZINE_PTR_LOCK(depot_ptr);
OSAtomicDecrement32Barrier(&(REGION_TRAILER_FOR_SMALL_REGION(r)->pinned_to_depot));
}
}
static region_t
small_find_msize_region(rack_t *rack, magazine_t *small_mag_ptr, mag_index_t mag_index, msize_t msize)
{
void *ptr;
grain_t slot = SMALL_FREE_SLOT_FOR_MSIZE(rack, msize);
free_list_t *free_list = small_mag_ptr->mag_free_list;
free_list_t *the_slot = free_list + slot;
free_list_t *limit;
unsigned bitmap;
// Assumes we've locked the magazine
CHECK_MAGAZINE_PTR_LOCKED(szone, small_mag_ptr, __PRETTY_FUNCTION__);
// Look for an exact match by checking the freelist for this msize.
ptr = small_free_list_get_ptr(rack, *the_slot);
if (ptr) {
return SMALL_REGION_FOR_PTR(ptr);
}
// Mask off the bits representing slots holding free blocks smaller than
// the size we need.
if (SMALL_FREELIST_BITMAP_WORDS(rack) > 1) {
// BITMAPN_CTZ implementation
unsigned idx = slot >> 5;
bitmap = 0;
unsigned mask = ~((1 << (slot & 31)) - 1);
for (; idx < SMALL_FREELIST_BITMAP_WORDS(rack); ++idx) {
bitmap = small_mag_ptr->mag_bitmap[idx] & mask;
if (bitmap != 0) {
break;
}
mask = ~0U;
}
// Check for fallthrough: No bits set in bitmap
if ((bitmap == 0) && (idx == SMALL_FREELIST_BITMAP_WORDS(rack))) {
return NULL;
}
// Start looking at the first set bit, plus 32 bits for every word of
// zeroes or entries that were too small.
slot = BITMAP32_CTZ((&bitmap)) + (idx * 32);
} else {
bitmap = small_mag_ptr->mag_bitmap[0] & ~((1 << slot) - 1);
if (!bitmap) {
return NULL;
}
slot = BITMAP32_CTZ((&bitmap));
}
limit = free_list + SMALL_FREE_SLOT_COUNT(rack) - 1;
free_list += slot;
if (free_list < limit) {
ptr = small_free_list_get_ptr(rack, *free_list);
if (ptr) {
return SMALL_REGION_FOR_PTR(ptr);
} else {
/* Shouldn't happen. Fall through to look at last slot. */
#if DEBUG_MALLOC
malloc_report(ASL_LEVEL_ERR, "in small_malloc_from_free_list(), mag_bitmap out of sync, slot=%d\n", slot);
#endif
}
}
// We are now looking at the last slot, which contains blocks equal to, or
// due to coalescing of free blocks, larger than (num_small_slots - 1) * (small quantum size).
ptr = small_free_list_get_ptr(rack, *limit);
if (ptr) {
return SMALL_REGION_FOR_PTR(ptr);
}
return NULL;
}
static boolean_t
small_get_region_from_depot(rack_t *rack, magazine_t *small_mag_ptr, mag_index_t mag_index, msize_t msize)
{
magazine_t *depot_ptr = &(rack->magazines[DEPOT_MAGAZINE_INDEX]);
/* FIXME: Would Uniprocessor benefit from recirc and MADV_FREE? */
if (rack->num_magazines == 1) { // Uniprocessor, single magazine, so no recirculation necessary
return 0;
}
#if DEBUG_MALLOC
if (DEPOT_MAGAZINE_INDEX == mag_index) {
malloc_zone_error(rack->debug_flags, true, "small_get_region_from_depot called for magazine index -1\n", NULL, NULL);
return 0;
}
#endif
SZONE_MAGAZINE_PTR_LOCK(depot_ptr);
// Appropriate a Depot'd region that can satisfy requested msize.
region_trailer_t *node;
region_t sparse_region;
while (1) {
sparse_region = small_find_msize_region(rack, depot_ptr, DEPOT_MAGAZINE_INDEX, msize);
if (NULL == sparse_region) { // Depot empty?
SZONE_MAGAZINE_PTR_UNLOCK(depot_ptr);
return 0;
}
node = REGION_TRAILER_FOR_SMALL_REGION(sparse_region);
if (0 >= node->pinned_to_depot) {
break;
}
SZONE_MAGAZINE_PTR_UNLOCK(depot_ptr);
yield();
SZONE_MAGAZINE_PTR_LOCK(depot_ptr);
}
// disconnect node from Depot
recirc_list_extract(rack, depot_ptr, node);
// Iterate the region pulling its free entries off the (locked) Depot's free list
int objects_in_use = small_free_detach_region(rack, depot_ptr, sparse_region);
// Transfer ownership of the region
MAGAZINE_INDEX_FOR_SMALL_REGION(sparse_region) = mag_index;
node->pinned_to_depot = 0;
// Iterate the region putting its free entries on its new (locked) magazine's free list
size_t bytes_inplay = small_free_reattach_region(rack, small_mag_ptr, sparse_region);
depot_ptr->mag_num_bytes_in_objects -= bytes_inplay;
depot_ptr->num_bytes_in_magazine -= SMALL_REGION_PAYLOAD_BYTES;
depot_ptr->mag_num_objects -= objects_in_use;
small_mag_ptr->mag_num_bytes_in_objects += bytes_inplay;
small_mag_ptr->num_bytes_in_magazine += SMALL_REGION_PAYLOAD_BYTES;
small_mag_ptr->mag_num_objects += objects_in_use;
// connect to magazine as first node
recirc_list_splice_first(rack, small_mag_ptr, node);
SZONE_MAGAZINE_PTR_UNLOCK(depot_ptr);
MAGMALLOC_DEPOTREGION(SMALL_SZONE_FROM_RACK(rack), (int)mag_index, (void *)sparse_region, SMALL_REGION_SIZE,
(int)BYTES_USED_FOR_SMALL_REGION(sparse_region)); // DTrace USDT Probe
return 1;
}
#if CONFIG_AGGRESSIVE_MADVISE || CONFIG_RECIRC_DEPOT
static MALLOC_INLINE void
small_madvise_free_range_no_lock(rack_t *rack,
magazine_t *small_mag_ptr,
region_t region,
free_list_t freee,
msize_t fmsize,
void *headptr,
size_t headsize)
{
void *ptr = small_free_list_get_ptr(rack, freee);
region_trailer_t *node = REGION_TRAILER_FOR_SMALL_REGION(region);
// Lock on small_magazines[mag_index] is already held here.
// Calculate the first page in the coalesced block that would be safe to mark MADV_FREE
size_t free_header_size = sizeof(free_list_t) + sizeof(msize_t);
// If the free_list_t entry is out-of-line then we don't need to reserve any space
// at the start of the region.
if (small_is_oob_free_entry(freee)) {
free_header_size = 0;
}
uintptr_t safe_ptr = (uintptr_t)ptr + free_header_size;
uintptr_t round_safe = round_page_kernel(safe_ptr);
// Calculate the last page in the coalesced block that would be safe to mark MADV_FREE
uintptr_t safe_extent = (uintptr_t)ptr + SMALL_BYTES_FOR_MSIZE(fmsize);
uintptr_t trunc_extent = trunc_page_kernel(safe_extent);
// The newly freed block may complete a span of bytes that cover one or more pages. Mark the span with MADV_FREE.
if (round_safe < trunc_extent) { // Coalesced area covers a page (perhaps many)
// Extend the freed block by the free region header and tail sizes to include pages
// we may have coalesced that no longer host free region tails and headers.
// This may extend over in-use ranges, but the MIN/MAX clamping below will fix that up.
uintptr_t lo = trunc_page_kernel((uintptr_t)headptr);
uintptr_t hi = round_page_kernel((uintptr_t)headptr + headsize + free_header_size);
uintptr_t free_lo = MAX(round_safe, lo);
uintptr_t free_hi = MIN(trunc_extent, hi);
if (free_lo < free_hi) {
// Before unlocking, ensure that the metadata for the freed region
// makes it look not free but includes the length. This ensures that
// any code that inspects the metadata while we are unlocked sees
// a valid state and will not try to use or coalesce freed memory
// into it.
small_free_mark_unfree(rack, freee, fmsize);
small_free_list_remove_ptr_no_clear(rack, small_mag_ptr, freee, fmsize);
OSAtomicIncrement32Barrier(&(node->pinned_to_depot));
SZONE_MAGAZINE_PTR_UNLOCK(small_mag_ptr);
mvm_madvise_free(rack, region, free_lo, free_hi, &rack->last_madvise, rack->debug_flags & MALLOC_DO_SCRIBBLE);
SZONE_MAGAZINE_PTR_LOCK(small_mag_ptr);
OSAtomicDecrement32Barrier(&(node->pinned_to_depot));
small_free_list_add_ptr(rack, small_mag_ptr, ptr, fmsize);
}
}
}
#endif // CONFIG_AGGRESSIVE_MADVISE || CONFIG_RECIRC_DEPOT
#if CONFIG_RECIRC_DEPOT
static region_t
small_free_try_depot_unmap_no_lock(rack_t *rack, magazine_t *depot_ptr, region_trailer_t *node)
{
if (0 < node->bytes_used || 0 < node->pinned_to_depot || depot_ptr->recirculation_entries < recirc_retained_regions) {
return NULL;
}
// disconnect first node from Depot
recirc_list_extract(rack, depot_ptr, node);
// Iterate the region pulling its free entries off the (locked) Depot's free list
region_t sparse_region = SMALL_REGION_FOR_PTR(node);
int objects_in_use = small_free_detach_region(rack, depot_ptr, sparse_region);
if (0 == objects_in_use) {
// Invalidate the hash table entry for this region with HASHRING_REGION_DEALLOCATED.
// Using HASHRING_REGION_DEALLOCATED preserves the collision chain, using HASHRING_OPEN_ENTRY (0) would not.
rgnhdl_t pSlot = hash_lookup_region_no_lock(rack->region_generation->hashed_regions,
rack->region_generation->num_regions_allocated,
rack->region_generation->num_regions_allocated_shift,
sparse_region);
if (NULL == pSlot) {
malloc_zone_error(rack->debug_flags, true, "small_free_try_depot_unmap_no_lock hash lookup failed: %p\n", sparse_region);
return NULL;
}
*pSlot = HASHRING_REGION_DEALLOCATED;
depot_ptr->num_bytes_in_magazine -= SMALL_REGION_PAYLOAD_BYTES;
// Atomically increment num_regions_dealloc
#ifdef __LP64___
OSAtomicIncrement64(&rack->num_regions_dealloc);
#else
OSAtomicIncrement32((int32_t *)&rack->num_regions_dealloc);
#endif
// Caller will transfer ownership of the region back to the OS with no locks held
MAGMALLOC_DEALLOCREGION(SMALL_SZONE_FROM_RACK(rack), (void *)sparse_region, (int)SMALL_REGION_SIZE); // DTrace USDT Probe
return sparse_region;
} else {
malloc_zone_error(rack->debug_flags, true, "small_free_try_depot_unmap_no_lock objects_in_use not zero: %d\n", objects_in_use);
return NULL;
}
}
static boolean_t
small_free_do_recirc_to_depot(rack_t *rack, magazine_t *small_mag_ptr, mag_index_t mag_index)
{
// The entire magazine crossed the "emptiness threshold". Transfer a region
// from this magazine to the Depot. Choose a region that itself has crossed the emptiness threshold (i.e
// is at least fraction "f" empty.) Such a region will be marked "suitable" on the recirculation list.
region_trailer_t *node = small_mag_ptr->firstNode;
while (node && (!node->recirc_suitable || node->pinned_to_depot)) {
node = node->next;
}
if (NULL == node) {
#if DEBUG_MALLOC
malloc_report(ASL_LEVEL_ERR, "*** small_free_do_recirc_to_depot end of list\n");
#endif
return TRUE; // Caller must SZONE_MAGAZINE_PTR_UNLOCK(small_mag_ptr);
}
region_t sparse_region = SMALL_REGION_FOR_PTR(node);
// Deal with unclaimed memory -- mag_bytes_free_at_end or mag_bytes_free_at start
if (sparse_region == small_mag_ptr->mag_last_region &&
(small_mag_ptr->mag_bytes_free_at_end || small_mag_ptr->mag_bytes_free_at_start)) {
small_finalize_region(rack, small_mag_ptr);
}
// disconnect "suitable" node from magazine
recirc_list_extract(rack, small_mag_ptr, node);
// Iterate the region pulling its free entries off its (locked) magazine's free list
int objects_in_use = small_free_detach_region(rack, small_mag_ptr, sparse_region);
magazine_t *depot_ptr = &(rack->magazines[DEPOT_MAGAZINE_INDEX]);
// hand over the region to the (locked) Depot
SZONE_MAGAZINE_PTR_LOCK(depot_ptr);
// this will cause small_free_list_add_ptr called by small_free_reattach_region to use
// the depot as its target magazine, rather than magazine formerly associated with sparse_region
MAGAZINE_INDEX_FOR_SMALL_REGION(sparse_region) = DEPOT_MAGAZINE_INDEX;
node->pinned_to_depot = 0;
// Iterate the region putting its free entries on Depot's free list
size_t bytes_inplay = small_free_reattach_region(rack, depot_ptr, sparse_region);
small_mag_ptr->mag_num_bytes_in_objects -= bytes_inplay;
small_mag_ptr->num_bytes_in_magazine -= SMALL_REGION_PAYLOAD_BYTES;
small_mag_ptr->mag_num_objects -= objects_in_use;
SZONE_MAGAZINE_PTR_UNLOCK(small_mag_ptr); // Unlock the originating magazine
depot_ptr->mag_num_bytes_in_objects += bytes_inplay;
depot_ptr->num_bytes_in_magazine += SMALL_REGION_PAYLOAD_BYTES;
depot_ptr->mag_num_objects += objects_in_use;
// connect to Depot as last node
recirc_list_splice_last(rack, depot_ptr, node);
MAGMALLOC_RECIRCREGION(SMALL_SZONE_FROM_RACK(rack), (int)mag_index, (void *)sparse_region, SMALL_REGION_SIZE,
(int)BYTES_USED_FOR_SMALL_REGION(sparse_region)); // DTrace USDT Probe
#if !CONFIG_AGGRESSIVE_MADVISE
// Mark free'd dirty pages with MADV_FREE to reduce memory pressure
small_free_scan_madvise_free(rack, depot_ptr, sparse_region);
#endif
// If the region is entirely empty vm_deallocate() it outside the depot lock
region_t r_dealloc = small_free_try_depot_unmap_no_lock(rack, depot_ptr, node);
SZONE_MAGAZINE_PTR_UNLOCK(depot_ptr);
if (r_dealloc) {
mvm_deallocate_pages(r_dealloc, SMALL_REGION_SIZE, 0);
}
return FALSE; // Caller need not unlock the originating magazine
}
static MALLOC_INLINE boolean_t
small_free_try_recirc_to_depot(rack_t *rack,
magazine_t *small_mag_ptr,
mag_index_t mag_index,
region_t region,
free_list_t freee,
msize_t msize,
void *headptr,
size_t headsize)
{
region_trailer_t *node = REGION_TRAILER_FOR_SMALL_REGION(region);
size_t bytes_used = node->bytes_used;
/* FIXME: Would Uniprocessor benefit from recirc and MADV_FREE? */
if (rack->num_magazines == 1) { // Uniprocessor, single magazine, so no recirculation necessary
/* NOTHING */
return TRUE; // Caller must do SZONE_MAGAZINE_PTR_UNLOCK(tiny_mag_ptr)
} else if (DEPOT_MAGAZINE_INDEX != mag_index) {
// Emptiness discriminant
if (bytes_used < DENSITY_THRESHOLD(SMALL_REGION_PAYLOAD_BYTES)) {
/* Region has crossed threshold from density to sparsity. Mark it "suitable" on the
* recirculation candidates list. */
node->recirc_suitable = TRUE;
} else {
/* After this free, we've found the region is still dense, so it must have been even more so before
* the free. That implies the region is already correctly marked. Do nothing. */
}
// Has the entire magazine crossed the "emptiness threshold"? If so, transfer a region
// from this magazine to the Depot. Choose a region that itself has crossed the emptiness threshold (i.e
// is at least fraction "f" empty.) Such a region will be marked "suitable" on the recirculation list.
size_t a = small_mag_ptr->num_bytes_in_magazine; // Total bytes allocated to this magazine
size_t u = small_mag_ptr->mag_num_bytes_in_objects; // In use (malloc'd) from this magaqzine
if (a - u > ((3 * SMALL_REGION_PAYLOAD_BYTES) / 2) && u < DENSITY_THRESHOLD(a)) {
return small_free_do_recirc_to_depot(rack, small_mag_ptr, mag_index);
}
} else {
#if !CONFIG_AGGRESSIVE_MADVISE
// We are free'ing into the depot, so madvise as we do so unless we were madvising every incoming
// allocation anyway.
small_madvise_free_range_no_lock(rack, small_mag_ptr, region, freee, msize, headptr, headsize);
#endif
if (0 < bytes_used || 0 < node->pinned_to_depot) {
/* Depot'd region is still live. Leave it in place on the Depot's recirculation list
* so as to avoid thrashing between the Depot's free list and a magazines's free list
* with detach_region/reattach_region */
} else {
/* Depot'd region is just now empty. Consider return to OS. */
region_t r_dealloc = small_free_try_depot_unmap_no_lock(rack, small_mag_ptr, node);
SZONE_MAGAZINE_PTR_UNLOCK(small_mag_ptr);
if (r_dealloc) {
mvm_deallocate_pages(r_dealloc, SMALL_REGION_SIZE, 0);
}
return FALSE; // Caller need not unlock
}
}
return TRUE; // Caller must do SZONE_MAGAZINE_PTR_UNLOCK(tiny_mag_ptr)
}
#endif // CONFIG_RECIRC_DEPOT
static MALLOC_INLINE boolean_t
small_free_no_lock(rack_t *rack, magazine_t *small_mag_ptr, mag_index_t mag_index, region_t region, void *ptr, msize_t msize)
{
msize_t *meta_headers = SMALL_META_HEADER_FOR_PTR(ptr);
unsigned index = SMALL_META_INDEX_FOR_PTR(ptr);
size_t original_size = SMALL_BYTES_FOR_MSIZE(msize);
unsigned char *next_block = ((unsigned char *)ptr + original_size);
msize_t next_index = index + msize;
MALLOC_TRACE(TRACE_small_free, (uintptr_t)rack, (uintptr_t)small_mag_ptr, (uintptr_t)ptr, SMALL_BYTES_FOR_MSIZE(msize));
#if CONFIG_AGGRESSIVE_MADVISE || CONFIG_RECIRC_DEPOT
void *original_ptr = ptr;
#endif
#if DEBUG_MALLOC
if (LOG(szone, ptr)) {
malloc_report(ASL_LEVEL_ERR, "in small_free_no_lock(), ptr=%p, msize=%d\n", ptr, msize);
}
if (!msize) {
malloc_zone_error(rack->debug_flags, true, "trying to free small block that is too small in small_free_no_lock(), ptr=%p, msize=%d\n",
ptr, msize);
}
#endif
// We try to coalesce this block with the preceeding one
if (index > 0 && (meta_headers[index - 1] & SMALL_IS_FREE)) {
msize_t previous_msize = meta_headers[index - 1] & ~SMALL_IS_FREE;
grain_t previous_index = index - previous_msize;
// Check if the metadata for the start of the block is also free.
if (meta_headers[previous_index] == (previous_msize | SMALL_IS_FREE)) {
void *previous_ptr = (void *)((uintptr_t)ptr - SMALL_BYTES_FOR_MSIZE(previous_msize));
free_list_t previous = small_free_list_find_by_ptr(rack, small_mag_ptr, previous_ptr, previous_msize);
small_free_list_remove_ptr(rack, small_mag_ptr, previous, previous_msize);
ptr = previous_ptr;
small_meta_header_set_middle(meta_headers, index); // This block is now a middle block.
msize += previous_msize;
index -= previous_msize;
} else {
_os_set_crash_log_message("small free list metadata inconsistency (headers[previous] != previous size)");
__builtin_trap();
}
}
// Try to coalesce with this block with the next block
if ((next_block < SMALL_REGION_END(region)) && (meta_headers[next_index] & SMALL_IS_FREE)) {
msize_t next_msize = meta_headers[next_index] & ~SMALL_IS_FREE;
free_list_t next = small_free_list_find_by_ptr(rack, small_mag_ptr, next_block, next_msize);
small_free_list_remove_ptr(rack, small_mag_ptr, next, next_msize);
msize += next_msize;
}
if (rack->debug_flags & MALLOC_DO_SCRIBBLE) {
if (!msize) {
malloc_zone_error(rack->debug_flags, true, "incorrect size information for %p - block header was damaged\n", ptr);
} else {
memset(ptr, SCRABBLE_BYTE, SMALL_BYTES_FOR_MSIZE(msize));
}
}
free_list_t freee = small_free_list_add_ptr(rack, small_mag_ptr, ptr, msize);
// use original_size and not msize to avoid double counting the coalesced blocks
small_mag_ptr->mag_num_bytes_in_objects -= original_size;
small_mag_ptr->mag_num_objects--;
// Update this region's bytes in use count
region_trailer_t *node = REGION_TRAILER_FOR_SMALL_REGION(region);
size_t bytes_used = node->bytes_used - original_size;
node->bytes_used = (unsigned int)bytes_used;
#if CONFIG_AGGRESSIVE_MADVISE
small_madvise_free_range_no_lock(rack, small_mag_ptr, region, freee, msize, original_ptr, original_size);
#endif
// Caller must do SZONE_MAGAZINE_PTR_UNLOCK(tiny_mag_ptr) if this function
// returns TRUE.
boolean_t needs_unlock = TRUE;
#if CONFIG_RECIRC_DEPOT
needs_unlock = small_free_try_recirc_to_depot(rack, small_mag_ptr, mag_index, region, freee, msize, original_ptr, original_size);
#endif
return needs_unlock;
}
// Allocates from the last region or a freshly allocated region
static void *
small_malloc_from_region_no_lock(rack_t *rack,
magazine_t *small_mag_ptr,
mag_index_t mag_index,
msize_t msize,
void *aligned_address)
{
void *ptr;
// Before anything we transform the mag_bytes_free_at_end or mag_bytes_free_at_start - if any - to a regular free block
/* FIXME: last_block needs to be coalesced with previous entry if free, */
if (small_mag_ptr->mag_bytes_free_at_end || small_mag_ptr->mag_bytes_free_at_start) {
small_finalize_region(rack, small_mag_ptr);
}
// Tag the region at "aligned_address" as belonging to us,
// and so put it under the protection of the magazine lock we are holding.
// Do this before advertising "aligned_address" on the hash ring(!)
MAGAZINE_INDEX_FOR_SMALL_REGION(aligned_address) = mag_index;
// Insert the new region into the hash ring
rack_region_insert(rack, (region_t)aligned_address);
small_mag_ptr->mag_last_region = aligned_address;
BYTES_USED_FOR_SMALL_REGION(aligned_address) = SMALL_BYTES_FOR_MSIZE(msize);
#if CONFIG_ASLR_INTERNAL
int offset_msize = malloc_entropy[1] & SMALL_ENTROPY_MASK;
#if DEBUG_MALLOC
if (getenv("MallocASLRForce")) {
offset_msize = strtol(getenv("MallocASLRForce"), NULL, 0) & SMALL_ENTROPY_MASK;
}
if (getenv("MallocASLRPrint")) {
malloc_report(ASL_LEVEL_INFO, "Region: %p offset: %d\n", aligned_address, offset_msize);
}
#endif
#else
int offset_msize = 0;
#endif
ptr = (void *)((uintptr_t)aligned_address + SMALL_BYTES_FOR_MSIZE(offset_msize));
small_meta_header_set_in_use(SMALL_META_HEADER_FOR_PTR(ptr), offset_msize, msize);
small_mag_ptr->mag_num_objects++;
small_mag_ptr->mag_num_bytes_in_objects += SMALL_BYTES_FOR_MSIZE(msize);
small_mag_ptr->num_bytes_in_magazine += SMALL_REGION_PAYLOAD_BYTES;
// add a big free block at the end
small_meta_header_set_in_use(SMALL_META_HEADER_FOR_PTR(ptr), offset_msize + msize, NUM_SMALL_BLOCKS - msize - offset_msize);
small_mag_ptr->mag_bytes_free_at_end = SMALL_BYTES_FOR_MSIZE(NUM_SMALL_BLOCKS - msize - offset_msize);
#if CONFIG_ASLR_INTERNAL
// add a big free block at the start
small_mag_ptr->mag_bytes_free_at_start = SMALL_BYTES_FOR_MSIZE(offset_msize);
if (offset_msize) {
small_meta_header_set_in_use(SMALL_META_HEADER_FOR_PTR(ptr), 0, offset_msize);
}
#else
small_mag_ptr->mag_bytes_free_at_start = 0;
#endif
// connect to magazine as last node
recirc_list_splice_last(rack, small_mag_ptr, REGION_TRAILER_FOR_SMALL_REGION(aligned_address));
return ptr;
}
void *
small_memalign(szone_t *szone, size_t alignment, size_t size, size_t span)
{
msize_t mspan = SMALL_MSIZE_FOR_BYTES(span + SMALL_QUANTUM - 1);
void *p = small_malloc_should_clear(&szone->small_rack, mspan, 0);
if (NULL == p) {
return NULL;
}
size_t offset = ((uintptr_t)p) & (alignment - 1); // p % alignment
size_t pad = (0 == offset) ? 0 : alignment - offset; // p + pad achieves desired alignment
msize_t msize = SMALL_MSIZE_FOR_BYTES(size + SMALL_QUANTUM - 1);
msize_t mpad = SMALL_MSIZE_FOR_BYTES(pad + SMALL_QUANTUM - 1);
msize_t mwaste = mspan - msize - mpad; // excess blocks
if (mpad > 0) {
void *q = (void *)(((uintptr_t)p) + pad);
// Mark q as block header and in-use, thus creating two blocks.
magazine_t *small_mag_ptr = mag_lock_zine_for_region_trailer(szone->small_rack.magazines,
REGION_TRAILER_FOR_SMALL_REGION(SMALL_REGION_FOR_PTR(p)),
MAGAZINE_INDEX_FOR_SMALL_REGION(SMALL_REGION_FOR_PTR(p)));
small_meta_header_set_in_use(SMALL_META_HEADER_FOR_PTR(p), SMALL_META_INDEX_FOR_PTR(p), mpad);
small_meta_header_set_in_use(SMALL_META_HEADER_FOR_PTR(q), SMALL_META_INDEX_FOR_PTR(q), msize + mwaste);
small_mag_ptr->mag_num_objects++;
SZONE_MAGAZINE_PTR_UNLOCK(small_mag_ptr);
// Give up mpad blocks beginning at p to the small free list
free_small(&szone->small_rack, p, SMALL_REGION_FOR_PTR(p), SMALL_BYTES_FOR_MSIZE(mpad));
p = q; // advance p to the desired alignment
}
if (mwaste > 0) {
void *q = (void *)(((uintptr_t)p) + SMALL_BYTES_FOR_MSIZE(msize));
// Mark q as block header and in-use, thus creating two blocks.
magazine_t *small_mag_ptr = mag_lock_zine_for_region_trailer(szone->small_rack.magazines,
REGION_TRAILER_FOR_SMALL_REGION(SMALL_REGION_FOR_PTR(p)),
MAGAZINE_INDEX_FOR_SMALL_REGION(SMALL_REGION_FOR_PTR(p)));
small_meta_header_set_in_use(SMALL_META_HEADER_FOR_PTR(p), SMALL_META_INDEX_FOR_PTR(p), msize);
small_meta_header_set_in_use(SMALL_META_HEADER_FOR_PTR(q), SMALL_META_INDEX_FOR_PTR(q), mwaste);
small_mag_ptr->mag_num_objects++;
SZONE_MAGAZINE_PTR_UNLOCK(small_mag_ptr);
// Give up mwaste blocks beginning at q to the small free list
free_small(&szone->small_rack, q, SMALL_REGION_FOR_PTR(q), SMALL_BYTES_FOR_MSIZE(mwaste));
}
return p; // p has the desired size and alignment, and can later be free()'d
}
boolean_t
small_claimed_address(rack_t *rack, void *ptr)
{
region_t r = small_region_for_ptr_no_lock(rack, ptr);
return r && ptr < (void *)SMALL_REGION_END(r);
}
void *
small_try_shrink_in_place(rack_t *rack, void *ptr, size_t old_size, size_t new_good_size)
{
msize_t new_msize = SMALL_MSIZE_FOR_BYTES(new_good_size);
msize_t mshrinkage = SMALL_MSIZE_FOR_BYTES(old_size) - new_msize;
if (mshrinkage) {
void *q = (void *)((uintptr_t)ptr + SMALL_BYTES_FOR_MSIZE(new_msize));
magazine_t *small_mag_ptr = mag_lock_zine_for_region_trailer(rack->magazines,
REGION_TRAILER_FOR_SMALL_REGION(SMALL_REGION_FOR_PTR(ptr)),
MAGAZINE_INDEX_FOR_SMALL_REGION(SMALL_REGION_FOR_PTR(ptr)));
// Mark q as block header and in-use, thus creating two blocks.
small_meta_header_set_in_use(SMALL_META_HEADER_FOR_PTR(ptr), SMALL_META_INDEX_FOR_PTR(ptr), new_msize);
small_meta_header_set_in_use(SMALL_META_HEADER_FOR_PTR(q), SMALL_META_INDEX_FOR_PTR(q), mshrinkage);
small_mag_ptr->mag_num_objects++;
SZONE_MAGAZINE_PTR_UNLOCK(small_mag_ptr);
free_small(rack, q, SMALL_REGION_FOR_PTR(q), 0);
}
return ptr;
}
boolean_t
small_try_realloc_in_place(rack_t *rack, void *ptr, size_t old_size, size_t new_size)
{
// returns 1 on success
msize_t *meta_headers = SMALL_META_HEADER_FOR_PTR(ptr);
unsigned index;
msize_t old_msize, new_msize;
unsigned next_index;
void *next_block;
msize_t next_msize_and_free;
boolean_t is_free;
msize_t next_msize, leftover_msize;
void *leftover;
index = SMALL_META_INDEX_FOR_PTR(ptr);
old_msize = SMALL_MSIZE_FOR_BYTES(old_size);
new_msize = SMALL_MSIZE_FOR_BYTES(new_size + SMALL_QUANTUM - 1);
next_index = index + old_msize;
if (next_index >= NUM_SMALL_BLOCKS) {
return 0;
}
next_block = (char *)ptr + old_size;
#if DEBUG_MALLOC
if ((uintptr_t)next_block & (SMALL_QUANTUM - 1)) {
malloc_zone_error(rack->debug_flags, true, "internal invariant broken in realloc(next_block) for %p\n", next_block);
}
if (meta_headers[index] != old_msize) {
malloc_report(ASL_LEVEL_ERR, "*** small_try_realloc_in_place incorrect old %d %d\n", meta_headers[index], old_msize);
}
#endif
magazine_t *small_mag_ptr = mag_lock_zine_for_region_trailer(rack->magazines,
REGION_TRAILER_FOR_SMALL_REGION(SMALL_REGION_FOR_PTR(ptr)),
MAGAZINE_INDEX_FOR_SMALL_REGION(SMALL_REGION_FOR_PTR(ptr)));
if (DEPOT_MAGAZINE_INDEX == MAGAZINE_INDEX_FOR_SMALL_REGION(SMALL_REGION_FOR_PTR(ptr))) {
SZONE_MAGAZINE_PTR_UNLOCK(small_mag_ptr);
return 0;
}
msize_t coalesced_msize = new_msize - old_msize;
#if CONFIG_SMALL_CACHE
void *last_free_ptr = small_mag_ptr->mag_last_free;
msize_t last_free_msize = small_mag_ptr->mag_last_free_msize;
if (last_free_ptr == next_block && old_msize + last_free_msize >= new_msize) {
/*
* There is a block in mag_last_free and it's immediately after
* this block and it's large enough. We can use some or all of it.
*/
leftover_msize = last_free_msize - coalesced_msize;
if (leftover_msize) {
small_mag_ptr->mag_last_free_msize -= coalesced_msize;
small_mag_ptr->mag_last_free += new_size - old_size;
// The block in mag_last_free is still marked as header and in-use, so copy that
// state to the block that remains. The state for the block that we're going to
// use is adjusted by the small_meta_header_set_middle() call below.
small_meta_header_set_in_use(meta_headers, index + new_msize, leftover_msize);
} else {
// Using the whole block.
small_mag_ptr->mag_last_free = NULL;
small_mag_ptr->mag_last_free_msize = 0;
small_mag_ptr->mag_last_free_rgn = NULL;
}
small_meta_header_set_in_use(meta_headers, index, new_msize);
small_meta_header_set_middle(meta_headers, next_index);
} else {
#endif // CONFIG_SMALL_CACHE
/*
* Try to expand into unused space immediately after this block.
*/
msize_t unused_msize = SMALL_MSIZE_FOR_BYTES(small_mag_ptr->mag_bytes_free_at_end);
void *unused_start = SMALL_REGION_END(SMALL_REGION_FOR_PTR(ptr)) - small_mag_ptr->mag_bytes_free_at_end;
if (small_mag_ptr->mag_last_region == SMALL_REGION_FOR_PTR(ptr)
&& coalesced_msize < unused_msize && unused_start == ptr + old_size) {
// Extend the in-use for this block to the new size
small_meta_header_set_in_use(meta_headers, index, new_msize);
// Clear the in-use size for the start of the area we extended into
small_meta_header_set_middle(meta_headers, next_index);
// Reduce mag_bytes_free_at_end and update its in-use size.
small_mag_ptr->mag_bytes_free_at_end -= SMALL_BYTES_FOR_MSIZE(coalesced_msize);
small_meta_header_set_in_use(meta_headers, index + new_msize, SMALL_MSIZE_FOR_BYTES(small_mag_ptr->mag_bytes_free_at_end));
} else {
/*
* Look for a free block immediately afterwards. If it's large enough, we can consume (part of)
* it.
*/
next_msize_and_free = meta_headers[next_index];
is_free = next_msize_and_free & SMALL_IS_FREE;
if (!is_free) {
SZONE_MAGAZINE_PTR_UNLOCK(small_mag_ptr);
return 0; // next_block is in use;
}
next_msize = next_msize_and_free & ~SMALL_IS_FREE;
if (old_msize + next_msize < new_msize) {
SZONE_MAGAZINE_PTR_UNLOCK(small_mag_ptr);
return 0; // even with next block, not enough
}
// The following block is big enough; pull it from its freelist and chop off enough to satisfy
// our needs.
free_list_t freee = small_free_list_find_by_ptr(rack, small_mag_ptr, next_block, next_msize);
small_free_list_remove_ptr(rack, small_mag_ptr, freee, next_msize);
small_meta_header_set_middle(meta_headers, next_index);
leftover_msize = old_msize + next_msize - new_msize;
if (leftover_msize) {
/* there's some left, so put the remainder back */
leftover = (unsigned char *)ptr + SMALL_BYTES_FOR_MSIZE(new_msize);
small_free_list_add_ptr(rack, small_mag_ptr, leftover, leftover_msize);
}
small_meta_header_set_in_use(meta_headers, index, new_msize);
}
#if CONFIG_SMALL_CACHE
}
#endif // CONFIG_SMALL_CACHE
#if DEBUG_MALLOC
if (SMALL_BYTES_FOR_MSIZE(new_msize) > szone->large_threshold) {
malloc_report(ASL_LEVEL_ERR, "*** realloc in place for %p exceeded msize=%d\n", new_msize);
}
if (LOG(szone, ptr)) {
malloc_report(ASL_LEVEL_INFO, "in small_try_realloc_in_place(), ptr=%p, msize=%d\n", ptr, *SMALL_METADATA_FOR_PTR(ptr));
}
#endif
small_mag_ptr->mag_num_bytes_in_objects += SMALL_BYTES_FOR_MSIZE(new_msize - old_msize);
// Update this region's bytes in use count
region_trailer_t *node = REGION_TRAILER_FOR_SMALL_REGION(SMALL_REGION_FOR_PTR(ptr));
size_t bytes_used = node->bytes_used + SMALL_BYTES_FOR_MSIZE(new_msize - old_msize);
node->bytes_used = (unsigned int)bytes_used;
// Emptiness discriminant
if (bytes_used < DENSITY_THRESHOLD(SMALL_REGION_PAYLOAD_BYTES)) {
/* After this reallocation the region is still sparse, so it must have been even more so before
* the reallocation. That implies the region is already correctly marked. Do nothing. */
} else {
/* Region has crossed threshold from sparsity to density. Mark it not "suitable" on the
* recirculation candidates list. */
node->recirc_suitable = FALSE;
}
SZONE_MAGAZINE_PTR_UNLOCK(small_mag_ptr);
CHECK(szone, __PRETTY_FUNCTION__);
return 1;
}
static char *small_check_fail_msg = "check: incorrect small region ";
#define SMALL_CHECK_FAIL(fmt, ...) \
malloc_zone_check_fail(small_check_fail_msg, \
"%ld, counter=%d\n" fmt, region_index, counter, __VA_ARGS__);
boolean_t
small_check_region(rack_t *rack, region_t region, size_t region_index,
unsigned counter)
{
unsigned char *ptr = SMALL_REGION_ADDRESS(region);
msize_t *meta_headers = SMALL_META_HEADER_FOR_PTR(ptr);
unsigned char *region_end = SMALL_REGION_END(region);
msize_t prev_free = 0;
unsigned index;
msize_t msize_and_free;
msize_t msize;
free_list_t free_head, previous, next;
msize_t *follower;
mag_index_t mag_index = MAGAZINE_INDEX_FOR_SMALL_REGION(SMALL_REGION_FOR_PTR(ptr));
magazine_t *small_mag_ptr = &(rack->magazines[mag_index]);
// Assumes locked
CHECK_MAGAZINE_PTR_LOCKED(szone, small_mag_ptr, __PRETTY_FUNCTION__);
if (region == small_mag_ptr->mag_last_region) {
ptr += small_mag_ptr->mag_bytes_free_at_start;
region_end -= small_mag_ptr->mag_bytes_free_at_end;
}
while (ptr < region_end) {
index = SMALL_META_INDEX_FOR_PTR(ptr);
msize_and_free = meta_headers[index];
if (!(msize_and_free & SMALL_IS_FREE)) {
// block is in use
msize = msize_and_free;
if (!msize) {
SMALL_CHECK_FAIL("*** invariant broken: null msize ptr=%p num_small_regions=%d end=%p\n", ptr,
(int)rack->num_regions, region_end);
return 0;
}
#if !CONFIG_RELAXED_INVARIANT_CHECKS
if (SMALL_BYTES_FOR_MSIZE(msize) > szone->large_threshold) {
SMALL_CHECK_FAIL("*** invariant broken for %p this small msize=%d - size is too large\n", ptr, msize_and_free);
return 0;
}
#endif // CONFIG_RELAXED_INVARIANT_CHECKS
ptr += SMALL_BYTES_FOR_MSIZE(msize);
prev_free = 0;
} else {
// free pointer
msize = msize_and_free & ~SMALL_IS_FREE;
free_head = (free_list_t){ .p = ptr };
follower = (msize_t *)FOLLOWING_SMALL_PTR(ptr, msize);
if (!msize) {
SMALL_CHECK_FAIL("*** invariant broken for free block %p this msize=%d\n", ptr, msize);
return 0;
}
#if !CONFIG_RELAXED_INVARIANT_CHECKS
if (prev_free) {
SMALL_CHECK_FAIL("*** invariant broken for %p (2 free in a row)\n", ptr);
return 0;
}
#endif
// check for possible OOB entry if needed
if (small_needs_oob_free_entry(ptr, msize)) {
oob_free_entry_t oob = small_oob_free_find_ptr(ptr, msize);
if (oob) {
free_head.oob = oob;
}
}
previous = small_free_list_get_previous(rack, free_head);
next = small_free_list_get_next(rack, free_head);
if (previous.p && !SMALL_PTR_IS_FREE(small_free_list_get_ptr(rack, previous))) {
SMALL_CHECK_FAIL("*** invariant broken for %p (previous %p is not a free pointer)\n", ptr, small_free_list_get_ptr(rack, previous));
return 0;
}
if (next.p && !SMALL_PTR_IS_FREE(small_free_list_get_ptr(rack, next))) {
SMALL_CHECK_FAIL("*** invariant broken for %p (next %p is not a free pointer)\n", ptr, small_free_list_get_ptr(rack, next));
return 0;
}
if (SMALL_PREVIOUS_MSIZE(follower) != msize) {
SMALL_CHECK_FAIL("*** invariant broken for small free %p followed by %p in region [%p-%p] "
"(end marker incorrect) should be %d; in fact %d\n",
ptr, follower, SMALL_REGION_ADDRESS(region), region_end, msize, SMALL_PREVIOUS_MSIZE(follower));
return 0;
}
ptr = (unsigned char *)follower;
prev_free = SMALL_IS_FREE;
}
}
return 1;
}
kern_return_t
small_in_use_enumerator(task_t task,
void *context,
unsigned type_mask,
szone_t *szone,
memory_reader_t reader,
vm_range_recorder_t recorder)
{
size_t num_regions;
size_t index;
region_t *regions;
vm_range_t buffer[MAX_RECORDER_BUFFER];
unsigned count = 0;
kern_return_t err;
region_t region;
vm_range_t range;
vm_range_t admin_range;
vm_range_t ptr_range;
unsigned char *mapped_region;
msize_t *block_header;
unsigned block_index;
unsigned block_limit;
msize_t msize_and_free;
msize_t msize;
magazine_t *small_mag_base = NULL;
region_hash_generation_t *srg_ptr;
err = reader(task, (vm_address_t)szone->small_rack.region_generation, sizeof(region_hash_generation_t), (void **)&srg_ptr);
if (err) {
return err;
}
num_regions = srg_ptr->num_regions_allocated;
err = reader(task, (vm_address_t)srg_ptr->hashed_regions, sizeof(region_t) * num_regions, (void **)®ions);
if (err) {
return err;
}
if (type_mask & MALLOC_PTR_IN_USE_RANGE_TYPE) {
// Map in all active magazines. Do this outside the iteration over regions.
err = reader(task, (vm_address_t)(szone->small_rack.magazines), szone->small_rack.num_magazines * sizeof(magazine_t),
(void **)&small_mag_base);
if (err) {
return err;
}
}
for (index = 0; index < num_regions; ++index) {
region = regions[index];
if (HASHRING_OPEN_ENTRY != region && HASHRING_REGION_DEALLOCATED != region) {
range.address = (vm_address_t)SMALL_REGION_ADDRESS(region);
range.size = SMALL_REGION_SIZE;
if (type_mask & MALLOC_ADMIN_REGION_RANGE_TYPE) {
admin_range.address = range.address + SMALL_METADATA_START;
admin_range.size = SMALL_METADATA_SIZE;
recorder(task, context, MALLOC_ADMIN_REGION_RANGE_TYPE, &admin_range, 1);
}
if (type_mask & (MALLOC_PTR_REGION_RANGE_TYPE | MALLOC_ADMIN_REGION_RANGE_TYPE)) {
ptr_range.address = range.address;
ptr_range.size = NUM_SMALL_BLOCKS * SMALL_QUANTUM;
recorder(task, context, MALLOC_PTR_REGION_RANGE_TYPE, &ptr_range, 1);
}
if (type_mask & MALLOC_PTR_IN_USE_RANGE_TYPE) {
vm_address_t mag_last_free = 0;
msize_t mag_last_free_msize = 0;
err = reader(task, range.address, range.size, (void **)&mapped_region);
if (err) {
return err;
}
mag_index_t mag_index = MAGAZINE_INDEX_FOR_SMALL_REGION(mapped_region);
magazine_t *small_mag_ptr = small_mag_base + mag_index;
if (DEPOT_MAGAZINE_INDEX != mag_index) {
mag_last_free = (uintptr_t)small_mag_ptr->mag_last_free;
mag_last_free_msize = small_mag_ptr->mag_last_free_msize;
} else {
for (mag_index = 0; mag_index < szone->small_rack.num_magazines; mag_index++) {
if ((void *)range.address == (small_mag_base + mag_index)->mag_last_free_rgn) {
mag_last_free = (uintptr_t)(small_mag_base + mag_index)->mag_last_free;
mag_last_free_msize = (small_mag_base + mag_index)->mag_last_free_msize;
}
}
}
block_header = (msize_t *)(mapped_region + SMALL_METADATA_START + sizeof(region_trailer_t));
block_index = 0;
block_limit = NUM_SMALL_BLOCKS;
if (region == small_mag_ptr->mag_last_region) {
block_index += SMALL_MSIZE_FOR_BYTES(small_mag_ptr->mag_bytes_free_at_start);
block_limit -= SMALL_MSIZE_FOR_BYTES(small_mag_ptr->mag_bytes_free_at_end);
}
while (block_index < block_limit) {
msize_and_free = block_header[block_index];
msize = msize_and_free & ~SMALL_IS_FREE;
if (!(msize_and_free & SMALL_IS_FREE) &&
range.address + SMALL_BYTES_FOR_MSIZE(block_index) != mag_last_free) {
// Block in use
buffer[count].address = range.address + SMALL_BYTES_FOR_MSIZE(block_index);
buffer[count].size = SMALL_BYTES_FOR_MSIZE(msize);
count++;
if (count >= MAX_RECORDER_BUFFER) {
recorder(task, context, MALLOC_PTR_IN_USE_RANGE_TYPE, buffer, count);
count = 0;
}
}
if (!msize) {
return KERN_FAILURE; // Somethings amiss. Avoid looping at this block_index.
}
block_index += msize;
}
if (count) {
recorder(task, context, MALLOC_PTR_IN_USE_RANGE_TYPE, buffer, count);
count = 0;
}
}
}
}
return 0;
}
static void *
small_malloc_from_free_list(rack_t *rack, magazine_t *small_mag_ptr, mag_index_t mag_index, msize_t msize)
{
msize_t this_msize;
grain_t slot = SMALL_FREE_SLOT_FOR_MSIZE(rack, msize);
free_list_t *free_list = small_mag_ptr->mag_free_list;
free_list_t *the_slot = free_list + slot;
free_list_t *limit;
unsigned bitmap;
msize_t leftover_msize;
void *leftover_ptr;
void *ptr;
// Assumes we've locked the region
CHECK_MAGAZINE_PTR_LOCKED(szone, small_mag_ptr, __PRETTY_FUNCTION__);
// Look for an exact match by checking the freelist for this msize.
if (small_free_list_get_ptr(rack, *the_slot)) {
ptr = small_free_list_get_ptr(rack, *the_slot);
this_msize = msize;
small_free_list_remove_ptr(rack, small_mag_ptr, *the_slot, msize);
goto return_small_alloc;
}
// Mask off the bits representing slots holding free blocks smaller than
// the size we need. If there are no larger free blocks, try allocating
// from the free space at the end of the small region.
if (SMALL_FREELIST_BITMAP_WORDS(rack) > 1) {
// BITMAPN_CTZ implementation
unsigned idx = slot >> 5;
bitmap = 0;
unsigned mask = ~((1 << (slot & 31)) - 1);
for (; idx < SMALL_FREELIST_BITMAP_WORDS(rack); ++idx) {
bitmap = small_mag_ptr->mag_bitmap[idx] & mask;
if (bitmap != 0) {
break;
}
mask = ~0U;
}
// Check for fallthrough: No bits set in bitmap
if ((bitmap == 0) && (idx == SMALL_FREELIST_BITMAP_WORDS(rack))) {
goto try_small_from_end;
}
// Start looking at the first set bit, plus 32 bits for every word of
// zeroes or entries that were too small.
slot = BITMAP32_CTZ((&bitmap)) + (idx * 32);
} else {
bitmap = small_mag_ptr->mag_bitmap[0] & ~((1 << slot) - 1);
if (!bitmap) {
goto try_small_from_end;
}
slot = BITMAP32_CTZ((&bitmap));
}
// FIXME: Explain use of - 1 here, last slot has special meaning
limit = free_list + SMALL_FREE_SLOT_COUNT(rack) - 1;
free_list += slot;
// Attempt to pull off the free_list slot that we now think is full.
if ((ptr = small_free_list_get_ptr(rack, *free_list))) {
this_msize = SMALL_PTR_SIZE(ptr);
small_free_list_remove_ptr(rack, small_mag_ptr, *free_list, this_msize);
goto add_leftover_and_proceed;
}
#if DEBUG_MALLOC
malloc_report(ASL_LEVEL_ERR, "in small_malloc_from_free_list(), mag_bitmap out of sync, slot=%d\n", slot);
#endif
try_small_from_end:
// Let's see if we can use small_mag_ptr->mag_bytes_free_at_end
if (small_mag_ptr->mag_bytes_free_at_end >= SMALL_BYTES_FOR_MSIZE(msize)) {
ptr = SMALL_REGION_END(small_mag_ptr->mag_last_region) - small_mag_ptr->mag_bytes_free_at_end;
small_mag_ptr->mag_bytes_free_at_end -= SMALL_BYTES_FOR_MSIZE(msize);
if (small_mag_ptr->mag_bytes_free_at_end) {
// let's mark this block as in use to serve as boundary
small_meta_header_set_in_use(SMALL_META_HEADER_FOR_PTR(ptr),
SMALL_META_INDEX_FOR_PTR((unsigned char *)ptr + SMALL_BYTES_FOR_MSIZE(msize)),
SMALL_MSIZE_FOR_BYTES(small_mag_ptr->mag_bytes_free_at_end));
}
this_msize = msize;
goto return_small_alloc;
}
#if CONFIG_ASLR_INTERNAL
// Try from start if nothing left at end
if (small_mag_ptr->mag_bytes_free_at_start >= SMALL_BYTES_FOR_MSIZE(msize)) {
ptr = SMALL_REGION_ADDRESS(small_mag_ptr->mag_last_region) + small_mag_ptr->mag_bytes_free_at_start -
SMALL_BYTES_FOR_MSIZE(msize);
small_mag_ptr->mag_bytes_free_at_start -= SMALL_BYTES_FOR_MSIZE(msize);
if (small_mag_ptr->mag_bytes_free_at_start) {
// let's mark this block as in use to serve as boundary
small_meta_header_set_in_use(
SMALL_META_HEADER_FOR_PTR(ptr), 0, SMALL_MSIZE_FOR_BYTES(small_mag_ptr->mag_bytes_free_at_start));
}
this_msize = msize;
goto return_small_alloc;
}
#endif
return NULL;
add_leftover_and_proceed:
if (this_msize > msize) {
leftover_msize = this_msize - msize;
leftover_ptr = (unsigned char *)ptr + SMALL_BYTES_FOR_MSIZE(msize);
#if DEBUG_MALLOC
if (LOG(szone, ptr)) {
malloc_report(ASL_LEVEL_INFO, "in small_malloc_from_free_list(), adding leftover ptr=%p, this_msize=%d\n", ptr, this_msize);
}
#endif
small_free_list_add_ptr(rack, small_mag_ptr, leftover_ptr, leftover_msize);
this_msize = msize;
}
return_small_alloc:
small_mag_ptr->mag_num_objects++;
small_mag_ptr->mag_num_bytes_in_objects += SMALL_BYTES_FOR_MSIZE(this_msize);
// Update this region's bytes in use count
region_trailer_t *node = REGION_TRAILER_FOR_SMALL_REGION(SMALL_REGION_FOR_PTR(ptr));
size_t bytes_used = node->bytes_used + SMALL_BYTES_FOR_MSIZE(this_msize);
node->bytes_used = (unsigned int)bytes_used;
// Emptiness discriminant
if (bytes_used < DENSITY_THRESHOLD(SMALL_REGION_PAYLOAD_BYTES)) {
/* After this allocation the region is still sparse, so it must have been even more so before
* the allocation. That implies the region is already correctly marked. Do nothing. */
} else {
/* Region has crossed threshold from sparsity to density. Mark in not "suitable" on the
* recirculation candidates list. */
node->recirc_suitable = FALSE;
}
#if DEBUG_MALLOC
if (LOG(szone, ptr)) {
malloc_report(ASL_LEVEL_INFO, "in small_malloc_from_free_list(), ptr=%p, this_msize=%d, msize=%d\n", ptr, this_msize, msize);
}
#endif
small_meta_header_set_in_use(SMALL_META_HEADER_FOR_PTR(ptr), SMALL_META_INDEX_FOR_PTR(ptr), this_msize);
return ptr;
}
void *
small_malloc_should_clear(rack_t *rack, msize_t msize, boolean_t cleared_requested)
{
void *ptr;
mag_index_t mag_index = small_mag_get_thread_index() % rack->num_magazines;
magazine_t *small_mag_ptr = &(rack->magazines[mag_index]);
MALLOC_TRACE(TRACE_small_malloc, (uintptr_t)rack, SMALL_BYTES_FOR_MSIZE(msize), (uintptr_t)small_mag_ptr, cleared_requested);
SZONE_MAGAZINE_PTR_LOCK(small_mag_ptr);
#if CONFIG_SMALL_CACHE
ptr = small_mag_ptr->mag_last_free;
if (small_mag_ptr->mag_last_free_msize == msize) {
// we have a winner
small_mag_ptr->mag_last_free = NULL;
small_mag_ptr->mag_last_free_msize = 0;
small_mag_ptr->mag_last_free_rgn = NULL;
SZONE_MAGAZINE_PTR_UNLOCK(small_mag_ptr);
CHECK(szone, __PRETTY_FUNCTION__);
if (cleared_requested) {
memset(ptr, 0, SMALL_BYTES_FOR_MSIZE(msize));
}
return ptr;
}
#endif /* CONFIG_SMALL_CACHE */
while (1) {
ptr = small_malloc_from_free_list(rack, small_mag_ptr, mag_index, msize);
if (ptr) {
SZONE_MAGAZINE_PTR_UNLOCK(small_mag_ptr);
CHECK(szone, __PRETTY_FUNCTION__);
if (cleared_requested) {
memset(ptr, 0, SMALL_BYTES_FOR_MSIZE(msize));
}
return ptr;
}
if (small_get_region_from_depot(rack, small_mag_ptr, mag_index, msize)) {
ptr = small_malloc_from_free_list(rack, small_mag_ptr, mag_index, msize);
if (ptr) {
SZONE_MAGAZINE_PTR_UNLOCK(small_mag_ptr);
CHECK(szone, __PRETTY_FUNCTION__);
if (cleared_requested) {
memset(ptr, 0, SMALL_BYTES_FOR_MSIZE(msize));
}
return ptr;
}
}
// The magazine is exhausted. A new region (heap) must be allocated to satisfy this call to malloc().
// The allocation, an mmap() system call, will be performed outside the magazine spin locks by the first
// thread that suffers the exhaustion. That thread sets "alloc_underway" and enters a critical section.
// Threads arriving here later are excluded from the critical section, yield the CPU, and then retry the
// allocation. After some time the magazine is resupplied, the original thread leaves with its allocation,
// and retry-ing threads succeed in the code just above.
if (!small_mag_ptr->alloc_underway) {
void *fresh_region;
// time to create a new region (do this outside the magazine lock)
small_mag_ptr->alloc_underway = TRUE;
OSMemoryBarrier();
SZONE_MAGAZINE_PTR_UNLOCK(small_mag_ptr);
fresh_region = mvm_allocate_pages_securely(SMALL_REGION_SIZE, SMALL_BLOCKS_ALIGN, VM_MEMORY_MALLOC_SMALL, rack->debug_flags);
SZONE_MAGAZINE_PTR_LOCK(small_mag_ptr);
// DTrace USDT Probe
MAGMALLOC_ALLOCREGION(SMALL_SZONE_FROM_RACK(rack), (int)mag_index, fresh_region, SMALL_REGION_SIZE);
if (!fresh_region) { // out of memory!
small_mag_ptr->alloc_underway = FALSE;
OSMemoryBarrier();
SZONE_MAGAZINE_PTR_UNLOCK(small_mag_ptr);
return NULL;
}
ptr = small_malloc_from_region_no_lock(rack, small_mag_ptr, mag_index, msize, fresh_region);
// we don't clear because this freshly allocated space is pristine
small_mag_ptr->alloc_underway = FALSE;
OSMemoryBarrier();
SZONE_MAGAZINE_PTR_UNLOCK(small_mag_ptr);
CHECK(szone, __PRETTY_FUNCTION__);
return ptr;
} else {
SZONE_MAGAZINE_PTR_UNLOCK(small_mag_ptr);
yield();
SZONE_MAGAZINE_PTR_LOCK(small_mag_ptr);
}
}
/* NOTREACHED */
}
size_t
small_size(rack_t *rack, const void *ptr)
{
if (small_region_for_ptr_no_lock(rack, ptr)) {
if (SMALL_META_INDEX_FOR_PTR(ptr) >= NUM_SMALL_BLOCKS) {
return 0;
}
msize_t msize_and_free = *SMALL_METADATA_FOR_PTR(ptr);
if (msize_and_free & SMALL_IS_FREE) {
return 0;
}
#if CONFIG_SMALL_CACHE
{
mag_index_t mag_index = MAGAZINE_INDEX_FOR_SMALL_REGION(SMALL_REGION_FOR_PTR(ptr));
if (DEPOT_MAGAZINE_INDEX != mag_index) {
magazine_t *small_mag_ptr = &(rack->magazines[mag_index]);
if (ptr == small_mag_ptr->mag_last_free) {
return 0;
}
} else {
for (mag_index = 0; mag_index < rack->num_magazines; mag_index++) {
magazine_t *small_mag_ptr = &(rack->magazines[mag_index]);
if (ptr == small_mag_ptr->mag_last_free) {
return 0;
}
}
}
}
#endif
return SMALL_BYTES_FOR_MSIZE(msize_and_free);
}
return 0;
}
static MALLOC_NOINLINE void
free_small_botch(rack_t *rack, void *ptr)
{
mag_index_t mag_index = MAGAZINE_INDEX_FOR_SMALL_REGION(SMALL_REGION_FOR_PTR(ptr));
magazine_t *small_mag_ptr = &(rack->magazines[mag_index]);
SZONE_MAGAZINE_PTR_UNLOCK(small_mag_ptr);
malloc_zone_error(rack->debug_flags, true, "double free for ptr %p\n", ptr);
}
void
free_small(rack_t *rack, void *ptr, region_t small_region, size_t known_size)
{
msize_t msize;
mag_index_t mag_index = MAGAZINE_INDEX_FOR_SMALL_REGION(SMALL_REGION_FOR_PTR(ptr));
magazine_t *small_mag_ptr = &(rack->magazines[mag_index]);
// ptr is known to be in small_region
if (known_size) {
msize = SMALL_MSIZE_FOR_BYTES(known_size + SMALL_QUANTUM - 1);
} else {
msize = SMALL_PTR_SIZE(ptr);
if (SMALL_PTR_IS_FREE(ptr)) {
free_small_botch(rack, ptr);
return;
}
}
SZONE_MAGAZINE_PTR_LOCK(small_mag_ptr);
#if CONFIG_SMALL_CACHE
// Depot does not participate in CONFIG_SMALL_CACHE since it can't be directly malloc()'d
if (DEPOT_MAGAZINE_INDEX != mag_index) {
void *ptr2 = small_mag_ptr->mag_last_free; // Might be NULL
msize_t msize2 = small_mag_ptr->mag_last_free_msize;
region_t rgn2 = small_mag_ptr->mag_last_free_rgn;
/* check that we don't already have this pointer in the cache */
if (ptr == ptr2) {
free_small_botch(rack, ptr);
return;
}
if ((rack->debug_flags & MALLOC_DO_SCRIBBLE) && msize) {
memset(ptr, SCRABBLE_BYTE, SMALL_BYTES_FOR_MSIZE(msize));
}
small_mag_ptr->mag_last_free = ptr;
small_mag_ptr->mag_last_free_msize = msize;
small_mag_ptr->mag_last_free_rgn = small_region;
if (!ptr2) {
SZONE_MAGAZINE_PTR_UNLOCK(small_mag_ptr);
CHECK(szone, __PRETTY_FUNCTION__);
return;
}
msize = msize2;
ptr = ptr2;
small_region = rgn2;
}
#endif /* CONFIG_SMALL_CACHE */
// Now in the time it took to acquire the lock, the region may have migrated
// from one magazine to another. I.e. trailer->mag_index is volatile.
// In which case the magazine lock we obtained (namely magazines[mag_index].mag_lock)
// is stale. If so, keep on tryin' ...
region_trailer_t *trailer = REGION_TRAILER_FOR_SMALL_REGION(small_region);
mag_index_t refreshed_index;
while (mag_index != (refreshed_index = trailer->mag_index)) { // Note assignment
SZONE_MAGAZINE_PTR_UNLOCK(small_mag_ptr);
mag_index = refreshed_index;
small_mag_ptr = &(rack->magazines[mag_index]);
SZONE_MAGAZINE_PTR_LOCK(small_mag_ptr);
}
if (small_free_no_lock(rack, small_mag_ptr, mag_index, small_region, ptr, msize)) {
SZONE_MAGAZINE_PTR_UNLOCK(small_mag_ptr);
}
CHECK(szone, __PRETTY_FUNCTION__);
}
void
print_small_free_list(rack_t *rack)
{
free_list_t ptr;
_SIMPLE_STRING b = _simple_salloc();
mag_index_t mag_index;
if (b) {
_simple_sappend(b, "small free sizes:\n");
for (mag_index = -1; mag_index < rack->num_magazines; mag_index++) {
grain_t slot = 0;
_simple_sprintf(b, "\tMagazine %d: ", mag_index);
while (slot < SMALL_FREE_SLOT_COUNT(rack)) {
ptr = rack->magazines[mag_index].mag_free_list[slot];
if (small_free_list_get_ptr(rack, ptr)) {
_simple_sprintf(b, "%s%y[%d]; ", (slot == SMALL_FREE_SLOT_COUNT(rack) - 1) ? ">=" : "", (slot + 1) * SMALL_QUANTUM,
small_free_list_count(rack, ptr));
}
slot++;
}
_simple_sappend(b, "\n");
}
malloc_report(MALLOC_REPORT_NOLOG | MALLOC_REPORT_NOPREFIX, "%s\n", _simple_string(b));
_simple_sfree(b);
}
}
void
print_small_region(szone_t *szone, boolean_t verbose, region_t region, size_t bytes_at_start, size_t bytes_at_end)
{
unsigned counts[1024];
unsigned in_use = 0;
uintptr_t start = (uintptr_t)SMALL_REGION_ADDRESS(region);
uintptr_t current = start + bytes_at_start;
uintptr_t limit = (uintptr_t)SMALL_REGION_END(region) - bytes_at_end;
msize_t msize_and_free;
msize_t msize;
unsigned ci;
_SIMPLE_STRING b;
uintptr_t pgTot = 0;
if (region == HASHRING_REGION_DEALLOCATED) {
if ((b = _simple_salloc()) != NULL) {
_simple_sprintf(b, "Small region [unknown address] was returned to the OS\n");
malloc_report(MALLOC_REPORT_NOLOG | MALLOC_REPORT_NOPREFIX, "%s\n", _simple_string(b));
_simple_sfree(b);
}
return;
}
memset(counts, 0, sizeof(counts));
while (current < limit) {
msize_and_free = *SMALL_METADATA_FOR_PTR(current);
msize = msize_and_free & ~SMALL_IS_FREE;
if (!msize) {
malloc_report(ASL_LEVEL_ERR, "*** error with %p: msize=%d\n", (void *)current, (unsigned)msize);
break;
}
if (!(msize_and_free & SMALL_IS_FREE)) {
// block in use
if (msize < 1024) {
counts[msize]++;
}
in_use++;
} else {
uintptr_t pgLo = round_page_quanta(current + sizeof(free_list_t) + sizeof(msize_t));
uintptr_t pgHi = trunc_page_quanta(current + SMALL_BYTES_FOR_MSIZE(msize) - sizeof(msize_t));
if (pgLo < pgHi) {
pgTot += (pgHi - pgLo);
}
}
current += SMALL_BYTES_FOR_MSIZE(msize);
}
if ((b = _simple_salloc()) != NULL) {
_simple_sprintf(b, "Small region [%p-%p, %y] \t", (void *)start, SMALL_REGION_END(region), (int)SMALL_REGION_SIZE);
_simple_sprintf(b, "Magazine=%d \t", MAGAZINE_INDEX_FOR_SMALL_REGION(region));
_simple_sprintf(b, "Allocations in use=%d \t Bytes in use=%ly \t", in_use, BYTES_USED_FOR_SMALL_REGION(region));
if (bytes_at_end || bytes_at_start) {
_simple_sprintf(b, "Untouched=%ly ", bytes_at_end + bytes_at_start);
}
if (DEPOT_MAGAZINE_INDEX == MAGAZINE_INDEX_FOR_SMALL_REGION(region)) {
_simple_sprintf(b, "Advised MADV_FREE=%ly", pgTot);
} else {
_simple_sprintf(b, "Fragments subject to reclamation=%ly", pgTot);
}
if (verbose && in_use) {
_simple_sappend(b, "\n\tSizes in use: ");
for (ci = 0; ci < 1024; ci++) {
if (counts[ci]) {
_simple_sprintf(b, "%d[%d] ", SMALL_BYTES_FOR_MSIZE(ci), counts[ci]);
}
}
}
malloc_report(MALLOC_REPORT_NOLOG | MALLOC_REPORT_NOPREFIX, "%s\n", _simple_string(b));
_simple_sfree(b);
}
}
static char *small_freelist_fail_msg = "check: small free list incorrect";
#define SMALL_FREELIST_FAIL(fmt, ...) \
malloc_zone_check_fail(small_freelist_fail_msg, \
" (slot=%u), counter=%d\n" fmt, slot, counter, __VA_ARGS__);
boolean_t
small_free_list_check(rack_t *rack, grain_t slot, unsigned counter)
{
mag_index_t mag_index;
for (mag_index = -1; mag_index < rack->num_magazines; mag_index++) {
magazine_t *small_mag_ptr = &(rack->magazines[mag_index]);
SZONE_MAGAZINE_PTR_LOCK(small_mag_ptr);
unsigned count = 0;
free_list_t current = rack->magazines[mag_index].mag_free_list[slot];
free_list_t previous = (free_list_t){ .p = NULL };
msize_t msize_and_free;
void *ptr = NULL;
while ((ptr = small_free_list_get_ptr(rack, current))) {
msize_and_free = *SMALL_METADATA_FOR_PTR(ptr);
if (!(msize_and_free & SMALL_IS_FREE)) {
SMALL_FREELIST_FAIL("*** in-use ptr in free list slot=%u count=%d ptr=%p\n", slot, count, ptr);
SZONE_MAGAZINE_PTR_UNLOCK(small_mag_ptr);
return 0;
}
if (((uintptr_t)ptr) & (SMALL_QUANTUM - 1)) {
SMALL_FREELIST_FAIL("*** unaligned ptr in free list slot=%u count=%d ptr=%p\n", slot, count, ptr);
SZONE_MAGAZINE_PTR_UNLOCK(small_mag_ptr);
return 0;
}
if (!small_region_for_ptr_no_lock(rack, ptr)) {
SMALL_FREELIST_FAIL("*** ptr not in szone slot=%d count=%d ptr=%p\n", slot, count, ptr);
SZONE_MAGAZINE_PTR_UNLOCK(small_mag_ptr);
return 0;
}
if (small_free_list_get_previous(rack, current).p != previous.p) {
SMALL_FREELIST_FAIL("*** previous incorrectly set slot=%u count=%d ptr=%p\n", slot, count, ptr);
SZONE_MAGAZINE_PTR_UNLOCK(small_mag_ptr);
return 0;
}
previous = current;
current = small_free_list_get_next(rack, current);
count++;
}
SZONE_MAGAZINE_PTR_UNLOCK(small_mag_ptr);
}
return 1;
}
================================================
FILE: InterView-obj-isa-class/libmalloc-166.220.1/src/magazine_tiny.c
================================================
/*
* Copyright (c) 2015 Apple Inc. All rights reserved.
*
* @APPLE_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apple Public Source License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. Please obtain a copy of the License at
* http://www.opensource.apple.com/apsl/ and read it before using this
* file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPLE_LICENSE_HEADER_END@
*/
#include "internal.h"
// The address and size of the block in mag_last_free are combined. These
// macros abstract construction of the combined value and extraction of the
// size and pointer.
#define TINY_MAG_LAST_FREE_FROM_PTR_AND_MSIZE(ptr, msize) (void *)(((uintptr_t)(ptr))|((msize_t)msize))
#define TINY_PTR_FROM_MAG_LAST_FREE(x) (void *)(((uintptr_t)(x)) & ~(TINY_QUANTUM - 1))
#define TINY_MSIZE_FROM_MAG_LAST_FREE(x) (msize_t)(((uintptr_t)(x)) & (TINY_QUANTUM - 1))
// Adjusts the pointer part of mag_last_free by a given amount in bytes. Must be
// a multiple of the quantum size (not checked).
#define TINY_MAG_LAST_FREE_PTR_ADJUST_PTR(x, size) (x) = ((void *)(x) + (size))
// Decrements the size part of mag_last_free by a given msize value. Must not
// reduce the msize part below zero (not checked).
#define TINY_MAG_LAST_FREE_PTR_DEC_MSIZE(x, msize_delta) (x) = ((void *)(x) - (msize_delta))
static MALLOC_INLINE MALLOC_ALWAYS_INLINE
mag_index_t
tiny_mag_get_thread_index(void)
{
#if CONFIG_TINY_USES_HYPER_SHIFT
if (os_likely(_os_cpu_number_override == -1)) {
return _os_cpu_number() >> hyper_shift;
} else {
return _os_cpu_number_override >> hyper_shift;
}
#else // CONFIG_SMALL_USES_HYPER_SHIFT
if (os_likely(_os_cpu_number_override == -1)) {
return _os_cpu_number();
} else {
return _os_cpu_number_override;
}
#endif // CONFIG_SMALL_USES_HYPER_SHIFT
}
/*
* Get the size of the previous free block, which is stored in the last two
* bytes of the block. If the previous block is not free, then the result is
* undefined.
*/
static msize_t
get_tiny_previous_free_msize(const void *ptr)
{
// check whether the previous block is in the tiny region and a block header
// if so, then the size of the previous block is one, and there is no stored
// size.
if (ptr != TINY_REGION_FOR_PTR(ptr)) {
void *prev_block = (void *)((uintptr_t)ptr - TINY_QUANTUM);
uint32_t *prev_header = TINY_BLOCK_HEADER_FOR_PTR(prev_block);
msize_t prev_index = TINY_INDEX_FOR_PTR(prev_block);
if (BITARRAY_BIT(prev_header, prev_index)) {
return 1;
}
return TINY_PREVIOUS_MSIZE(ptr);
}
// don't read possibly unmapped memory before the beginning of the region
return 0;
}
static MALLOC_INLINE void
set_tiny_meta_header_in_use(const void *ptr, msize_t msize)
{
uint32_t *block_header = TINY_BLOCK_HEADER_FOR_PTR(ptr);
msize_t index = TINY_INDEX_FOR_PTR(ptr);
msize_t clr_msize = msize - 1;
msize_t midx = (index >> 5) << 1;
uint32_t val = (1 << (index & 31));
#if DEBUG_MALLOC
if (msize >= NUM_TINY_SLOTS) {
malloc_report(ASL_LEVEL_ERR, "set_tiny_meta_header_in_use() invariant broken %p %d\n", ptr, msize);
}
if ((unsigned)index + (unsigned)msize > 0x10000) {
malloc_report(ASL_LEVEL_ERR, "set_tiny_meta_header_in_use() invariant broken (2) %p %d\n", ptr, msize);
}
#endif
block_header[midx] |= val; // BITARRAY_SET(block_header, index);
block_header[midx + 1] |= val; // BITARRAY_SET(in_use, index);
// bitarray_mclr(block_header, index, end_bit);
// bitarray_mclr(in_use, index, end_bit);
index++;
midx = (index >> 5) << 1;
unsigned start = index & 31;
unsigned end = start + clr_msize;
#if defined(__LP64__)
if (end > 63) {
unsigned mask0 = (0xFFFFFFFFU >> (31 - start)) >> 1;
unsigned mask1 = (0xFFFFFFFFU << (end - 64));
block_header[midx + 0] &= mask0; // clear header
block_header[midx + 1] &= mask0; // clear in_use
block_header[midx + 2] = 0; // clear header
block_header[midx + 3] = 0; // clear in_use
block_header[midx + 4] &= mask1; // clear header
block_header[midx + 5] &= mask1; // clear in_use
} else
#endif
if (end > 31) {
unsigned mask0 = (0xFFFFFFFFU >> (31 - start)) >> 1;
unsigned mask1 = (0xFFFFFFFFU << (end - 32));
block_header[midx + 0] &= mask0;
block_header[midx + 1] &= mask0;
block_header[midx + 2] &= mask1;
block_header[midx + 3] &= mask1;
} else {
unsigned mask = (0xFFFFFFFFU >> (31 - start)) >> 1;
mask |= (0xFFFFFFFFU << end);
block_header[midx + 0] &= mask;
block_header[midx + 1] &= mask;
}
// we set the block_header bit for the following block to reaffirm next block is a block
index += clr_msize;
midx = (index >> 5) << 1;
val = (1 << (index & 31));
block_header[midx] |= val; // BITARRAY_SET(block_header, (index+clr_msize));
#if DEBUG_MALLOC
{
boolean_t ff;
msize_t mf;
mf = get_tiny_meta_header(ptr, &ff);
if (msize != mf) {
malloc_report(ASL_LEVEL_INFO, "setting header for tiny in_use %p : %d\n", ptr, msize);
malloc_report(ASL_LEVEL_INFO, "reading header for tiny %p : %d %d\n", ptr, mf, ff);
}
}
#endif
}
static MALLOC_INLINE void set_tiny_meta_header_in_use_1(const void *ptr) // As above with msize == 1
{
uint32_t *block_header = TINY_BLOCK_HEADER_FOR_PTR(ptr);
msize_t index = TINY_INDEX_FOR_PTR(ptr);
msize_t midx = (index >> 5) << 1;
uint32_t val = (1 << (index & 31));
block_header[midx] |= val; // BITARRAY_SET(block_header, index);
block_header[midx + 1] |= val; // BITARRAY_SET(in_use, index);
index++;
midx = (index >> 5) << 1;
val = (1 << (index & 31));
block_header[midx] |= val; // BITARRAY_SET(block_header, (index+clr_msize))
}
static MALLOC_INLINE void
set_tiny_meta_header_middle(const void *ptr)
{
// indicates this block is in the middle of an in use block
uint32_t *block_header;
uint32_t *in_use;
msize_t index;
block_header = TINY_BLOCK_HEADER_FOR_PTR(ptr);
in_use = TINY_INUSE_FOR_HEADER(block_header);
index = TINY_INDEX_FOR_PTR(ptr);
BITARRAY_CLR(block_header, index);
BITARRAY_CLR(in_use, index);
}
static MALLOC_INLINE void
set_tiny_meta_header_free(const void *ptr, msize_t msize)
{
// !msize is acceptable and means 65536
uint32_t *block_header = TINY_BLOCK_HEADER_FOR_PTR(ptr);
msize_t index = TINY_INDEX_FOR_PTR(ptr);
msize_t midx = (index >> 5) << 1;
uint32_t val = (1 << (index & 31));
#if DEBUG_MALLOC
if ((unsigned)index + (unsigned)msize > 0x10000) {
malloc_report(ASL_LEVEL_ERR, "setting header for tiny free %p msize too large: %d\n", ptr, msize);
}
#endif
block_header[midx] |= val; // BITARRAY_SET(block_header, index);
block_header[midx + 1] &= ~val; // BITARRAY_CLR(in_use, index);
// mark the end of this block if msize is > 1. For msize == 0, the whole
// region is free, so there is no following block. For msize == 1, there is
// no space to write the size on 64 bit systems. The size for 1 quantum
// blocks is computed from the metadata bitmaps.
if (msize > 1) {
void *follower = FOLLOWING_TINY_PTR(ptr, msize);
TINY_PREVIOUS_MSIZE(follower) = msize;
TINY_FREE_SIZE(ptr) = msize;
}
if (msize == 0) {
TINY_FREE_SIZE(ptr) = msize;
}
#if DEBUG_MALLOC
boolean_t ff;
msize_t mf = get_tiny_meta_header(ptr, &ff);
if ((msize != mf) || !ff) {
malloc_report(ASL_LEVEL_INFO, "setting header for tiny free %p : %u\n", ptr, msize);
malloc_report(ASL_LEVEL_INFO, "reading header for tiny %p : %u %u\n", ptr, mf, ff);
}
#endif
}
static MALLOC_INLINE boolean_t
tiny_meta_header_is_free(const void *ptr)
{
uint32_t *block_header;
uint32_t *in_use;
msize_t index;
block_header = TINY_BLOCK_HEADER_FOR_PTR(ptr);
in_use = TINY_INUSE_FOR_HEADER(block_header);
index = TINY_INDEX_FOR_PTR(ptr);
if (!BITARRAY_BIT(block_header, index)) {
return 0;
}
return !BITARRAY_BIT(in_use, index);
}
static MALLOC_INLINE void *
tiny_previous_preceding_free(void *ptr, msize_t *prev_msize)
{
// returns the previous block, assuming and verifying it's free
uint32_t *block_header;
uint32_t *in_use;
msize_t index;
msize_t previous_msize;
msize_t previous_index;
void *previous_ptr;
block_header = TINY_BLOCK_HEADER_FOR_PTR(ptr);
in_use = TINY_INUSE_FOR_HEADER(block_header);
index = TINY_INDEX_FOR_PTR(ptr);
if (!index) {
return NULL;
}
if ((previous_msize = get_tiny_previous_free_msize(ptr)) > index) {
return NULL;
}
previous_index = index - previous_msize;
previous_ptr = (void *)((uintptr_t)TINY_REGION_FOR_PTR(ptr) + TINY_BYTES_FOR_MSIZE(previous_index));
if (!BITARRAY_BIT(block_header, previous_index)) {
return NULL;
}
if (BITARRAY_BIT(in_use, previous_index)) {
return NULL;
}
if (get_tiny_free_size(previous_ptr) != previous_msize) {
return NULL;
}
// conservative check did match true check
*prev_msize = previous_msize;
return previous_ptr;
}
/*
* Adds an item to the proper free list, and also marks the meta-header of the
* block properly.
* Assumes szone has been locked
*/
static void
tiny_free_list_add_ptr(rack_t *rack, magazine_t *tiny_mag_ptr, void *ptr, msize_t msize)
{
grain_t slot = (!msize || (msize >= NUM_TINY_SLOTS)) ? NUM_TINY_SLOTS - 1 : msize - 1;
tiny_free_list_t *free_ptr = ptr;
tiny_free_list_t *free_head = tiny_mag_ptr->mag_free_list[slot].p;
#if DEBUG_MALLOC
if (LOG(szone, ptr)) {
malloc_report(ASL_LEVEL_INFO, "in %s, ptr=%p, msize=%d\n", __FUNCTION__, ptr, msize);
}
if (((uintptr_t)ptr) & (TINY_QUANTUM - 1)) {
malloc_zone_error(rack->debug_flags, true, "tiny_free_list_add_ptr: Unaligned ptr: %p\n", ptr);
}
#endif
set_tiny_meta_header_free(ptr, msize);
if (free_head) {
#if DEBUG_MALLOC
if (free_list_unchecksum_ptr(szone, &free_head->previous)) {
malloc_zone_error(rack->debug_flags, true,
"tiny_free_list_add_ptr: Internal invariant broken (free_head->previous): "
"ptr=%p slot=%d free_head=%p previous=%p\n", ptr, slot, (void *)free_head, free_head->previous.p);
}
if (!tiny_meta_header_is_free(free_head)) {
malloc_zone_error(rack->debug_flags, true,
"tiny_free_list_add_ptr: Internal invariant broken (free_head is not a free pointer): "
"ptr=%p slot=%d free_head=%p\n", ptr, slot, (void *)free_head);
}
#endif
free_head->previous.u = free_list_checksum_ptr(rack, free_ptr);
} else {
BITMAPV_SET(tiny_mag_ptr->mag_bitmap, slot);
}
free_ptr->previous.u = free_list_checksum_ptr(rack, NULL);
free_ptr->next.u = free_list_checksum_ptr(rack, free_head);
tiny_mag_ptr->mag_free_list[slot].p = free_ptr;
}
/*
* Removes the item pointed to by ptr in the proper free list.
* Assumes szone has been locked
*/
static void
tiny_free_list_remove_ptr(rack_t *rack, magazine_t *tiny_mag_ptr, void *ptr, msize_t msize)
{
grain_t slot = (!msize || (msize >= NUM_TINY_SLOTS)) ? NUM_TINY_SLOTS - 1 : msize - 1;
tiny_free_list_t *free_ptr = ptr, *next, *previous;
next = free_list_unchecksum_ptr(rack, &free_ptr->next);
previous = free_list_unchecksum_ptr(rack, &free_ptr->previous);
#if DEBUG_MALLOC
if (LOG(szone, ptr)) {
malloc_report(ASL_LEVEL_INFO, "In %s, ptr=%p, msize=%d\n", __FUNCTION__, ptr, msize);
}
#endif
if (!previous) {
// The block to remove is the head of the free list
#if DEBUG_MALLOC
if (tiny_mag_ptr->mag_free_list[slot] != ptr) {
malloc_zone_error(rack->debug_flags, true,
"tiny_free_list_remove_ptr: Internal invariant broken (tiny_mag_ptr->mag_free_list[slot]): "
"ptr=%p slot=%d msize=%d tiny_mag_ptr->mag_free_list[slot]=%p\n", ptr, slot, msize,
(void *)tiny_mag_ptr->mag_free_list[slot]);
return;
}
#endif
tiny_mag_ptr->mag_free_list[slot].p = next;
if (!next) {
BITMAPV_CLR(tiny_mag_ptr->mag_bitmap, slot);
}
} else {
// Check that the next pointer of "previous" points to free_ptr.
tiny_free_list_t *prev_next = free_list_unchecksum_ptr(rack, &previous->next);
if (prev_next != free_ptr) {
malloc_zone_error(rack->debug_flags, true,
"tiny_free_list_remove_ptr: Internal invariant broken (next ptr of prev): "
"ptr=%p, prev_next=%p\n", ptr, prev_next);
__builtin_unreachable(); // Always crashes in malloc_zone_error().
}
// We know free_ptr is already checksummed, so we don't need to do it
// again.
previous->next = free_ptr->next;
}
if (next) {
// Check that the previous pointer of "next" points to free_ptr.
tiny_free_list_t *next_prev = free_list_unchecksum_ptr(rack, &next->previous);
if (next_prev != free_ptr) {
malloc_zone_error(rack->debug_flags, true,
"tiny_free_list_remove_ptr: Internal invariant broken (prev ptr of next): "
"ptr=%p, next_prev=%p\n", ptr, next_prev);
__builtin_unreachable(); // Always crashes in malloc_zone_error().
}
// We know free_ptr is already checksummed, so we don't need to do it
// again.
next->previous = free_ptr->previous;
}
}
void
tiny_finalize_region(rack_t *rack, magazine_t *tiny_mag_ptr)
{
void *last_block, *previous_block;
uint32_t *last_header;
msize_t last_msize, previous_msize, last_index;
// It is possible that the block prior to the last block in the region has
// been free'd, but was not coalesced with the free bytes at the end of the
// block, since we treat the bytes at the end of the region as "in use" in
// the meta headers. Attempt to coalesce the last block with the previous
// block, so we don't violate the "no consecutive free blocks" invariant.
//
// FIXME: Need to investigate how much work would be required to increase
// 'mag_bytes_free_at_end' when freeing the preceding block, rather
// than performing this workaround.
//
if (tiny_mag_ptr->mag_bytes_free_at_end) {
last_block = (void *)((uintptr_t)TINY_REGION_END(tiny_mag_ptr->mag_last_region) - tiny_mag_ptr->mag_bytes_free_at_end);
last_msize = TINY_MSIZE_FOR_BYTES(tiny_mag_ptr->mag_bytes_free_at_end);
last_header = TINY_BLOCK_HEADER_FOR_PTR(last_block);
last_index = TINY_INDEX_FOR_PTR(last_block);
// Before anything we transform any remaining mag_bytes_free_at_end into a
// regular free block. We take special care here to update the bitfield
// information, since we are bypassing the normal free codepath. If there
// is more than one quanta worth of memory in mag_bytes_free_at_end, then
// there will be two block headers:
// 1) header for the free space at end, msize = 1
// 2) header inserted by set_tiny_meta_header_in_use after block
// We must clear the second one so that when the free block's size is
// queried, we do not think the block is only 1 quantum in size because
// of the second set header bit.
if (last_index != (NUM_TINY_BLOCKS - 1)) {
BITARRAY_CLR(last_header, (last_index + 1));
}
previous_block = tiny_previous_preceding_free(last_block, &previous_msize);
if (previous_block) {
set_tiny_meta_header_middle(last_block);
tiny_free_list_remove_ptr(rack, tiny_mag_ptr, previous_block, previous_msize);
last_block = previous_block;
last_msize += previous_msize;
}
// splice last_block into the free list
tiny_free_list_add_ptr(rack, tiny_mag_ptr, last_block, last_msize);
tiny_mag_ptr->mag_bytes_free_at_end = 0;
}
#if CONFIG_ASLR_INTERNAL
// Coalesce the big free block at start with any following free blocks
if (tiny_mag_ptr->mag_bytes_free_at_start) {
last_block = TINY_REGION_ADDRESS(tiny_mag_ptr->mag_last_region);
last_msize = TINY_MSIZE_FOR_BYTES(tiny_mag_ptr->mag_bytes_free_at_start);
void *next_block = (void *)((uintptr_t)last_block + tiny_mag_ptr->mag_bytes_free_at_start);
// clear the in use bit we were using to mark the end of the big start block
set_tiny_meta_header_middle((void *)((uintptr_t)next_block - TINY_QUANTUM));
// Coalesce the big start block with any following free blocks
if (tiny_meta_header_is_free(next_block)) {
msize_t next_msize = get_tiny_free_size(next_block);
set_tiny_meta_header_middle(next_block);
tiny_free_list_remove_ptr(rack, tiny_mag_ptr, next_block, next_msize);
last_msize += next_msize;
}
// splice last_block into the free list
tiny_free_list_add_ptr(rack, tiny_mag_ptr, last_block, last_msize);
tiny_mag_ptr->mag_bytes_free_at_start = 0;
}
#endif
tiny_mag_ptr->mag_last_region = NULL;
}
int
tiny_free_detach_region(rack_t *rack, magazine_t *tiny_mag_ptr, region_t r)
{
uintptr_t start = (uintptr_t)TINY_REGION_ADDRESS(r);
uintptr_t current = start;
uintptr_t limit = (uintptr_t)TINY_REGION_END(r);
boolean_t is_free;
msize_t msize;
int total_alloc = 0;
while (current < limit) {
msize = get_tiny_meta_header((void *)current, &is_free);
if (is_free && !msize && (current == start)) {
// first block is all free
break;
}
if (!msize) {
#if DEBUG_MALLOC
malloc_report(ASL_LEVEL_ERR, "*** tiny_free_detach_region error with %p: msize=%d is_free=%d\n", (void *)current, msize, is_free);
#endif
break;
}
if (is_free) {
tiny_free_list_remove_ptr(rack, tiny_mag_ptr, (void *)current, msize);
} else {
total_alloc++;
}
current += TINY_BYTES_FOR_MSIZE(msize);
}
return total_alloc;
}
size_t
tiny_free_reattach_region(rack_t *rack, magazine_t *tiny_mag_ptr, region_t r)
{
uintptr_t start = (uintptr_t)TINY_REGION_ADDRESS(r);
uintptr_t current = start;
uintptr_t limit = (uintptr_t)TINY_REGION_END(r);
boolean_t is_free;
msize_t msize;
size_t total_alloc = 0;
while (current < limit) {
msize = get_tiny_meta_header((void *)current, &is_free);
if (is_free && !msize && (current == start)) {
// first block is all free
break;
}
if (!msize) {
#if DEBUG_MALLOC
malloc_report(ASL_LEVEL_ERR, "*** tiny_free_reattach_region error with %p: msize=%d is_free=%d\n", (void *)current, msize, is_free);
#endif
break;
}
if (is_free) {
tiny_free_list_add_ptr(rack, tiny_mag_ptr, (void *)current, msize);
} else {
total_alloc += TINY_BYTES_FOR_MSIZE(msize);
}
current += TINY_BYTES_FOR_MSIZE(msize);
}
return total_alloc;
}
typedef struct {
uint8_t pnum, size;
} tiny_pg_pair_t;
void
tiny_free_scan_madvise_free(rack_t *rack, magazine_t *depot_ptr, region_t r)
{
uintptr_t start = (uintptr_t)TINY_REGION_ADDRESS(r);
uintptr_t current = start;
uintptr_t limit = (uintptr_t)TINY_REGION_END(r);
boolean_t is_free;
msize_t msize;
tiny_pg_pair_t advisory[((TINY_REGION_PAYLOAD_BYTES + vm_page_quanta_size - 1) >> vm_page_quanta_shift) >>
1]; // 256bytes stack allocated
int advisories = 0;
// Scan the metadata identifying blocks which span one or more pages. Mark the pages MADV_FREE taking care to preserve free list
// management data.
while (current < limit) {
msize = get_tiny_meta_header((void *)current, &is_free);
if (is_free && !msize && (current == start)) {
// first block is all free
#if DEBUG_MALLOC
malloc_report(ASL_LEVEL_INFO, "*** tiny_free_scan_madvise_free first block is all free! %p: msize=%d is_free=%d\n", (void *)current,
msize, is_free);
#endif
uintptr_t pgLo = round_page_kernel(start + sizeof(tiny_free_list_t) + sizeof(msize_t));
uintptr_t pgHi = trunc_page_kernel(start + TINY_REGION_SIZE - sizeof(msize_t));
if (pgLo < pgHi) {
advisory[advisories].pnum = (pgLo - start) >> vm_kernel_page_shift;
advisory[advisories].size = (pgHi - pgLo) >> vm_kernel_page_shift;
advisories++;
}
break;
}
if (!msize) {
#if DEBUG_MALLOC
malloc_report(ASL_LEVEL_ERR, "*** tiny_free_scan_madvise_free error with %p: msize=%d is_free=%d\n", (void *)current, msize, is_free);
#endif
break;
}
if (is_free) {
uintptr_t pgLo = round_page_kernel(current + sizeof(tiny_free_list_t) + sizeof(msize_t));
uintptr_t pgHi = trunc_page_kernel(current + TINY_BYTES_FOR_MSIZE(msize) - sizeof(msize_t));
if (pgLo < pgHi) {
advisory[advisories].pnum = (pgLo - start) >> vm_kernel_page_shift;
advisory[advisories].size = (pgHi - pgLo) >> vm_kernel_page_shift;
advisories++;
}
}
current += TINY_BYTES_FOR_MSIZE(msize);
}
if (advisories > 0) {
int i;
// So long as the following hold for this region:
// (1) No malloc()'s are ever performed from the depot (hence free pages remain free,)
// (2) The region is not handed over to a per-CPU magazine (where malloc()'s could be performed),
// (3) The entire region is not mumap()'d (so the madvise's are applied to the intended addresses),
// then the madvise opportunities collected just above can be applied outside all locks.
// (1) is ensured by design, (2) and (3) are ensured by bumping the globally visible counter node->pinned_to_depot.
OSAtomicIncrement32Barrier(&(REGION_TRAILER_FOR_TINY_REGION(r)->pinned_to_depot));
SZONE_MAGAZINE_PTR_UNLOCK(depot_ptr);
for (i = 0; i < advisories; ++i) {
uintptr_t addr = (advisory[i].pnum << vm_kernel_page_shift) + start;
size_t size = advisory[i].size << vm_kernel_page_shift;
mvm_madvise_free(rack, r, addr, addr + size, NULL, rack->debug_flags & MALLOC_DO_SCRIBBLE);
}
SZONE_MAGAZINE_PTR_LOCK(depot_ptr);
OSAtomicDecrement32Barrier(&(REGION_TRAILER_FOR_TINY_REGION(r)->pinned_to_depot));
}
}
static region_t
tiny_find_msize_region(rack_t *rack, magazine_t *tiny_mag_ptr, mag_index_t mag_index, msize_t msize)
{
tiny_free_list_t *ptr;
grain_t slot = msize - 1;
free_list_t *free_list = tiny_mag_ptr->mag_free_list;
free_list_t *the_slot = free_list + slot;
free_list_t *limit;
#if defined(__LP64__)
uint64_t bitmap;
#else
uint32_t bitmap;
#endif
// Assumes we've locked the magazine
CHECK_MAGAZINE_PTR_LOCKED(szone, tiny_mag_ptr, __PRETTY_FUNCTION__);
// Look for an exact match by checking the freelist for this msize.
ptr = the_slot->p;
if (ptr) {
return TINY_REGION_FOR_PTR(ptr);
}
// Mask off the bits representing slots holding free blocks smaller than the
// size we need. If there are no larger free blocks, try allocating from
// the free space at the end of the tiny region.
#if defined(__LP64__)
bitmap = ((uint64_t *)(tiny_mag_ptr->mag_bitmap))[0] & ~((1ULL << slot) - 1);
#else
bitmap = tiny_mag_ptr->mag_bitmap[0] & ~((1 << slot) - 1);
#endif
if (!bitmap) {
return NULL;
}
slot = BITMAPV_CTZ(bitmap);
limit = free_list + NUM_TINY_SLOTS - 1;
free_list += slot;
if (free_list < limit) {
ptr = free_list->p;
if (ptr) {
return TINY_REGION_FOR_PTR(ptr);
} else {
/* Shouldn't happen. Fall through to look at last slot. */
#if DEBUG_MALLOC
malloc_report(ASL_LEVEL_ERR, "in tiny_find_msize_region(), mag_bitmap out of sync, slot=%d\n", slot);
#endif
}
}
// We are now looking at the last slot, which contains blocks equal to, or
// due to coalescing of free blocks, larger than (NUM_TINY_SLOTS - 1) * tiny quantum size.
ptr = limit->p;
if (ptr) {
return TINY_REGION_FOR_PTR(ptr);
}
return NULL;
}
static MALLOC_INLINE void
tiny_madvise_free_range_no_lock(rack_t *rack,
magazine_t *tiny_mag_ptr,
region_t region,
void *headptr,
size_t headsize,
void *ptr,
msize_t msize)
{
region_trailer_t *node = REGION_TRAILER_FOR_TINY_REGION(region);
// Lock on tiny_magazines[mag_index] is already held here
// Calculate the first page in the coalesced block that would be safe to mark MADV_FREE
size_t free_header_size = sizeof(tiny_free_list_t) + sizeof(msize_t);
uintptr_t safe_ptr = (uintptr_t)ptr + free_header_size;
uintptr_t round_safe = round_page_kernel(safe_ptr);
// Calculate the last page in the coalesced block that would be safe to mark MADV_FREE
size_t free_tail_size = sizeof(msize_t);
uintptr_t safe_extent = (uintptr_t)ptr + TINY_BYTES_FOR_MSIZE(msize) - free_tail_size;
uintptr_t trunc_extent = trunc_page_kernel(safe_extent);
// The newly freed block may complete a span of bytes that cover a page. Mark it with MADV_FREE.
if (round_safe < trunc_extent) { // Coalesced area covers a page (perhaps many)
// Extend the freed block by the free region header and tail sizes to include pages
// we may have coalesced that no longer host free region tails and headers.
// This may extend over in-use ranges, but the MIN/MAX clamping below will fix that up.
uintptr_t lo = trunc_page_kernel((uintptr_t)headptr - free_tail_size);
uintptr_t hi = round_page_kernel((uintptr_t)headptr + headsize + free_header_size);
uintptr_t free_lo = MAX(round_safe, lo);
uintptr_t free_hi = MIN(trunc_extent, hi);
if (free_lo < free_hi) {
tiny_free_list_remove_ptr(rack, tiny_mag_ptr, ptr, msize);
set_tiny_meta_header_in_use(ptr, msize);
OSAtomicIncrement32Barrier(&(node->pinned_to_depot));
SZONE_MAGAZINE_PTR_UNLOCK(tiny_mag_ptr);
mvm_madvise_free(rack, region, free_lo, free_hi, &rack->last_madvise, rack->debug_flags & MALLOC_DO_SCRIBBLE);
SZONE_MAGAZINE_PTR_LOCK(tiny_mag_ptr);
OSAtomicDecrement32Barrier(&(node->pinned_to_depot));
set_tiny_meta_header_free(ptr, msize);
tiny_free_list_add_ptr(rack, tiny_mag_ptr, ptr, msize);
}
}
}
static boolean_t
tiny_get_region_from_depot(rack_t *rack, magazine_t *tiny_mag_ptr, mag_index_t mag_index, msize_t msize)
{
magazine_t *depot_ptr = &(rack->magazines[DEPOT_MAGAZINE_INDEX]);
/* FIXME: Would Uniprocessor benefit from recirc and MADV_FREE? */
if (rack->num_magazines == 1) { // Uniprocessor, single magazine, so no recirculation necessary
return 0;
}
#if DEBUG_MALLOC
if (DEPOT_MAGAZINE_INDEX == mag_index) {
malloc_zone_error(rack->debug_flags, true, "tiny_get_region_from_depot called for magazine index -1\n");
return 0;
}
#endif
SZONE_MAGAZINE_PTR_LOCK(depot_ptr);
// Appropriate a Depot'd region that can satisfy requested msize.
region_trailer_t *node;
region_t sparse_region;
while (1) {
sparse_region = tiny_find_msize_region(rack, depot_ptr, DEPOT_MAGAZINE_INDEX, msize);
if (NULL == sparse_region) { // Depot empty?
SZONE_MAGAZINE_PTR_UNLOCK(depot_ptr);
return 0;
}
node = REGION_TRAILER_FOR_TINY_REGION(sparse_region);
if (0 >= node->pinned_to_depot) {
break;
}
SZONE_MAGAZINE_PTR_UNLOCK(depot_ptr);
yield();
SZONE_MAGAZINE_PTR_LOCK(depot_ptr);
}
// disconnect node from Depot
recirc_list_extract(rack, depot_ptr, node);
// Iterate the region pulling its free entries off the (locked) Depot's free list
int objects_in_use = tiny_free_detach_region(rack, depot_ptr, sparse_region);
// Transfer ownership of the region
MAGAZINE_INDEX_FOR_TINY_REGION(sparse_region) = mag_index;
node->pinned_to_depot = 0;
// Iterate the region putting its free entries on its new (locked) magazine's free list
size_t bytes_inplay = tiny_free_reattach_region(rack, tiny_mag_ptr, sparse_region);
depot_ptr->mag_num_bytes_in_objects -= bytes_inplay;
depot_ptr->num_bytes_in_magazine -= TINY_REGION_PAYLOAD_BYTES;
depot_ptr->mag_num_objects -= objects_in_use;
tiny_mag_ptr->mag_num_bytes_in_objects += bytes_inplay;
tiny_mag_ptr->num_bytes_in_magazine += TINY_REGION_PAYLOAD_BYTES;
tiny_mag_ptr->mag_num_objects += objects_in_use;
// connect to magazine as first node
recirc_list_splice_first(rack, tiny_mag_ptr, node);
SZONE_MAGAZINE_PTR_UNLOCK(depot_ptr);
// DTrace USDT Probe
MAGMALLOC_DEPOTREGION(TINY_SZONE_FROM_RACK(rack), (int)mag_index, (void *)sparse_region,
TINY_REGION_SIZE, (int)BYTES_USED_FOR_TINY_REGION(sparse_region));
return 1;
}
#if CONFIG_RECIRC_DEPOT
static region_t
tiny_free_try_depot_unmap_no_lock(rack_t *rack, magazine_t *depot_ptr, region_trailer_t *node)
{
if (0 < node->bytes_used || 0 < node->pinned_to_depot ||
depot_ptr->recirculation_entries < recirc_retained_regions)
{
return NULL;
}
// disconnect node from Depot
recirc_list_extract(rack, depot_ptr, node);
// Iterate the region pulling its free entries off the (locked) Depot's free list
region_t sparse_region = TINY_REGION_FOR_PTR(node);
int objects_in_use = tiny_free_detach_region(rack, depot_ptr, sparse_region);
if (0 == objects_in_use) {
// Invalidate the hash table entry for this region with HASHRING_REGION_DEALLOCATED.
// Using HASHRING_REGION_DEALLOCATED preserves the collision chain, using HASHRING_OPEN_ENTRY (0) would not.
rgnhdl_t pSlot = hash_lookup_region_no_lock(rack->region_generation->hashed_regions,
rack->region_generation->num_regions_allocated,
rack->region_generation->num_regions_allocated_shift,
sparse_region);
if (NULL == pSlot) {
malloc_zone_error(rack->debug_flags, true, "tiny_free_try_depot_unmap_no_lock hash lookup failed: %p\n", sparse_region);
return NULL;
}
*pSlot = HASHRING_REGION_DEALLOCATED;
depot_ptr->num_bytes_in_magazine -= TINY_REGION_PAYLOAD_BYTES;
// Atomically increment num_regions_dealloc
#ifdef __LP64___
OSAtomicIncrement64(&rack->num_regions_dealloc);
#else
OSAtomicIncrement32((int32_t *)&rack->num_regions_dealloc);
#endif
// Caller will transfer ownership of the region back to the OS with no locks held
MAGMALLOC_DEALLOCREGION(TINY_SZONE_FROM_RACK(rack), (void *)sparse_region, TINY_REGION_SIZE); // DTrace USDT Probe
return sparse_region;
} else {
malloc_zone_error(rack->debug_flags, true, "tiny_free_try_depot_unmap_no_lock objects_in_use not zero: %d\n", objects_in_use);
return NULL;
}
}
static boolean_t
tiny_free_do_recirc_to_depot(rack_t *rack, magazine_t *tiny_mag_ptr, mag_index_t mag_index)
{
// The entire magazine crossed the "emptiness threshold". Transfer a region
// from this magazine to the Depot. Choose a region that itself has crossed the emptiness threshold (i.e
// is at least fraction "f" empty.) Such a region will be marked "suitable" on the recirculation list.
region_trailer_t *node = tiny_mag_ptr->firstNode;
while (node && (!node->recirc_suitable || node->pinned_to_depot)) {
// If we skip a node due to pinned_to_depot being non-zero, it must be
// because another thread is madvising the same region in
// tiny_madvise_free_range_no_lock(), called from tiny_free_no_lock().
// When that's done, the same thread will enter tiny_free_try_recirc_to_depot()
// for the same region, which will come back here. So this just defers
// recirculation of the region.
node = node->next;
}
if (NULL == node) {
#if DEBUG_MALLOC
malloc_report(ASL_LEVEL_INFO, "*** tiny_free_do_recirc_to_depot end of list\n");
#endif
return TRUE; // Caller must SZONE_MAGAZINE_PTR_UNLOCK(tiny_mag_ptr);
}
region_t sparse_region = TINY_REGION_FOR_PTR(node);
// Deal with unclaimed memory -- mag_bytes_free_at_end or mag_bytes_free_at_start
if (sparse_region == tiny_mag_ptr->mag_last_region &&
(tiny_mag_ptr->mag_bytes_free_at_end || tiny_mag_ptr->mag_bytes_free_at_start)) {
tiny_finalize_region(rack, tiny_mag_ptr);
}
// disconnect "suitable" node from magazine
recirc_list_extract(rack, tiny_mag_ptr, node);
// Iterate the region pulling its free entries off its (locked) magazine's free list
int objects_in_use = tiny_free_detach_region(rack, tiny_mag_ptr, sparse_region);
magazine_t *depot_ptr = &(rack->magazines[DEPOT_MAGAZINE_INDEX]);
// hand over the region to the (locked) Depot
SZONE_MAGAZINE_PTR_LOCK(depot_ptr);
// this will cause tiny_free_list_add_ptr called by tiny_free_reattach_region to use
// the depot as its target magazine, rather than magazine formerly associated with sparse_region
MAGAZINE_INDEX_FOR_TINY_REGION(sparse_region) = DEPOT_MAGAZINE_INDEX;
node->pinned_to_depot = 0;
// Iterate the region putting its free entries on Depot's free list
size_t bytes_inplay = tiny_free_reattach_region(rack, depot_ptr, sparse_region);
tiny_mag_ptr->mag_num_bytes_in_objects -= bytes_inplay;
tiny_mag_ptr->num_bytes_in_magazine -= TINY_REGION_PAYLOAD_BYTES;
tiny_mag_ptr->mag_num_objects -= objects_in_use;
SZONE_MAGAZINE_PTR_UNLOCK(tiny_mag_ptr); // Unlock the originating magazine
depot_ptr->mag_num_bytes_in_objects += bytes_inplay;
depot_ptr->num_bytes_in_magazine += TINY_REGION_PAYLOAD_BYTES;
depot_ptr->mag_num_objects += objects_in_use;
// connect to Depot as last node
recirc_list_splice_last(rack, depot_ptr, node);
MAGMALLOC_RECIRCREGION(TINY_SZONE_FROM_RACK(rack), (int)mag_index, (void *)sparse_region, TINY_REGION_SIZE,
(int)BYTES_USED_FOR_TINY_REGION(sparse_region)); // DTrace USDT Probe
#if !CONFIG_AGGRESSIVE_MADVISE
// Mark free'd dirty pages with MADV_FREE to reduce memory pressure
tiny_free_scan_madvise_free(rack, depot_ptr, sparse_region);
#endif
// If the region is entirely empty vm_deallocate() it outside the depot lock
region_t r_dealloc = tiny_free_try_depot_unmap_no_lock(rack, depot_ptr, node);
SZONE_MAGAZINE_PTR_UNLOCK(depot_ptr);
if (r_dealloc) {
mvm_deallocate_pages(r_dealloc, TINY_REGION_SIZE, 0);
}
return FALSE; // Caller need not unlock the originating magazine
}
static MALLOC_INLINE boolean_t
tiny_free_try_recirc_to_depot(rack_t *rack,
magazine_t *tiny_mag_ptr,
mag_index_t mag_index,
region_t region,
void *headptr,
size_t headsize,
void *ptr,
msize_t msize)
{
region_trailer_t *node = REGION_TRAILER_FOR_TINY_REGION(region);
size_t bytes_used = node->bytes_used;
/* FIXME: Would Uniprocessor benefit from recirc and MADV_FREE? */
if (rack->num_magazines == 1) { // Uniprocessor, single magazine, so no recirculation necessary
/* NOTHING */
return TRUE; // Caller must do SZONE_MAGAZINE_PTR_UNLOCK(tiny_mag_ptr)
} else if (DEPOT_MAGAZINE_INDEX != mag_index) {
// Emptiness discriminant
if (bytes_used < DENSITY_THRESHOLD(TINY_REGION_PAYLOAD_BYTES)) {
/* Region has crossed threshold from density to sparsity. Mark it "suitable" on the
* recirculation candidates list. */
node->recirc_suitable = TRUE;
} else {
/* After this free, we've found the region is still dense, so it must have been even more so before
* the free. That implies the region is already correctly marked. Do nothing. */
}
// Has the entire magazine crossed the "emptiness threshold"? If so, transfer a region
// from this magazine to the Depot. Choose a region that itself has crossed the emptiness threshold (i.e
// is at least fraction "f" empty.) Such a region will be marked "suitable" on the recirculation list.
size_t a = tiny_mag_ptr->num_bytes_in_magazine; // Total bytes allocated to this magazine
size_t u = tiny_mag_ptr->mag_num_bytes_in_objects; // In use (malloc'd) from this magaqzine
if (a - u > ((3 * TINY_REGION_PAYLOAD_BYTES) / 2) && u < DENSITY_THRESHOLD(a)) {
return tiny_free_do_recirc_to_depot(rack, tiny_mag_ptr, mag_index);
}
} else {
#if !CONFIG_AGGRESSIVE_MADVISE
// We are free'ing into the depot, so madvise as we do so unless we were madvising every incoming
// allocation anyway.
tiny_madvise_free_range_no_lock(rack, tiny_mag_ptr, region, headptr, headsize, ptr, msize);
#endif
if (0 < bytes_used || 0 < node->pinned_to_depot) {
/* Depot'd region is still live. Leave it in place on the Depot's recirculation list
* so as to avoid thrashing between the Depot's free list and a magazines's free list
* with detach_region/reattach_region */
} else {
/* Depot'd region is just now empty. Consider return to OS. */
region_t r_dealloc = tiny_free_try_depot_unmap_no_lock(rack, tiny_mag_ptr, node);
SZONE_MAGAZINE_PTR_UNLOCK(tiny_mag_ptr);
if (r_dealloc) {
mvm_deallocate_pages(r_dealloc, TINY_REGION_SIZE, 0);
}
return FALSE; // Caller need not unlock
}
}
return TRUE; // Caller must do SZONE_MAGAZINE_PTR_UNLOCK(tiny_mag_ptr)
}
#endif // CONFIG_RECIRC_DEPOT
boolean_t
tiny_free_no_lock(rack_t *rack, magazine_t *tiny_mag_ptr, mag_index_t mag_index, region_t region, void *ptr, msize_t msize)
{
void *original_ptr = ptr;
size_t original_size = TINY_BYTES_FOR_MSIZE(msize);
void *next_block = ((unsigned char *)ptr + original_size);
msize_t previous_msize, next_msize;
void *previous;
tiny_free_list_t *big_free_block;
tiny_free_list_t *after_next_block;
tiny_free_list_t *before_next_block;
#if DEBUG_MALLOC
if (LOG(szone, ptr)) {
malloc_report(ASL_LEVEL_INFO, "in tiny_free_no_lock(), ptr=%p, msize=%d\n", ptr, msize);
}
if (!msize) {
malloc_zone_error(rack->debug_flags, true,
"trying to free tiny block that is too small in tiny_free_no_lock(), ptr=%p, msize=%d\n",
ptr, msize);
}
#endif
// We try to coalesce this block with the preceeding one
previous = tiny_previous_preceding_free(ptr, &previous_msize);
if (previous) {
#if DEBUG_MALLOC
if (LOG(szone, ptr) || LOG(szone, previous)) {
malloc_report(ASL_LEVEL_INFO, "in tiny_free_no_lock(), coalesced backwards for %p previous=%p\n", ptr, previous);
}
#endif
// clear the meta_header since this is no longer the start of a block
set_tiny_meta_header_middle(ptr);
tiny_free_list_remove_ptr(rack, tiny_mag_ptr, previous, previous_msize);
ptr = previous;
msize += previous_msize;
}
// We try to coalesce with the next block
if ((next_block < TINY_REGION_END(region)) && tiny_meta_header_is_free(next_block)) {
next_msize = get_tiny_free_size(next_block);
#if DEBUG_MALLOC
if (LOG(szone, ptr) || LOG(szone, next_block)) {
malloc_report(ASL_LEVEL_INFO, "in tiny_free_no_lock(), for ptr=%p, msize=%d coalesced forward=%p next_msize=%d\n", ptr, msize,
next_block, next_msize);
}
#endif
// If we are coalescing with the next block, and the next block is in
// the last slot of the free list, then we optimize this case here to
// avoid removing next_block from the slot (NUM_TINY_SLOTS - 1) and then adding ptr back
// to slot (NUM_TINY_SLOTS - 1).
if (next_msize >= NUM_TINY_SLOTS) {
msize += next_msize;
big_free_block = (tiny_free_list_t *)next_block;
after_next_block = free_list_unchecksum_ptr(rack, &big_free_block->next);
before_next_block = free_list_unchecksum_ptr(rack, &big_free_block->previous);
if (!before_next_block) {
tiny_mag_ptr->mag_free_list[NUM_TINY_SLOTS - 1].p = ptr;
} else {
before_next_block->next.u = free_list_checksum_ptr(rack, ptr);
}
if (after_next_block) {
after_next_block->previous.u = free_list_checksum_ptr(rack, ptr);
}
// we don't need to checksum these since they are already checksummed
((tiny_free_list_t *)ptr)->previous = big_free_block->previous;
((tiny_free_list_t *)ptr)->next = big_free_block->next;
// clear the meta_header to enable coalescing backwards
set_tiny_meta_header_middle(big_free_block);
set_tiny_meta_header_free(ptr, msize);
goto tiny_free_ending;
}
tiny_free_list_remove_ptr(rack, tiny_mag_ptr, next_block, next_msize);
set_tiny_meta_header_middle(next_block); // clear the meta_header to enable coalescing backwards
msize += next_msize;
}
// The tiny cache already scribbles free blocks as they go through the
// cache whenever msize < TINY_QUANTUM , so we do not need to do it here.
if ((rack->debug_flags & MALLOC_DO_SCRIBBLE) && msize && (msize >= TINY_QUANTUM)) {
memset(ptr, SCRABBLE_BYTE, TINY_BYTES_FOR_MSIZE(msize));
}
tiny_free_list_add_ptr(rack, tiny_mag_ptr, ptr, msize);
tiny_free_ending:
tiny_mag_ptr->mag_num_objects--;
// we use original_size and not msize to avoid double counting the coalesced blocks
tiny_mag_ptr->mag_num_bytes_in_objects -= original_size;
// Update this region's bytes in use count
region_trailer_t *node = REGION_TRAILER_FOR_TINY_REGION(region);
size_t bytes_used = node->bytes_used - original_size;
node->bytes_used = (unsigned int)bytes_used;
#if CONFIG_AGGRESSIVE_MADVISE
// Platforms that want to madvise every freed allocation do so here, even if we continue
// on to use the recirc depot after.
tiny_madvise_free_range_no_lock(rack, tiny_mag_ptr, region, original_ptr, original_size, ptr, msize);
#endif
// Caller must do SZONE_MAGAZINE_PTR_UNLOCK(tiny_mag_ptr) if this function
// returns TRUE.
boolean_t needs_unlock = TRUE;
#if CONFIG_RECIRC_DEPOT
needs_unlock = tiny_free_try_recirc_to_depot(rack, tiny_mag_ptr, mag_index, region, original_ptr, original_size, ptr, msize);
#endif
return needs_unlock;
}
// Allocates from the last region or a freshly allocated region
static void *
tiny_malloc_from_region_no_lock(rack_t *rack,
magazine_t *tiny_mag_ptr,
mag_index_t mag_index,
msize_t msize,
void *aligned_address)
{
void *ptr;
// Deal with unclaimed memory -- mag_bytes_free_at_end or mag_bytes_free_at_start
if (tiny_mag_ptr->mag_bytes_free_at_end || tiny_mag_ptr->mag_bytes_free_at_start) {
tiny_finalize_region(rack, tiny_mag_ptr);
}
// We set the unused bits of the header in the last pair to be all ones, and those of the inuse to zeroes.
#if NUM_TINY_BLOCKS & 31
const uint32_t header = 0xFFFFFFFFU << (NUM_TINY_BLOCKS & 31);
#else
const uint32_t header = 0;
#endif
((tiny_region_t)aligned_address)->pairs[CEIL_NUM_TINY_BLOCKS_WORDS - 1].header = header;
((tiny_region_t)aligned_address)->pairs[CEIL_NUM_TINY_BLOCKS_WORDS - 1].inuse = 0;
// Tag the region at "aligned_address" as belonging to us,
// and so put it under the protection of the magazine lock we are holding.
// Do this before advertising "aligned_address" on the hash ring(!)
MAGAZINE_INDEX_FOR_TINY_REGION(aligned_address) = mag_index;
// Insert the new region into the hash ring
rack_region_insert(rack, (region_t)aligned_address);
tiny_mag_ptr->mag_last_region = aligned_address;
BYTES_USED_FOR_TINY_REGION(aligned_address) = TINY_BYTES_FOR_MSIZE(msize);
#if CONFIG_ASLR_INTERNAL
int offset_msize = malloc_entropy[0] & TINY_ENTROPY_MASK;
#if DEBUG_MALLOC
if (getenv("MallocASLRForce")) {
offset_msize = strtol(getenv("MallocASLRForce"), NULL, 0) & TINY_ENTROPY_MASK;
}
if (getenv("MallocASLRPrint")) {
malloc_report(ASL_LEVEL_INFO, "Region: %p offset: %d\n", aligned_address, offset_msize);
}
#endif
#else
int offset_msize = 0;
#endif
ptr = (void *)((uintptr_t)aligned_address + TINY_BYTES_FOR_MSIZE(offset_msize));
set_tiny_meta_header_in_use(ptr, msize);
tiny_mag_ptr->mag_num_objects++;
tiny_mag_ptr->mag_num_bytes_in_objects += TINY_BYTES_FOR_MSIZE(msize);
tiny_mag_ptr->num_bytes_in_magazine += TINY_REGION_PAYLOAD_BYTES;
// We put a header on the last block so that it appears in use (for coalescing, etc...)
set_tiny_meta_header_in_use_1((void *)((uintptr_t)ptr + TINY_BYTES_FOR_MSIZE(msize)));
tiny_mag_ptr->mag_bytes_free_at_end = TINY_BYTES_FOR_MSIZE(NUM_TINY_BLOCKS - msize - offset_msize);
#if CONFIG_ASLR_INTERNAL
// Put a header on the previous block for same reason
tiny_mag_ptr->mag_bytes_free_at_start = TINY_BYTES_FOR_MSIZE(offset_msize);
if (offset_msize) {
set_tiny_meta_header_in_use_1((void *)((uintptr_t)ptr - TINY_QUANTUM));
}
#else
tiny_mag_ptr->mag_bytes_free_at_start = 0;
#endif
// connect to magazine as last node
recirc_list_splice_last(rack, tiny_mag_ptr, REGION_TRAILER_FOR_TINY_REGION(aligned_address));
#if DEBUG_MALLOC
if (LOG(szone, ptr)) {
malloc_report(ASL_LEVEL_INFO, "in tiny_malloc_from_region_no_lock(), ptr=%p, msize=%d\n", ptr, msize);
}
#endif
return ptr;
}
void *
tiny_memalign(szone_t *szone, size_t alignment, size_t size, size_t span)
{
msize_t mspan = TINY_MSIZE_FOR_BYTES(span + TINY_QUANTUM - 1);
void *p = tiny_malloc_should_clear(&szone->tiny_rack, mspan, 0);
if (NULL == p) {
return NULL;
}
size_t offset = ((uintptr_t)p) & (alignment - 1); // p % alignment
size_t pad = (0 == offset) ? 0 : alignment - offset; // p + pad achieves desired alignment
msize_t msize = TINY_MSIZE_FOR_BYTES(size + TINY_QUANTUM - 1);
msize_t mpad = TINY_MSIZE_FOR_BYTES(pad + TINY_QUANTUM - 1);
msize_t mwaste = mspan - msize - mpad; // excess blocks
if (mpad > 0) {
void *q = (void *)(((uintptr_t)p) + pad);
// Mark q as a block header and in-use, thus creating two blocks.
magazine_t *tiny_mag_ptr = mag_lock_zine_for_region_trailer(szone->tiny_rack.magazines,
REGION_TRAILER_FOR_TINY_REGION(TINY_REGION_FOR_PTR(p)),
MAGAZINE_INDEX_FOR_TINY_REGION(TINY_REGION_FOR_PTR(p)));
set_tiny_meta_header_in_use(q, msize);
tiny_mag_ptr->mag_num_objects++;
// set_tiny_meta_header_in_use() "reaffirms" the block_header on the *following* block, so
// now set its in_use bit as well. But only if its within the original allocation made above.
if (mwaste > 0) {
BITARRAY_SET(TINY_INUSE_FOR_HEADER(TINY_BLOCK_HEADER_FOR_PTR(q)), TINY_INDEX_FOR_PTR(q) + msize);
}
SZONE_MAGAZINE_PTR_UNLOCK(tiny_mag_ptr);
// Give up mpad blocks beginning at p to the tiny free list
free_tiny(&szone->tiny_rack, p, TINY_REGION_FOR_PTR(p), TINY_BYTES_FOR_MSIZE(mpad));
p = q; // advance p to the desired alignment
}
if (mwaste > 0) {
void *q = (void *)(((uintptr_t)p) + TINY_BYTES_FOR_MSIZE(msize));
// Mark q as block header and in-use, thus creating two blocks.
magazine_t *tiny_mag_ptr = mag_lock_zine_for_region_trailer(szone->tiny_rack.magazines,
REGION_TRAILER_FOR_TINY_REGION(TINY_REGION_FOR_PTR(p)),
MAGAZINE_INDEX_FOR_TINY_REGION(TINY_REGION_FOR_PTR(p)));
set_tiny_meta_header_in_use(q, mwaste);
tiny_mag_ptr->mag_num_objects++;
SZONE_MAGAZINE_PTR_UNLOCK(tiny_mag_ptr);
// Give up mwaste blocks beginning at q to the tiny free list
free_tiny(&szone->tiny_rack, q, TINY_REGION_FOR_PTR(q), TINY_BYTES_FOR_MSIZE(mwaste));
}
return p; // p has the desired size and alignment, and can later be free()'d
}
boolean_t
tiny_claimed_address(rack_t *rack, void *ptr)
{
region_t r = tiny_region_for_ptr_no_lock(rack, ptr);
return r && ptr < TINY_REGION_END(r);
}
void *
tiny_try_shrink_in_place(rack_t *rack, void *ptr, size_t old_size, size_t new_good_size)
{
msize_t new_msize = TINY_MSIZE_FOR_BYTES(new_good_size);
msize_t mshrinkage = TINY_MSIZE_FOR_BYTES(old_size) - new_msize;
if (mshrinkage) {
void *q = (void *)((uintptr_t)ptr + TINY_BYTES_FOR_MSIZE(new_msize));
magazine_t *tiny_mag_ptr = mag_lock_zine_for_region_trailer(rack->magazines,
REGION_TRAILER_FOR_TINY_REGION(TINY_REGION_FOR_PTR(ptr)),
MAGAZINE_INDEX_FOR_TINY_REGION(TINY_REGION_FOR_PTR(ptr)));
// Mark q as block header and in-use, thus creating two blocks.
set_tiny_meta_header_in_use(q, mshrinkage);
tiny_mag_ptr->mag_num_objects++;
SZONE_MAGAZINE_PTR_UNLOCK(tiny_mag_ptr);
free_tiny(rack, q, TINY_REGION_FOR_PTR(q), 0);
}
return ptr;
}
boolean_t
tiny_try_realloc_in_place(rack_t *rack, void *ptr, size_t old_size, size_t new_size)
{
// returns 1 on success
msize_t index;
msize_t old_msize;
unsigned next_index;
void *next_block;
boolean_t is_free;
msize_t next_msize, coalesced_msize, leftover_msize, new_msize;
void *leftover;
index = TINY_INDEX_FOR_PTR(ptr);
old_msize = TINY_MSIZE_FOR_BYTES(old_size);
new_msize = TINY_MSIZE_FOR_BYTES(new_size + TINY_QUANTUM - 1);
next_index = index + old_msize;
if (next_index >= NUM_TINY_BLOCKS) {
return 0;
}
next_block = (char *)ptr + old_size;
magazine_t *tiny_mag_ptr = mag_lock_zine_for_region_trailer(rack->magazines,
REGION_TRAILER_FOR_TINY_REGION(TINY_REGION_FOR_PTR(ptr)),
MAGAZINE_INDEX_FOR_TINY_REGION(TINY_REGION_FOR_PTR(ptr)));
if (DEPOT_MAGAZINE_INDEX == MAGAZINE_INDEX_FOR_TINY_REGION(TINY_REGION_FOR_PTR(ptr))) {
SZONE_MAGAZINE_PTR_UNLOCK(tiny_mag_ptr);
return 0;
}
coalesced_msize = new_msize - old_msize;
#if CONFIG_TINY_CACHE
void *last_free_ptr = tiny_mag_ptr->mag_last_free;
msize_t last_free_msize = tiny_mag_ptr->mag_last_free_msize;
if (last_free_ptr == next_block && old_msize + last_free_msize >= new_msize) {
/*
* There is a block in mag_last_free and it's immediately after
* this block and it's large enough. We can use some or all of it.
*/
leftover_msize = last_free_msize - coalesced_msize;
if (leftover_msize) {
tiny_mag_ptr->mag_last_free_msize -= coalesced_msize;
tiny_mag_ptr->mag_last_free += new_size - old_size;
// The block in mag_last_free is still marked as header and in-use, so copy that
// state to the block that remains. The state for the block that we're going to
// use is adjusted by the set_tiny_meta_header_middle() call below.
set_tiny_meta_header_in_use(next_block + TINY_BYTES_FOR_MSIZE(coalesced_msize), leftover_msize);
} else {
// Using the whole block.
tiny_mag_ptr->mag_last_free = NULL;
tiny_mag_ptr->mag_last_free_msize = 0;
tiny_mag_ptr->mag_last_free_rgn = NULL;
}
set_tiny_meta_header_middle(next_block);
} else {
#endif // CONFIG_TINY_CACHE
/*
* Try to expand into unused space immediately after this block.
*/
msize_t unused_msize = TINY_MSIZE_FOR_BYTES(tiny_mag_ptr->mag_bytes_free_at_end);
void *unused_start = TINY_REGION_END(TINY_REGION_FOR_PTR(ptr)) - tiny_mag_ptr->mag_bytes_free_at_end;
if (tiny_mag_ptr->mag_last_region == TINY_REGION_FOR_PTR(ptr)
&& coalesced_msize < unused_msize && unused_start == ptr + old_size) {
// The block at the start of mag_bytes_free_at_end is marked as
// header/in-use and the next one has header/free. We need to
// reset both the header and in-use bit in the first block and we
// need to reset the header bit in the second block if it's part of
// the new allocation.
set_tiny_meta_header_middle(unused_start);
if (coalesced_msize > 1) {
set_tiny_meta_header_middle(unused_start + TINY_QUANTUM);
}
tiny_mag_ptr->mag_bytes_free_at_end -= TINY_BYTES_FOR_MSIZE(coalesced_msize);
if (tiny_mag_ptr->mag_bytes_free_at_end) {
// Mark the first block of the remaining free area as a header and in-use.
set_tiny_meta_header_in_use_1(ptr + TINY_BYTES_FOR_MSIZE(new_msize));
}
} else {
/*
* Look for a free block immediately afterwards. If it's large
* enough, we can consume (part of) it.
*/
is_free = tiny_meta_header_is_free(next_block);
if (!is_free) {
SZONE_MAGAZINE_PTR_UNLOCK(tiny_mag_ptr);
return 0; // next_block is in use;
}
next_msize = get_tiny_free_size(next_block);
if (old_msize + next_msize < new_msize) {
SZONE_MAGAZINE_PTR_UNLOCK(tiny_mag_ptr);
return 0; // even with next block, not enough
}
/*
* The following block is big enough; pull it from its freelist and chop off enough to satisfy
* our needs.
*/
tiny_free_list_remove_ptr(rack, tiny_mag_ptr, next_block, next_msize);
set_tiny_meta_header_middle(next_block); // clear the meta_header to enable coalescing backwards
leftover_msize = next_msize - coalesced_msize;
if (leftover_msize) {
/* there's some left, so put the remainder back */
leftover = (void *)((uintptr_t)next_block + TINY_BYTES_FOR_MSIZE(coalesced_msize));
tiny_free_list_add_ptr(rack, tiny_mag_ptr, leftover, leftover_msize);
}
set_tiny_meta_header_in_use(ptr, old_msize + coalesced_msize);
}
#if CONFIG_TINY_CACHE
}
#endif // CONFIG_TINY_CACHE
#if DEBUG_MALLOC
if (LOG(szone, ptr)) {
malloc_report(ASL_LEVEL_INFO, "in tiny_try_realloc_in_place(), ptr=%p, msize=%d\n", ptr, old_msize + coalesced_msize);
}
#endif
tiny_mag_ptr->mag_num_bytes_in_objects += TINY_BYTES_FOR_MSIZE(coalesced_msize);
// Update this region's bytes in use count
region_trailer_t *node = REGION_TRAILER_FOR_TINY_REGION(TINY_REGION_FOR_PTR(ptr));
size_t bytes_used = node->bytes_used + TINY_BYTES_FOR_MSIZE(coalesced_msize);
node->bytes_used = (unsigned int)bytes_used;
// Emptiness discriminant
if (bytes_used < DENSITY_THRESHOLD(TINY_REGION_PAYLOAD_BYTES)) {
/* After this reallocation the region is still sparse, so it must have been even more so before
* the reallocation. That implies the region is already correctly marked. Do nothing. */
} else {
/* Region has crossed threshold from sparsity to density. Mark it not "suitable" on the
* recirculation candidates list. */
node->recirc_suitable = FALSE;
}
SZONE_MAGAZINE_PTR_UNLOCK(tiny_mag_ptr);
CHECK(szone, __PRETTY_FUNCTION__);
return 1;
}
static char *tiny_check_fail_msg = "*** check: incorrect tiny region ";
#define TINY_CHECK_FAIL(fmt, ...) \
malloc_zone_check_fail(tiny_check_fail_msg, \
"%ld, counter=%d\n" fmt, region_index, counter, __VA_ARGS__);
boolean_t
tiny_check_region(rack_t *rack, region_t region, size_t region_index,
unsigned counter)
{
uintptr_t start, ptr, region_end;
boolean_t prev_free = 0;
boolean_t is_free;
msize_t msize;
tiny_free_list_t *free_head;
void *follower, *previous, *next;
mag_index_t mag_index = MAGAZINE_INDEX_FOR_TINY_REGION(region);
magazine_t *tiny_mag_ptr = &(rack->magazines[mag_index]);
// Assumes locked
CHECK_MAGAZINE_PTR_LOCKED(szone, tiny_mag_ptr, __PRETTY_FUNCTION__);
// Do not check the region if pinned_to_depot is not zero because it
// may not be in a consistent state (specifically, if may have a
// block marked as in-use that's longer than any legal allocation,
// which upsets get_tiny_meta_header() because it can't determine the
// block's length).
if (!REGION_TRAILER_FOR_TINY_REGION(region)->pinned_to_depot) {
return 1;
}
/* establish region limits */
start = (uintptr_t)TINY_REGION_ADDRESS(region);
ptr = start;
if (region == tiny_mag_ptr->mag_last_region) {
ptr += tiny_mag_ptr->mag_bytes_free_at_start;
/*
* Check the leading block's integrity here also.
*/
if (tiny_mag_ptr->mag_bytes_free_at_start) {
msize = get_tiny_meta_header((void *)(ptr - TINY_QUANTUM), &is_free);
if (is_free || (msize != 1)) {
TINY_CHECK_FAIL("*** invariant broken for leader block %p - %d %d\n",
(void *)(ptr - TINY_QUANTUM), msize, is_free);
return 0;
}
}
}
region_end = (uintptr_t)TINY_REGION_END(region);
/*
* The last region may have a trailing chunk which has not been converted into inuse/freelist
* blocks yet.
*/
if (region == tiny_mag_ptr->mag_last_region) {
region_end -= tiny_mag_ptr->mag_bytes_free_at_end;
}
/*
* Scan blocks within the region.
*/
while (ptr < region_end) {
/*
* If the first block is free, and its size is 65536 (msize = 0) then the entire region is
* free.
*/
msize = get_tiny_meta_header((void *)ptr, &is_free);
if (is_free && !msize && (ptr == start)) {
return 1;
}
/*
* If the block's size is 65536 (msize = 0) then since we're not the first entry the size is
* corrupt.
*/
if (!msize) {
TINY_CHECK_FAIL("*** invariant broken for tiny block %p this msize=%d - size is too small\n", (void *)ptr, msize);
return 0;
}
if (!is_free) {
/*
* In use blocks cannot be more than (NUM_TINY_SLOTS - 1) quanta large.
*/
prev_free = 0;
if (msize > (NUM_TINY_SLOTS - 1)) {
TINY_CHECK_FAIL("*** invariant broken for %p this tiny msize=%d - size is too large\n", (void *)ptr, msize);
return 0;
}
/* move to next block */
ptr += TINY_BYTES_FOR_MSIZE(msize);
} else {
#if !CONFIG_RELAXED_INVARIANT_CHECKS
/*
* Free blocks must have been coalesced, we cannot have a free block following another
* free block.
*/
if (prev_free) {
TINY_CHECK_FAIL("*** invariant broken for free block %p this tiny msize=%d: two free blocks in a row\n", (void *)ptr, msize);
return 0;
}
#endif // CONFIG_RELAXED_INVARIANT_CHECKS
prev_free = 1;
/*
* Check the integrity of this block's entry in its freelist.
*/
free_head = (tiny_free_list_t *)ptr;
previous = free_list_unchecksum_ptr(rack, &free_head->previous);
next = free_list_unchecksum_ptr(rack, &free_head->next);
if (previous && !tiny_meta_header_is_free(previous)) {
TINY_CHECK_FAIL("*** invariant broken for %p (previous %p is not a free pointer)\n", (void *)ptr, previous);
return 0;
}
if (next && !tiny_meta_header_is_free(next)) {
TINY_CHECK_FAIL("*** invariant broken for %p (next in free list %p is not a free pointer)\n", (void *)ptr, next);
return 0;
}
/*
* Check the free block's trailing size value.
*/
follower = FOLLOWING_TINY_PTR(ptr, msize);
if (((uintptr_t)follower != region_end) && (get_tiny_previous_free_msize(follower) != msize)) {
TINY_CHECK_FAIL("*** invariant broken for tiny free %p followed by %p in region [%p-%p] "
"(end marker incorrect) should be %d; in fact %d\n",
(void *)ptr, follower, TINY_REGION_ADDRESS(region), (void *)region_end,
msize, get_tiny_previous_free_msize(follower));
return 0;
}
/* move to next block */
ptr = (uintptr_t)follower;
}
}
/*
* Ensure that we scanned the entire region
*/
if (ptr != region_end) {
TINY_CHECK_FAIL("*** invariant broken for region end %p - %p\n", (void *)ptr, (void *)region_end);
return 0;
}
/*
* Check the trailing block's integrity.
*/
if (region == tiny_mag_ptr->mag_last_region) {
if (tiny_mag_ptr->mag_bytes_free_at_end) {
msize = get_tiny_meta_header((void *)ptr, &is_free);
if (is_free || (msize != 1)) {
TINY_CHECK_FAIL("*** invariant broken for blocker block %p - %d %d\n", (void *)ptr, msize, is_free);
return 0;
}
}
}
return 1;
}
kern_return_t
tiny_in_use_enumerator(task_t task,
void *context,
unsigned type_mask,
szone_t *szone,
memory_reader_t reader,
vm_range_recorder_t recorder)
{
size_t num_regions;
size_t index;
region_t *regions;
vm_range_t buffer[MAX_RECORDER_BUFFER];
unsigned count = 0;
kern_return_t err;
region_t region;
vm_range_t range;
vm_range_t admin_range;
vm_range_t ptr_range;
unsigned char *mapped_region;
uint32_t *block_header;
uint32_t *in_use;
unsigned block_index;
unsigned block_limit;
boolean_t is_free;
msize_t msize;
void *mapped_ptr;
unsigned bit;
magazine_t *tiny_mag_base = NULL;
region_hash_generation_t *trg_ptr;
err = reader(task, (vm_address_t)szone->tiny_rack.region_generation, sizeof(region_hash_generation_t), (void **)&trg_ptr);
if (err) {
return err;
}
num_regions = trg_ptr->num_regions_allocated;
err = reader(task, (vm_address_t)trg_ptr->hashed_regions, sizeof(region_t) * num_regions, (void **)®ions);
if (err) {
return err;
}
if (type_mask & MALLOC_PTR_IN_USE_RANGE_TYPE) {
// Map in all active magazines. Do this outside the iteration over regions.
err = reader(task, (vm_address_t)(szone->tiny_rack.magazines), szone->tiny_rack.num_magazines * sizeof(magazine_t),
(void **)&tiny_mag_base);
if (err) {
return err;
}
}
for (index = 0; index < num_regions; ++index) {
region = regions[index];
if (HASHRING_OPEN_ENTRY != region && HASHRING_REGION_DEALLOCATED != region) {
range.address = (vm_address_t)TINY_REGION_ADDRESS(region);
range.size = (vm_size_t)TINY_REGION_SIZE;
if (type_mask & MALLOC_ADMIN_REGION_RANGE_TYPE) {
admin_range.address = range.address + TINY_METADATA_START;
admin_range.size = TINY_METADATA_SIZE;
recorder(task, context, MALLOC_ADMIN_REGION_RANGE_TYPE, &admin_range, 1);
}
if (type_mask & (MALLOC_PTR_REGION_RANGE_TYPE | MALLOC_ADMIN_REGION_RANGE_TYPE)) {
ptr_range.address = range.address;
ptr_range.size = NUM_TINY_BLOCKS * TINY_QUANTUM;
recorder(task, context, MALLOC_PTR_REGION_RANGE_TYPE, &ptr_range, 1);
}
if (type_mask & MALLOC_PTR_IN_USE_RANGE_TYPE) {
vm_address_t mag_last_free;
msize_t mag_last_free_msize = 0;
err = reader(task, range.address, range.size, (void **)&mapped_region);
if (err) {
return err;
}
mag_index_t mag_index = MAGAZINE_INDEX_FOR_TINY_REGION(mapped_region);
magazine_t *tiny_mag_ptr = tiny_mag_base + mag_index;
if (DEPOT_MAGAZINE_INDEX != mag_index) {
mag_last_free = (uintptr_t)tiny_mag_ptr->mag_last_free;
mag_last_free_msize = tiny_mag_ptr->mag_last_free_msize;
} else {
for (mag_index = 0; mag_index < szone->tiny_rack.num_magazines; mag_index++) {
if ((void *)range.address == (tiny_mag_base + mag_index)->mag_last_free_rgn) {
mag_last_free = (uintptr_t)(tiny_mag_base + mag_index)->mag_last_free;
mag_last_free_msize = (tiny_mag_base + mag_index)->mag_last_free_msize;
}
}
}
block_header = (uint32_t *)(mapped_region + TINY_METADATA_START + sizeof(region_trailer_t));
in_use = TINY_INUSE_FOR_HEADER(block_header);
block_index = 0;
block_limit = NUM_TINY_BLOCKS;
if (region == tiny_mag_ptr->mag_last_region) {
block_index += TINY_MSIZE_FOR_BYTES(tiny_mag_ptr->mag_bytes_free_at_start);
block_limit -= TINY_MSIZE_FOR_BYTES(tiny_mag_ptr->mag_bytes_free_at_end);
}
while (block_index < block_limit) {
vm_size_t block_offset = TINY_BYTES_FOR_MSIZE(block_index);
is_free = !BITARRAY_BIT(in_use, block_index);
if (is_free) {
mapped_ptr = mapped_region + block_offset;
// mapped_region, the address at which 'range' in 'task' has been
// mapped into our process, is not necessarily aligned to
// TINY_BLOCKS_ALIGN.
//
// Since the code in get_tiny_free_size() assumes the pointer came
// from a properly aligned tiny region, and mapped_region is not
// necessarily aligned, then do the size calculation directly.
// If the next bit is set in the header bitmap, then the size is one
// quantum. Otherwise, read the size field.
if (!BITARRAY_BIT(block_header, (block_index + 1))) {
msize = TINY_FREE_SIZE(mapped_ptr);
} else {
msize = 1;
}
} else if (range.address + block_offset != mag_last_free) {
msize = 1;
bit = block_index + 1;
while (!BITARRAY_BIT(block_header, bit)) {
bit++;
msize++;
}
buffer[count].address = range.address + block_offset;
buffer[count].size = TINY_BYTES_FOR_MSIZE(msize);
count++;
if (count >= MAX_RECORDER_BUFFER) {
recorder(task, context, MALLOC_PTR_IN_USE_RANGE_TYPE, buffer, count);
count = 0;
}
} else {
// Block is not free but it matches mag_last_free_ptr so even
// though it is not marked free in the bitmap, we treat it as if
// it is and move on
msize = mag_last_free_msize;
}
if (!msize) {
return KERN_FAILURE; // Somethings amiss. Avoid looping at this block_index.
}
block_index += msize;
}
if (count) {
recorder(task, context, MALLOC_PTR_IN_USE_RANGE_TYPE, buffer, count);
count = 0;
}
}
}
}
return 0;
}
void *
tiny_malloc_from_free_list(rack_t *rack, magazine_t *tiny_mag_ptr, mag_index_t mag_index, msize_t msize)
{
tiny_free_list_t *ptr;
msize_t this_msize;
grain_t slot = msize - 1;
free_list_t *free_list = tiny_mag_ptr->mag_free_list;
free_list_t *the_slot = free_list + slot;
tiny_free_list_t *next;
free_list_t *limit;
#if defined(__LP64__)
uint64_t bitmap;
#else
uint32_t bitmap;
#endif
msize_t leftover_msize;
tiny_free_list_t *leftover_ptr;
// Assumes we've locked the region
CHECK_MAGAZINE_PTR_LOCKED(szone, tiny_mag_ptr, __PRETTY_FUNCTION__);
// Look for an exact match by checking the freelist for this msize.
//
ptr = the_slot->p;
if (ptr) {
next = free_list_unchecksum_ptr(rack, &ptr->next);
if (next) {
next->previous = ptr->previous;
} else {
BITMAPV_CLR(tiny_mag_ptr->mag_bitmap, slot);
}
the_slot->p = next;
this_msize = msize;
#if DEBUG_MALLOC
if (LOG(szone, ptr)) {
malloc_report(ASL_LEVEL_INFO, "in tiny_malloc_from_free_list(), exact match ptr=%p, this_msize=%d\n", ptr, this_msize);
}
#endif
goto return_tiny_alloc;
}
// Mask off the bits representing slots holding free blocks smaller than the
// size we need. If there are no larger free blocks, try allocating from
// the free space at the end of the tiny region.
#if defined(__LP64__)
bitmap = ((uint64_t *)(tiny_mag_ptr->mag_bitmap))[0] & ~((1ULL << slot) - 1);
#else
bitmap = tiny_mag_ptr->mag_bitmap[0] & ~((1 << slot) - 1);
#endif
if (!bitmap) {
goto try_tiny_malloc_from_end;
}
slot = BITMAPV_CTZ(bitmap);
limit = free_list + NUM_TINY_SLOTS - 1;
free_list += slot;
if (free_list < limit) {
ptr = free_list->p;
if (ptr) {
next = free_list_unchecksum_ptr(rack, &ptr->next);
free_list->p = next;
if (next) {
next->previous = ptr->previous;
} else {
BITMAPV_CLR(tiny_mag_ptr->mag_bitmap, slot);
}
this_msize = get_tiny_free_size(ptr);
goto add_leftover_and_proceed;
}
#if DEBUG_MALLOC
malloc_report(ASL_LEVEL_ERR, "in tiny_malloc_from_free_list(), mag_bitmap out of sync, slot=%d\n", slot);
#endif
}
// We are now looking at the last slot, which contains blocks equal to, or
// due to coalescing of free blocks, larger than (NUM_TINY_SLOTS - 1) * tiny quantum size.
// If the last freelist is not empty, and the head contains a block that is
// larger than our request, then the remainder is put back on the free list.
ptr = limit->p;
if (ptr) {
this_msize = get_tiny_free_size(ptr);
next = free_list_unchecksum_ptr(rack, &ptr->next);
if (this_msize - msize >= NUM_TINY_SLOTS) {
// the leftover will go back to the free list, so we optimize by
// modifying the free list rather than a pop and push of the head
leftover_msize = this_msize - msize;
leftover_ptr = (tiny_free_list_t *)((unsigned char *)ptr + TINY_BYTES_FOR_MSIZE(msize));
limit->p = leftover_ptr;
if (next) {
next->previous.u = free_list_checksum_ptr(rack, leftover_ptr);
}
leftover_ptr->previous = ptr->previous;
leftover_ptr->next = ptr->next;
set_tiny_meta_header_free(leftover_ptr, leftover_msize);
#if DEBUG_MALLOC
if (LOG(szone, ptr)) {
malloc_report(ASL_LEVEL_INFO,
"in tiny_malloc_from_free_list(), last slot ptr=%p, msize=%d this_msize=%d\n", ptr, msize, this_msize);
}
#endif
this_msize = msize;
goto return_tiny_alloc;
}
if (next) {
next->previous = ptr->previous;
}
limit->p = next;
goto add_leftover_and_proceed;
/* NOTREACHED */
}
try_tiny_malloc_from_end:
// Let's see if we can use tiny_mag_ptr->mag_bytes_free_at_end
if (tiny_mag_ptr->mag_bytes_free_at_end >= TINY_BYTES_FOR_MSIZE(msize)) {
ptr = (tiny_free_list_t *)((uintptr_t)TINY_REGION_END(tiny_mag_ptr->mag_last_region) - tiny_mag_ptr->mag_bytes_free_at_end);
tiny_mag_ptr->mag_bytes_free_at_end -= TINY_BYTES_FOR_MSIZE(msize);
if (tiny_mag_ptr->mag_bytes_free_at_end) {
// let's add an in use block after ptr to serve as boundary
set_tiny_meta_header_in_use_1((unsigned char *)ptr + TINY_BYTES_FOR_MSIZE(msize));
}
this_msize = msize;
#if DEBUG_MALLOC
if (LOG(szone, ptr)) {
malloc_report(ASL_LEVEL_INFO, "in tiny_malloc_from_free_list(), from end ptr=%p, msize=%d\n", ptr, msize);
}
#endif
goto return_tiny_alloc;
}
#if CONFIG_ASLR_INTERNAL
// Try from start if nothing left at end
if (tiny_mag_ptr->mag_bytes_free_at_start >= TINY_BYTES_FOR_MSIZE(msize)) {
ptr = (tiny_free_list_t *)(TINY_REGION_ADDRESS(tiny_mag_ptr->mag_last_region) + tiny_mag_ptr->mag_bytes_free_at_start -
TINY_BYTES_FOR_MSIZE(msize));
tiny_mag_ptr->mag_bytes_free_at_start -= TINY_BYTES_FOR_MSIZE(msize);
if (tiny_mag_ptr->mag_bytes_free_at_start) {
// let's add an in use block before ptr to serve as boundary
set_tiny_meta_header_in_use_1((unsigned char *)ptr - TINY_QUANTUM);
}
this_msize = msize;
#if DEBUG_MALLOC
if (LOG(szone, ptr)) {
malloc_report(ASL_LEVEL_INFO, "in tiny_malloc_from_free_list(), from start ptr=%p, msize=%d\n", ptr, msize);
}
#endif
goto return_tiny_alloc;
}
#endif
return NULL;
add_leftover_and_proceed:
if (!this_msize || (this_msize > msize)) {
leftover_msize = this_msize - msize;
leftover_ptr = (tiny_free_list_t *)((unsigned char *)ptr + TINY_BYTES_FOR_MSIZE(msize));
#if DEBUG_MALLOC
if (LOG(szone, ptr)) {
malloc_report(ASL_LEVEL_INFO, "in tiny_malloc_from_free_list(), adding leftover ptr=%p, this_msize=%d\n", ptr, this_msize);
}
#endif
tiny_free_list_add_ptr(rack, tiny_mag_ptr, leftover_ptr, leftover_msize);
this_msize = msize;
}
return_tiny_alloc:
tiny_mag_ptr->mag_num_objects++;
tiny_mag_ptr->mag_num_bytes_in_objects += TINY_BYTES_FOR_MSIZE(this_msize);
// Update this region's bytes in use count
region_trailer_t *node = REGION_TRAILER_FOR_TINY_REGION(TINY_REGION_FOR_PTR(ptr));
size_t bytes_used = node->bytes_used + TINY_BYTES_FOR_MSIZE(this_msize);
node->bytes_used = (unsigned int)bytes_used;
// Emptiness discriminant
if (bytes_used < DENSITY_THRESHOLD(TINY_REGION_PAYLOAD_BYTES)) {
/* After this allocation the region is still sparse, so it must have been even more so before
* the allocation. That implies the region is already correctly marked. Do nothing. */
} else {
/* Region has crossed threshold from sparsity to density. Mark it not "suitable" on the
* recirculation candidates list. */
node->recirc_suitable = FALSE;
}
#if DEBUG_MALLOC
if (LOG(szone, ptr)) {
malloc_report(ASL_LEVEL_INFO, "in tiny_malloc_from_free_list(), ptr=%p, this_msize=%d, msize=%d\n", ptr, this_msize, msize);
}
#endif
if (this_msize > 1) {
set_tiny_meta_header_in_use(ptr, this_msize);
} else {
set_tiny_meta_header_in_use_1(ptr);
}
return ptr;
}
void *
tiny_malloc_should_clear(rack_t *rack, msize_t msize, boolean_t cleared_requested)
{
void *ptr;
mag_index_t mag_index = tiny_mag_get_thread_index() % rack->num_magazines;
magazine_t *tiny_mag_ptr = &(rack->magazines[mag_index]);
MALLOC_TRACE(TRACE_tiny_malloc, (uintptr_t)rack, TINY_BYTES_FOR_MSIZE(msize), (uintptr_t)tiny_mag_ptr, cleared_requested);
#if DEBUG_MALLOC
if (DEPOT_MAGAZINE_INDEX == mag_index) {
malloc_zone_error(rack->debug_flags, true, "malloc called for magazine index -1\n");
return (NULL);
}
if (!msize) {
malloc_zone_error(rack->debug_flags, true, "invariant broken (!msize) in allocation (region)\n");
return (NULL);
}
#endif
SZONE_MAGAZINE_PTR_LOCK(tiny_mag_ptr);
#if CONFIG_TINY_CACHE
ptr = tiny_mag_ptr->mag_last_free;
if (tiny_mag_ptr->mag_last_free_msize == msize) {
// we have a winner
tiny_mag_ptr->mag_last_free = NULL;
tiny_mag_ptr->mag_last_free_msize = 0;
tiny_mag_ptr->mag_last_free_rgn = NULL;
SZONE_MAGAZINE_PTR_UNLOCK(tiny_mag_ptr);
CHECK(szone, __PRETTY_FUNCTION__);
if (cleared_requested) {
memset(ptr, 0, TINY_BYTES_FOR_MSIZE(msize));
}
#if DEBUG_MALLOC
if (LOG(szone, ptr)) {
malloc_report(ASL_LEVEL_INFO, "in tiny_malloc_should_clear(), tiny cache ptr=%p, msize=%d\n", ptr, msize);
}
#endif
return ptr;
}
#endif /* CONFIG_TINY_CACHE */
while (1) {
ptr = tiny_malloc_from_free_list(rack, tiny_mag_ptr, mag_index, msize);
if (ptr) {
SZONE_MAGAZINE_PTR_UNLOCK(tiny_mag_ptr);
CHECK(szone, __PRETTY_FUNCTION__);
if (cleared_requested) {
memset(ptr, 0, TINY_BYTES_FOR_MSIZE(msize));
}
return ptr;
}
if (tiny_get_region_from_depot(rack, tiny_mag_ptr, mag_index, msize)) {
ptr = tiny_malloc_from_free_list(rack, tiny_mag_ptr, mag_index, msize);
if (ptr) {
SZONE_MAGAZINE_PTR_UNLOCK(tiny_mag_ptr);
CHECK(szone, __PRETTY_FUNCTION__);
if (cleared_requested) {
memset(ptr, 0, TINY_BYTES_FOR_MSIZE(msize));
}
return ptr;
}
}
// The magazine is exhausted. A new region (heap) must be allocated to satisfy this call to malloc().
// The allocation, an mmap() system call, will be performed outside the magazine spin locks by the first
// thread that suffers the exhaustion. That thread sets "alloc_underway" and enters a critical section.
// Threads arriving here later are excluded from the critical section, yield the CPU, and then retry the
// allocation. After some time the magazine is resupplied, the original thread leaves with its allocation,
// and retry-ing threads succeed in the code just above.
if (!tiny_mag_ptr->alloc_underway) {
void *fresh_region;
// time to create a new region (do this outside the magazine lock)
tiny_mag_ptr->alloc_underway = TRUE;
OSMemoryBarrier();
SZONE_MAGAZINE_PTR_UNLOCK(tiny_mag_ptr);
fresh_region = mvm_allocate_pages_securely(TINY_REGION_SIZE, TINY_BLOCKS_ALIGN, VM_MEMORY_MALLOC_TINY, rack->debug_flags);
SZONE_MAGAZINE_PTR_LOCK(tiny_mag_ptr);
// DTrace USDT Probe
MAGMALLOC_ALLOCREGION(TINY_SZONE_FROM_RACK(rack), (int)mag_index, fresh_region, TINY_REGION_SIZE);
if (!fresh_region) { // out of memory!
tiny_mag_ptr->alloc_underway = FALSE;
OSMemoryBarrier();
SZONE_MAGAZINE_PTR_UNLOCK(tiny_mag_ptr);
return NULL;
}
ptr = tiny_malloc_from_region_no_lock(rack, tiny_mag_ptr, mag_index, msize, fresh_region);
// we don't clear because this freshly allocated space is pristine
tiny_mag_ptr->alloc_underway = FALSE;
OSMemoryBarrier();
SZONE_MAGAZINE_PTR_UNLOCK(tiny_mag_ptr);
CHECK(szone, __PRETTY_FUNCTION__);
return ptr;
} else {
SZONE_MAGAZINE_PTR_UNLOCK(tiny_mag_ptr);
yield();
SZONE_MAGAZINE_PTR_LOCK(tiny_mag_ptr);
}
}
/* NOTREACHED */
}
size_t
tiny_size(rack_t *rack, const void *ptr)
{
if (tiny_region_for_ptr_no_lock(rack, ptr)) {
if (TINY_INDEX_FOR_PTR(ptr) >= NUM_TINY_BLOCKS) {
return 0;
}
boolean_t is_free;
msize_t msize = get_tiny_meta_header(ptr, &is_free);
if (is_free) {
return 0;
}
#if CONFIG_TINY_CACHE
{
mag_index_t mag_index = MAGAZINE_INDEX_FOR_TINY_REGION(TINY_REGION_FOR_PTR(ptr));
if (DEPOT_MAGAZINE_INDEX != mag_index) {
magazine_t *tiny_mag_ptr = &rack->magazines[mag_index];
if (msize < TINY_QUANTUM && ptr == tiny_mag_ptr->mag_last_free) {
return 0;
}
} else {
for (mag_index = 0; mag_index < rack->num_magazines; mag_index++) {
magazine_t *tiny_mag_ptr = &(rack->magazines[mag_index]);
if (msize < TINY_QUANTUM && ptr == tiny_mag_ptr->mag_last_free) {
return 0;
}
}
}
}
#endif
return TINY_BYTES_FOR_MSIZE(msize);
}
return 0;
}
static MALLOC_NOINLINE void
free_tiny_botch(rack_t *rack, tiny_free_list_t *ptr)
{
mag_index_t mag_index = MAGAZINE_INDEX_FOR_TINY_REGION(TINY_REGION_FOR_PTR(ptr));
magazine_t *tiny_mag_ptr = &(rack->magazines[mag_index]);
SZONE_MAGAZINE_PTR_UNLOCK(tiny_mag_ptr);
malloc_zone_error(rack->debug_flags, true, "Double free of object %p\n", ptr);
}
void
free_tiny(rack_t *rack, void *ptr, region_t tiny_region, size_t known_size)
{
msize_t msize;
boolean_t is_free;
mag_index_t mag_index = MAGAZINE_INDEX_FOR_TINY_REGION(tiny_region);
magazine_t *tiny_mag_ptr = &(rack->magazines[mag_index]);
MALLOC_TRACE(TRACE_tiny_free, (uintptr_t)rack, (uintptr_t)ptr, (uintptr_t)tiny_mag_ptr, known_size);
// ptr is known to be in tiny_region
if (known_size) {
msize = TINY_MSIZE_FOR_BYTES(known_size + TINY_QUANTUM - 1);
} else {
msize = get_tiny_meta_header(ptr, &is_free);
if (is_free) {
free_tiny_botch(rack, ptr);
return;
}
}
#if DEBUG_MALLOC
if (!msize) {
malloc_report(ASL_LEVEL_ERR, "*** free_tiny() block in use is too large: %p\n", ptr);
return;
}
#endif
SZONE_MAGAZINE_PTR_LOCK(tiny_mag_ptr);
#if CONFIG_TINY_CACHE
// Depot does not participate in CONFIG_TINY_CACHE since it can't be directly malloc()'d
if (DEPOT_MAGAZINE_INDEX != mag_index) {
if (msize < TINY_QUANTUM) { // to see if the bits fit in the last 4 bits
void *ptr2 = tiny_mag_ptr->mag_last_free; // Might be NULL
msize_t msize2 = tiny_mag_ptr->mag_last_free_msize;
region_t rgn2 = tiny_mag_ptr->mag_last_free_rgn;
/* check that we don't already have this pointer in the cache */
if (ptr == ptr2) {
free_tiny_botch(rack, ptr);
return;
}
if ((rack->debug_flags & MALLOC_DO_SCRIBBLE) && msize) {
memset(ptr, SCRABBLE_BYTE, TINY_BYTES_FOR_MSIZE(msize));
}
tiny_mag_ptr->mag_last_free = ptr;
tiny_mag_ptr->mag_last_free_msize = msize;
tiny_mag_ptr->mag_last_free_rgn = tiny_region;
if (!ptr2) {
SZONE_MAGAZINE_PTR_UNLOCK(tiny_mag_ptr);
CHECK(szone, __PRETTY_FUNCTION__);
return;
}
msize = msize2;
ptr = ptr2;
tiny_region = rgn2;
}
}
#endif /* CONFIG_TINY_CACHE */
// Now in the time it took to acquire the lock, the region may have migrated
// from one magazine to another. I.e. trailer->mag_index is volatile.
// In which case the magazine lock we obtained (namely magazines[mag_index].mag_lock)
// is stale. If so, keep on tryin' ...
region_trailer_t *trailer = REGION_TRAILER_FOR_TINY_REGION(tiny_region);
mag_index_t refreshed_index;
while (mag_index != (refreshed_index = trailer->mag_index)) { // Note assignment
SZONE_MAGAZINE_PTR_UNLOCK(tiny_mag_ptr);
mag_index = refreshed_index;
tiny_mag_ptr = &(rack->magazines[mag_index]);
SZONE_MAGAZINE_PTR_LOCK(tiny_mag_ptr);
}
if (tiny_free_no_lock(rack, tiny_mag_ptr, mag_index, tiny_region, ptr, msize)) {
SZONE_MAGAZINE_PTR_UNLOCK(tiny_mag_ptr);
}
CHECK(szone, __PRETTY_FUNCTION__);
}
unsigned
tiny_batch_malloc(szone_t *szone, size_t size, void **results, unsigned count)
{
msize_t msize = TINY_MSIZE_FOR_BYTES(size + TINY_QUANTUM - 1);
unsigned found = 0;
mag_index_t mag_index = tiny_mag_get_thread_index() % szone->tiny_rack.num_magazines;
magazine_t *tiny_mag_ptr = &(szone->tiny_rack.magazines[mag_index]);
// make sure to return objects at least one quantum in size
if (!msize) {
msize = 1;
}
CHECK(szone, __PRETTY_FUNCTION__);
// We must lock the zone now, since tiny_malloc_from_free_list assumes that
// the caller has done so.
SZONE_MAGAZINE_PTR_LOCK(tiny_mag_ptr);
// with the zone locked, allocate objects from the free list until all
// sufficiently large objects have been exhausted, or we have met our quota
// of objects to allocate.
while (found < count) {
void *ptr = tiny_malloc_from_free_list(&szone->tiny_rack, tiny_mag_ptr, mag_index, msize);
if (!ptr) {
break;
}
*results++ = ptr;
found++;
}
SZONE_MAGAZINE_PTR_UNLOCK(tiny_mag_ptr);
return found;
}
void
tiny_batch_free(szone_t *szone, void **to_be_freed, unsigned count)
{
unsigned cc = 0;
void *ptr;
region_t tiny_region = NULL;
boolean_t is_free;
msize_t msize;
magazine_t *tiny_mag_ptr = NULL;
mag_index_t mag_index = -1;
// frees all the pointers in to_be_freed
// note that to_be_freed may be overwritten during the process
if (!count) {
return;
}
CHECK(szone, __PRETTY_FUNCTION__);
while (cc < count) {
ptr = to_be_freed[cc];
if (ptr) {
if (NULL == tiny_region || tiny_region != TINY_REGION_FOR_PTR(ptr)) { // region same as last iteration?
if (tiny_mag_ptr) { // non-NULL iff magazine lock taken
SZONE_MAGAZINE_PTR_UNLOCK(tiny_mag_ptr);
tiny_mag_ptr = NULL;
}
tiny_region = tiny_region_for_ptr_no_lock(&szone->tiny_rack, ptr);
if (tiny_region) {
tiny_mag_ptr = mag_lock_zine_for_region_trailer(szone->tiny_rack.magazines,
REGION_TRAILER_FOR_TINY_REGION(tiny_region),
MAGAZINE_INDEX_FOR_TINY_REGION(tiny_region));
mag_index = MAGAZINE_INDEX_FOR_TINY_REGION(tiny_region);
}
}
if (tiny_region) {
// this is a tiny pointer
if (TINY_INDEX_FOR_PTR(ptr) >= NUM_TINY_BLOCKS) {
break; // pointer to metadata; let the standard free deal with it
}
msize = get_tiny_meta_header(ptr, &is_free);
if (is_free) {
break; // a double free; let the standard free deal with it
}
if (!tiny_free_no_lock(&szone->tiny_rack, tiny_mag_ptr, mag_index, tiny_region, ptr, msize)) {
// Arrange to re-acquire magazine lock
tiny_mag_ptr = NULL;
tiny_region = NULL;
}
to_be_freed[cc] = NULL;
} else {
// No region in this zone claims ptr; let the standard free deal with it
break;
}
}
cc++;
}
if (tiny_mag_ptr) {
SZONE_MAGAZINE_PTR_UNLOCK(tiny_mag_ptr);
tiny_mag_ptr = NULL;
}
}
void
print_tiny_free_list(rack_t *rack)
{
tiny_free_list_t *ptr;
_SIMPLE_STRING b = _simple_salloc();
mag_index_t mag_index;
if (b) {
_simple_sappend(b, "tiny free sizes:\n");
for (mag_index = -1; mag_index < rack->num_magazines; mag_index++) {
grain_t slot = 0;
_simple_sprintf(b, "\tMagazine %d: ", mag_index);
while (slot < NUM_TINY_SLOTS) {
ptr = rack->magazines[mag_index].mag_free_list[slot].p;
if (ptr) {
_simple_sprintf(b, "%s%y[%d]; ", (slot == NUM_TINY_SLOTS - 1) ? ">=" : "", (slot + 1) * TINY_QUANTUM,
free_list_count(rack, (free_list_t){ .p = ptr }));
}
slot++;
}
_simple_sappend(b, "\n");
}
malloc_report(MALLOC_REPORT_NOLOG | MALLOC_REPORT_NOPREFIX, "%s\n", _simple_string(b));
_simple_sfree(b);
}
}
void
print_tiny_region(boolean_t verbose, region_t region, size_t bytes_at_start, size_t bytes_at_end)
{
unsigned counts[1024];
unsigned in_use = 0;
uintptr_t start = (uintptr_t)TINY_REGION_ADDRESS(region);
uintptr_t current = start + bytes_at_start;
uintptr_t limit = (uintptr_t)TINY_REGION_END(region) - bytes_at_end;
boolean_t is_free;
msize_t msize;
unsigned ci;
_SIMPLE_STRING b;
uintptr_t pgTot = 0;
if (region == HASHRING_REGION_DEALLOCATED) {
if ((b = _simple_salloc()) != NULL) {
_simple_sprintf(b, "Tiny region [unknown address] was returned to the OS\n");
malloc_report(MALLOC_REPORT_NOLOG | MALLOC_REPORT_NOPREFIX, "%s\n", _simple_string(b));
_simple_sfree(b);
}
return;
}
memset(counts, 0, sizeof(counts));
while (current < limit) {
msize = get_tiny_meta_header((void *)current, &is_free);
if (is_free && !msize && (current == start)) {
// first block is all free
uintptr_t pgLo = round_page_quanta(start + sizeof(tiny_free_list_t) + sizeof(msize_t));
uintptr_t pgHi = trunc_page_quanta(start + TINY_REGION_SIZE - sizeof(msize_t));
if (pgLo < pgHi) {
pgTot += (pgHi - pgLo);
}
break;
}
if (!msize) {
malloc_report(ASL_LEVEL_ERR, "*** error with %p: msize=%d\n", (void *)current, (unsigned)msize);
break;
}
if (!is_free) {
// block in use
if (msize > NUM_TINY_SLOTS) {
malloc_report(ASL_LEVEL_ERR, "*** error at %p msize for in_use is %d\n", (void *)current, msize);
}
if (msize < 1024) {
counts[msize]++;
}
in_use++;
} else {
uintptr_t pgLo = round_page_quanta(current + sizeof(tiny_free_list_t) + sizeof(msize_t));
uintptr_t pgHi = trunc_page_quanta(current + TINY_BYTES_FOR_MSIZE(msize) - sizeof(msize_t));
if (pgLo < pgHi) {
pgTot += (pgHi - pgLo);
}
}
current += TINY_BYTES_FOR_MSIZE(msize);
}
if ((b = _simple_salloc()) != NULL) {
_simple_sprintf(b, "Tiny region [%p-%p, %y] \t", (void *)start, TINY_REGION_END(region), (int)TINY_REGION_SIZE);
_simple_sprintf(b, "Magazine=%d \t", MAGAZINE_INDEX_FOR_TINY_REGION(region));
_simple_sprintf(b, "Allocations in use=%d \t Bytes in use=%ly \t", in_use, BYTES_USED_FOR_TINY_REGION(region));
if (bytes_at_end || bytes_at_start) {
_simple_sprintf(b, "Untouched=%ly ", bytes_at_end + bytes_at_start);
}
if (DEPOT_MAGAZINE_INDEX == MAGAZINE_INDEX_FOR_TINY_REGION(region)) {
_simple_sprintf(b, "Advised MADV_FREE=%ly", pgTot);
} else {
_simple_sprintf(b, "Fragments subject to reclamation=%ly", pgTot);
}
if (verbose && in_use) {
_simple_sappend(b, "\n\tSizes in use: ");
for (ci = 0; ci < 1024; ci++) {
if (counts[ci]) {
_simple_sprintf(b, "%d[%d] ", TINY_BYTES_FOR_MSIZE(ci), counts[ci]);
}
}
}
malloc_report(MALLOC_REPORT_NOLOG | MALLOC_REPORT_NOPREFIX, "%s\n", _simple_string(b));
_simple_sfree(b);
}
}
static char *tiny_freelist_fail_msg = "check: tiny free list incorrect ";
#define TINY_FREELIST_FAIL(fmt, ...) \
malloc_zone_check_fail(tiny_freelist_fail_msg, \
" (slot=%u), counter=%d\n" fmt, slot, counter, __VA_ARGS__);
boolean_t
tiny_free_list_check(rack_t *rack, grain_t slot, unsigned counter)
{
mag_index_t mag_index;
for (mag_index = -1; mag_index < rack->num_magazines; mag_index++) {
magazine_t *tiny_mag_ptr = &(rack->magazines[mag_index]);
SZONE_MAGAZINE_PTR_LOCK(tiny_mag_ptr);
unsigned count = 0;
tiny_free_list_t *ptr = rack->magazines[mag_index].mag_free_list[slot].p;
boolean_t is_free;
tiny_free_list_t *previous = NULL;
while (ptr) {
is_free = tiny_meta_header_is_free(ptr);
if (!is_free) {
TINY_FREELIST_FAIL("*** in-use ptr in free list slot=%u count=%d ptr=%p\n", slot, count, ptr);
SZONE_MAGAZINE_PTR_UNLOCK(tiny_mag_ptr);
return 0;
}
if (((uintptr_t)ptr) & (TINY_QUANTUM - 1)) {
TINY_FREELIST_FAIL("*** unaligned ptr in free list slot=%u count=%d ptr=%p\n", slot, count, ptr);
SZONE_MAGAZINE_PTR_UNLOCK(tiny_mag_ptr);
return 0;
}
if (!tiny_region_for_ptr_no_lock(rack, ptr)) {
TINY_FREELIST_FAIL("*** ptr not in szone slot=%d count=%u ptr=%p\n", slot, count, ptr);
SZONE_MAGAZINE_PTR_UNLOCK(tiny_mag_ptr);
return 0;
}
if (free_list_unchecksum_ptr(rack, &ptr->previous) != previous) {
TINY_FREELIST_FAIL("*** previous incorrectly set slot=%u count=%d ptr=%p\n", slot, count, ptr);
SZONE_MAGAZINE_PTR_UNLOCK(tiny_mag_ptr);
return 0;
}
previous = ptr;
ptr = free_list_unchecksum_ptr(rack, &ptr->next);
count++;
}
SZONE_MAGAZINE_PTR_UNLOCK(tiny_mag_ptr);
}
return 1;
}
================================================
FILE: InterView-obj-isa-class/libmalloc-166.220.1/src/magazine_zone.h
================================================
/*
* Copyright (c) 2015 Apple Inc. All rights reserved.
*
* @APPLE_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apple Public Source License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. Please obtain a copy of the License at
* http://www.opensource.apple.com/apsl/ and read it before using this
* file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPLE_LICENSE_HEADER_END@
*/
#ifndef __MAGAZINE_ZONE_H
#define __MAGAZINE_ZONE_H
/********************* DEFINITIONS ************************/
// Out-of-band free list entry. Out-of-band free list entries are used
// in specific cases where a free-list entry is the *only* data on a given page,
// and the presence of that entry causes the page to stay dirty.
//
// `ptr` is all 16-bit quantum-sized index and packed, as that references a
// block address inside the current region. `next` and `prev` have to be pointer
// sized references, as these values can point to entries outside the current
// region, so it's not safe to compact them.
typedef struct {
uintptr_t prev;
uintptr_t next;
uint16_t ptr;
} MALLOC_PACKED oob_free_entry_s, *oob_free_entry_t;
// In-place free list entry. Unlike the out-of-band entry, the in-place entries
// are stored at the start of the range that has been freed.
typedef struct _inplace_free_entry_s *inplace_free_entry_t;
typedef struct {
void *ptr;
uint8_t checksum;
} inplace_linkage_s;
typedef union {
inplace_free_entry_t p;
uintptr_t u;
} inplace_union;
typedef struct _inplace_free_entry_s {
inplace_union previous;
inplace_union next;
} inplace_free_entry_s, *inplace_free_entry_t;
#ifdef __LP64__
MALLOC_STATIC_ASSERT(sizeof(inplace_free_entry_s) == 16, "inplace free list must be 16-bytes long");
#else
MALLOC_STATIC_ASSERT(sizeof(inplace_free_entry_s) == 8, "inplace free list must be 8-bytes long");
#endif
typedef struct _small_inplace_free_entry_s {
inplace_linkage_s previous;
inplace_linkage_s next;
} small_inplace_free_entry_s, *small_inplace_free_entry_t;
typedef union {
small_inplace_free_entry_t small_inplace;
inplace_free_entry_t inplace;
oob_free_entry_t oob;
void *p;
} free_list_t;
typedef struct {
inplace_union previous;
inplace_union next;
} tiny_free_list_t;
typedef unsigned int grain_t; // N.B. wide enough to index all free slots
typedef int mag_index_t;
#define CHECK_REGIONS (1 << 31)
#define DISABLE_ASLR (1 << 30)
#define MAX_RECORDER_BUFFER 256
/********************* DEFINITIONS for tiny ************************/
/*
* Memory in the Tiny range is allocated from regions (heaps) pointed to by the
* szone's hashed_regions pointer.
*
* Each region is laid out as a heap, followed by a header block, all within
* a 1MB (2^20) block. This means there are 64520 16-byte blocks and the header
* is 16138 bytes, making the total 1048458 bytes, leaving 118 bytes unused.
*
* The header block is arranged as in struct tiny_region defined just below, and
* consists of two bitfields (or bit arrays) interleaved 32 bits by 32 bits.
*
* Each bitfield comprises NUM_TINY_BLOCKS bits, and refers to the corresponding
* TINY_QUANTUM block within the heap.
*
* The bitfields are used to encode the state of memory within the heap. The header bit indicates
* that the corresponding quantum is the first quantum in a block (either in use or free). The
* in-use bit is set for the header if the block has been handed out (allocated). If the header
* bit is not set, the in-use bit is invalid.
*
* The szone maintains an array of NUM_TINY_SLOTS freelists, each of which is used to hold
* free objects of the corresponding quantum size.
*
* A free block is laid out depending on its size, in order to fit all free
* blocks in 16 bytes, on both 32 and 64 bit platforms. One quantum blocks do
* not store their size in the block, instead relying on the header information
* to determine their size. Blocks of two or more quanta have room to store
* their size in the block, and store it both after the 'next' pointer, and in
* the last 2 bytes of the block.
*
* 1-quantum block
* Offset (32-bit mode) (64-bit mode)
* 0x0 0x0 : previous
* 0x4 0x08 : next
* end end
*
* >1-quantum block
* Offset (32-bit mode) (64-bit mode)
* 0x0 0x0 : previous
* 0x4 0x08 : next
* 0x8 0x10 : size (in quantum counts)
* end - 2 end - 2 : size (in quantum counts)
* end end
*
* All fields are pointer-sized, except for the size which is an unsigned short.
*
*/
#define FOLLOWING_TINY_PTR(ptr, msize) (((unsigned char *)(ptr)) + ((msize) << SHIFT_TINY_QUANTUM))
#define TINY_BLOCKS_ALIGN (SHIFT_TINY_CEIL_BLOCKS + SHIFT_TINY_QUANTUM) // 20
#define TINY_ENTROPY_BITS 15
#define TINY_ENTROPY_MASK ((1 << TINY_ENTROPY_BITS) - 1)
/*
* Avoid having so much entropy that the end of a valid tiny allocation
* might overrun the end of the tiny region.
*/
#if TINY_ENTROPY_MASK + NUM_TINY_SLOTS > NUM_TINY_BLOCKS
#error Too many entropy bits for tiny region requested
#endif
/*
* Enough room for the data, followed by the bit arrays (2-bits per block)
* plus rounding to the nearest page.
*/
#define CEIL_NUM_TINY_BLOCKS_WORDS (((NUM_TINY_BLOCKS + 31) & ~31) >> 5)
#define TINY_METADATA_SIZE (sizeof(region_trailer_t) + sizeof(tiny_header_inuse_pair_t) * CEIL_NUM_TINY_BLOCKS_WORDS)
#define TINY_REGION_SIZE ((NUM_TINY_BLOCKS * TINY_QUANTUM + TINY_METADATA_SIZE + PAGE_MAX_SIZE - 1) & ~(PAGE_MAX_SIZE - 1))
#define TINY_METADATA_START (NUM_TINY_BLOCKS * TINY_QUANTUM)
/*
* Beginning and end pointers for a region's heap.
*/
#define TINY_REGION_ADDRESS(region) ((void *)(region))
#define TINY_REGION_END(region) ((void *)(((uintptr_t)(region)) + (NUM_TINY_BLOCKS * TINY_QUANTUM)))
/*
* Locate the heap base for a pointer known to be within a tiny region.
*/
#define TINY_REGION_FOR_PTR(_p) ((void *)((uintptr_t)(_p) & ~((1 << TINY_BLOCKS_ALIGN) - 1)))
/*
* Convert between byte and msize units.
*/
#define TINY_BYTES_FOR_MSIZE(_m) ((_m) << SHIFT_TINY_QUANTUM)
#define TINY_MSIZE_FOR_BYTES(_b) ((_b) >> SHIFT_TINY_QUANTUM)
#if MALLOC_TARGET_64BIT
#define TINY_FREE_SIZE(ptr) (((msize_t *)(ptr))[8])
#else // MALLOC_TARGET_64BIT
#define TINY_FREE_SIZE(ptr) (((msize_t *)(ptr))[4])
#endif // MALLOC_TARGET_64BIT
#define TINY_PREVIOUS_MSIZE(ptr) ((msize_t *)(ptr))[-1]
/*
* Layout of a tiny region
*/
typedef uint32_t tiny_block_t[4]; // assert(TINY_QUANTUM == sizeof(tiny_block_t))
typedef struct tiny_header_inuse_pair {
uint32_t header;
uint32_t inuse;
} tiny_header_inuse_pair_t;
typedef struct region_trailer {
struct region_trailer *prev;
struct region_trailer *next;
boolean_t recirc_suitable;
volatile int pinned_to_depot;
unsigned bytes_used;
mag_index_t mag_index;
} region_trailer_t;
typedef struct tiny_region {
tiny_block_t blocks[NUM_TINY_BLOCKS];
region_trailer_t trailer;
// The interleaved bit arrays comprising the header and inuse bitfields.
// The unused bits of each component in the last pair will be initialized to sentinel values.
tiny_header_inuse_pair_t pairs[CEIL_NUM_TINY_BLOCKS_WORDS];
uint8_t pad[TINY_REGION_SIZE - (NUM_TINY_BLOCKS * sizeof(tiny_block_t)) - TINY_METADATA_SIZE];
} * tiny_region_t;
/*
* Per-region meta data for tiny allocator
*/
#define REGION_TRAILER_FOR_TINY_REGION(r) (&(((tiny_region_t)(r))->trailer))
#define MAGAZINE_INDEX_FOR_TINY_REGION(r) (REGION_TRAILER_FOR_TINY_REGION(r)->mag_index)
#define BYTES_USED_FOR_TINY_REGION(r) (REGION_TRAILER_FOR_TINY_REGION(r)->bytes_used)
/*
* Locate the block header for a pointer known to be within a tiny region.
*/
#define TINY_BLOCK_HEADER_FOR_PTR(_p) ((void *)&(((tiny_region_t)TINY_REGION_FOR_PTR(_p))->pairs))
/*
* Locate the inuse map for a given block header pointer.
*/
#define TINY_INUSE_FOR_HEADER(_h) ((void *)&(((tiny_header_inuse_pair_t *)(_h))->inuse))
/*
* Compute the bitmap index for a pointer known to be within a tiny region.
*/
#define TINY_INDEX_FOR_PTR(_p) (((uintptr_t)(_p) >> SHIFT_TINY_QUANTUM) & (NUM_TINY_CEIL_BLOCKS - 1))
/*
* Offset back to an szone_t given prior knowledge that this rack_t
* is contained within an szone_t.
*
* Note: the only place this is used, the dtrace probes, only occurs
* when the rack has been set up inside a scalable zone. Should
* this ever be used somewhere that this does not hold true
* (say, the test cases) then the pointer returned will be junk.
*/
#define TINY_SZONE_FROM_RACK(_r) \
(szone_t *)((uintptr_t)(_r) - offsetof(struct szone_s, tiny_rack))
#if !CONFIG_TINY_CACHE
#warning CONFIG_TINY_CACHE turned off
#endif
#define TINY_REGION_PAYLOAD_BYTES (NUM_TINY_BLOCKS * TINY_QUANTUM)
/********************* DEFINITIONS for small ************************/
/*
* Memory in the Small range is allocated from regions (heaps) pointed to by the szone's hashed_regions
* pointer.
*
* Each region is laid out as a heap, followed by the metadata array, all within an 8MB (2^23) block.
* The array is arranged as an array of shorts, one for each SMALL_QUANTUM in the heap. There are
* 16319 512-blocks and the array is 16319*2 bytes, which totals 8387966, leaving 642 bytes unused.
* Once the region trailer is accounted for, there is room for 61 out-of-band free list entries in
* the remaining padding (or 6, if the region was split into 16320 blocks, not 16319).
*
* The 16-bit shorts in the region are used for allocation metadata. The MSB bit marks a block as
* either free, or not. The remaining 15-bits give the size of the allocation, defined in "msize", the
* quantum-shifted size of the allocation.
*
* The metadata table either:
*
* 1. Stores the allocation size in the first short for the block, with the MSB cleared to indicate
* that the block is allocated and in-use, or,
*
* 2. Stores the free-allocation size in the first and last shorts for the block, with the MSB set
* in both places to indicate that the block is freed. (Storing the range in last block allows
* for coalescing of adjacent free entries).
*
* 3. Zero, or "middle", meaning that this block in the region is not the start or end of an
* allocated block.
*
* The small zone represents the free list in one of two ways:
*
* 1. In-line free list entries. These are stored at the starting address of the just-freed memory
* and both the previous and next pointer are checksummed to attempt to detect use-after-free
* writes.
*
* An in-line free list entry is laid out as:
* |prev (uintptr_t)|checksum (uint8_t)|next (uintptr_t)|checksum (uint8_t)
*
* 2. Out-of-band free list entries. These utilitise the remaining padding in the 8mb region that
* follows the blocks, metadata and region trailer. Out-of-band entries are used *iff* the
* freed address lies on a page boundary and the freed region spans more than a page. If we were
* to store the free list entry in-line in that memory, it would keep the entire page dirty,
* so an out-of-band entry is used.
*
* An out-of-band free list entry is laid out as:
* |prev (uintptr_t)|next (uintptr_t)|ptr (uint16_t)|
*
* The szone maintains an array of 32 freelists, each of which is used to hold free objects
* of the corresponding quantum size.
*/
#define SMALL_IS_FREE (1 << 15)
#define FOLLOWING_SMALL_PTR(ptr, msize) (((unsigned char *)(ptr)) + ((msize) << SHIFT_SMALL_QUANTUM))
/*
* SMALL_IS_OOB is used mark to the MSB of OOB free list entries to show that they are in use, and
* distinguish them from their initial, empty, state.
*/
#define SMALL_IS_OOB (1 << 15)
#define SMALL_ENTROPY_BITS 13
#define SMALL_ENTROPY_MASK ((1 << SMALL_ENTROPY_BITS) - 1)
/*
* Avoid having so much entropy that the end of a valid small allocation
* might overrun the end of the small region.
*/
#if SMALL_ENTROPY_MASK + NUM_SMALL_SLOTS > NUM_SMALL_BLOCKS
#error Too many entropy bits for small region requested
#endif
#define SMALL_METADATA_SIZE (sizeof(region_trailer_t) + NUM_SMALL_BLOCKS * sizeof(msize_t))
#define SMALL_REGION_SIZE ((NUM_SMALL_BLOCKS * SMALL_QUANTUM + SMALL_METADATA_SIZE + PAGE_MAX_SIZE - 1) & ~(PAGE_MAX_SIZE - 1))
#define SMALL_METADATA_START (NUM_SMALL_BLOCKS * SMALL_QUANTUM)
/*
* Beginning and end pointers for a region's heap.
*/
#define SMALL_REGION_ADDRESS(region) ((unsigned char *)region)
#define SMALL_REGION_END(region) (SMALL_REGION_ADDRESS(region) + (NUM_SMALL_BLOCKS * SMALL_QUANTUM))
/*
* Locate the heap base for a pointer known to be within a small region.
*/
#define SMALL_REGION_FOR_PTR(_p) ((void *)((uintptr_t)(_p) & ~((1 << SMALL_BLOCKS_ALIGN) - 1)))
#define SMALL_OFFSET_FOR_PTR(_p) ((uintptr_t)(_p) & ((1 << SMALL_BLOCKS_ALIGN) - 1))
/*
* Convert between byte and msize units.
*/
#define SMALL_BYTES_FOR_MSIZE(_m) ((uint32_t)(_m) << SHIFT_SMALL_QUANTUM)
#define SMALL_MSIZE_FOR_BYTES(_b) ((_b) >> SHIFT_SMALL_QUANTUM)
#define SMALL_PREVIOUS_MSIZE(ptr) (*SMALL_METADATA_FOR_PTR(ptr - 1) & ~SMALL_IS_FREE)
/*
* Convert from msize unit to free list slot.
*/
#define SMALL_FREE_SLOT_COUNT(_r) \
(((_r)->debug_flags & MALLOC_EXTENDED_SMALL_SLOTS) ? \
NUM_SMALL_SLOTS_LARGEMEM + 1 : NUM_SMALL_SLOTS + 1)
#define SMALL_FREE_SLOT_FOR_MSIZE(_r, _m) \
(((_m) <= SMALL_FREE_SLOT_COUNT(_r)) ? ((_m) - 1) : (SMALL_FREE_SLOT_COUNT(_r) - 1))
/* compare with MAGAZINE_FREELIST_BITMAP_WORDS */
#define SMALL_FREELIST_BITMAP_WORDS(_r) ((SMALL_FREE_SLOT_COUNT(_r) + 31) >> 5)
/*
* Offset back to an szone_t given prior knowledge that this rack_t
* is contained within an szone_t.
*
* Note: the only place this is used, the dtrace probes, only occurs
* when the rack has been set up inside a scalable zone. Should
* this ever be used somewhere that this does not hold true
* (say, the test cases) then the pointer returned will be junk.
*/
#define SMALL_SZONE_FROM_RACK(_r) \
(szone_t *)((uintptr_t)(_r) - offsetof(struct szone_s, small_rack))
/*
* Layout of a small region
*/
typedef uint32_t small_block_t[SMALL_QUANTUM / sizeof(uint32_t)];
#define SMALL_HEAP_SIZE (NUM_SMALL_BLOCKS * sizeof(small_block_t))
#define SMALL_OOB_COUNT ((SMALL_REGION_SIZE - SMALL_HEAP_SIZE - SMALL_METADATA_SIZE) / sizeof(oob_free_entry_s))
#define SMALL_OOB_SIZE (SMALL_OOB_COUNT * sizeof(oob_free_entry_s))
#define SMALL_REGION_PAD (SMALL_REGION_SIZE - SMALL_HEAP_SIZE - SMALL_METADATA_SIZE - SMALL_OOB_SIZE)
typedef struct small_region {
small_block_t blocks[NUM_SMALL_BLOCKS];
region_trailer_t trailer;
msize_t small_meta_words[NUM_SMALL_BLOCKS];
oob_free_entry_s small_oob_free_entries[SMALL_OOB_COUNT];
uint8_t pad[SMALL_REGION_PAD];
} * small_region_t;
// The layout described above should result in a small_region_t being 8MB.
MALLOC_STATIC_ASSERT(sizeof(struct small_region) == 8388608, "incorrect small_region_size");
/*
* Per-region meta data for small allocator
*/
#define REGION_TRAILER_FOR_SMALL_REGION(r) (&(((small_region_t)(r))->trailer))
#define MAGAZINE_INDEX_FOR_SMALL_REGION(r) (REGION_TRAILER_FOR_SMALL_REGION(r)->mag_index)
#define BYTES_USED_FOR_SMALL_REGION(r) (REGION_TRAILER_FOR_SMALL_REGION(r)->bytes_used)
/*
* Locate the metadata base for a pointer known to be within a small region.
*/
#define SMALL_META_HEADER_FOR_PTR(_p) (((small_region_t)SMALL_REGION_FOR_PTR(_p))->small_meta_words)
/*
* Compute the metadata index for a pointer known to be within a small region.
*/
#define SMALL_META_INDEX_FOR_PTR(_p) (((uintptr_t)(_p) >> SHIFT_SMALL_QUANTUM) & (NUM_SMALL_CEIL_BLOCKS - 1))
/*
* Find the metadata word for a pointer known to be within a small region.
*/
#define SMALL_METADATA_FOR_PTR(_p) (SMALL_META_HEADER_FOR_PTR(_p) + SMALL_META_INDEX_FOR_PTR(_p))
/*
* Determine whether a pointer known to be within a small region points to memory which is free.
*/
#define SMALL_PTR_IS_FREE(_p) (*SMALL_METADATA_FOR_PTR(_p) & SMALL_IS_FREE)
/*
* Extract the msize value for a pointer known to be within a small region.
*/
#define SMALL_PTR_SIZE(_p) (*SMALL_METADATA_FOR_PTR(_p) & ~SMALL_IS_FREE)
#if !CONFIG_SMALL_CACHE
#warning CONFIG_SMALL_CACHE turned off
#endif
#define SMALL_REGION_PAYLOAD_BYTES (NUM_SMALL_BLOCKS * SMALL_QUANTUM)
/************************* DEFINITIONS for large ****************************/
typedef struct large_entry_s {
vm_address_t address;
vm_size_t size;
boolean_t did_madvise_reusable;
} large_entry_t;
#if !CONFIG_LARGE_CACHE && DEBUG_MALLOC
#warning CONFIG_LARGE_CACHE turned off
#endif
/*******************************************************************************
* Per-processor magazine for tiny and small allocators
******************************************************************************/
typedef struct magazine_s { // vm_allocate()'d, so the array of magazines is page-aligned to begin with.
// Take magazine_lock first, Depot lock when needed for recirc, then szone->{tiny,small}_regions_lock when needed for alloc
_malloc_lock_s magazine_lock MALLOC_CACHE_ALIGN;
// Protection for the crtical section that does allocate_pages outside the magazine_lock
volatile boolean_t alloc_underway;
// One element deep "death row", optimizes malloc/free/malloc for identical size.
void *mag_last_free;
msize_t mag_last_free_msize; // msize for mag_last_free
#if MALLOC_TARGET_64BIT
uint32_t _pad;
#endif
region_t mag_last_free_rgn; // holds the region for mag_last_free
free_list_t mag_free_list[MAGAZINE_FREELIST_SLOTS];
uint32_t mag_bitmap[MAGAZINE_FREELIST_BITMAP_WORDS];
// the first and last free region in the last block are treated as big blocks in use that are not accounted for
size_t mag_bytes_free_at_end;
size_t mag_bytes_free_at_start;
region_t mag_last_region; // Valid iff mag_bytes_free_at_end || mag_bytes_free_at_start > 0
// bean counting ...
size_t mag_num_bytes_in_objects;
size_t num_bytes_in_magazine;
unsigned mag_num_objects;
// recirculation list -- invariant: all regions owned by this magazine that meet the emptiness criteria
// are located nearer to the head of the list than any region that doesn't satisfy that criteria.
// Doubly linked list for efficient extraction.
unsigned recirculation_entries;
region_trailer_t *firstNode;
region_trailer_t *lastNode;
#if MALLOC_TARGET_64BIT
uintptr_t pad[320 - 14 - MAGAZINE_FREELIST_SLOTS -
(MAGAZINE_FREELIST_BITMAP_WORDS + 1) / 2];
#else
uintptr_t pad[320 - 16 - MAGAZINE_FREELIST_SLOTS -
MAGAZINE_FREELIST_BITMAP_WORDS];
#endif
} magazine_t;
#if MALLOC_TARGET_64BIT
MALLOC_STATIC_ASSERT(sizeof(magazine_t) == 2560, "Incorrect padding in magazine_t");
#else
MALLOC_STATIC_ASSERT(sizeof(magazine_t) == 1280, "Incorrect padding in magazine_t");
#endif
#define TINY_MAX_MAGAZINES 64 /* MUST BE A POWER OF 2! */
#define TINY_MAGAZINE_PAGED_SIZE \
(((sizeof(magazine_t) * (TINY_MAX_MAGAZINES + 1)) + vm_page_quanta_size - 1) & \
~(vm_page_quanta_size - 1)) /* + 1 for the Depot */
#define SMALL_MAX_MAGAZINES 64 /* MUST BE A POWER OF 2! */
#define SMALL_MAGAZINE_PAGED_SIZE \
(((sizeof(magazine_t) * (SMALL_MAX_MAGAZINES + 1)) + vm_page_quanta_size - 1) & \
~(vm_page_quanta_size - 1)) /* + 1 for the Depot */
#define DEPOT_MAGAZINE_INDEX -1
/****************************** zone itself ***********************************/
/*
* Note that objects whose adddress are held in pointers here must be pursued
* individually in the {tiny,small}_in_use_enumeration() routines. See for
* example the treatment of region_hash_generation and tiny_magazines below.
*/
typedef struct szone_s { // vm_allocate()'d, so page-aligned to begin with.
malloc_zone_t basic_zone; // first page will be given read-only protection
uint8_t pad[PAGE_MAX_SIZE - sizeof(malloc_zone_t)];
unsigned long cpu_id_key; // unused
// remainder of structure is R/W (contains no function pointers)
unsigned debug_flags;
void *log_address;
/* Allocation racks per allocator type. */
struct rack_s tiny_rack;
struct rack_s small_rack;
/* large objects: all the rest */
_malloc_lock_s large_szone_lock MALLOC_CACHE_ALIGN; // One customer at a time for large
unsigned num_large_objects_in_use;
unsigned num_large_entries;
large_entry_t *large_entries; // hashed by location; null entries don't count
size_t num_bytes_in_large_objects;
#if CONFIG_LARGE_CACHE
int large_entry_cache_oldest;
int large_entry_cache_newest;
large_entry_t large_entry_cache[LARGE_ENTRY_CACHE_SIZE]; // "death row" for large malloc/free
boolean_t large_legacy_reset_mprotect;
size_t large_entry_cache_reserve_bytes;
size_t large_entry_cache_reserve_limit;
size_t large_entry_cache_bytes; // total size of death row, bytes
#endif
/* flag and limits pertaining to altered malloc behavior for systems with
* large amounts of physical memory */
unsigned is_largemem;
unsigned large_threshold;
unsigned vm_copy_threshold;
/* security cookie */
uintptr_t cookie;
/* The purgeable zone constructed by create_purgeable_zone() would like to hand off tiny and small
* allocations to the default scalable zone. Record the latter as the "helper" zone here. */
struct szone_s *helper_zone;
boolean_t flotsam_enabled;
} szone_t;
#define SZONE_PAGED_SIZE round_page_quanta((sizeof(szone_t)))
#endif // __MAGAZINE_ZONE_H
================================================
FILE: InterView-obj-isa-class/libmalloc-166.220.1/src/magmallocProvider.d
================================================
provider magmalloc {
probe refreshIndex(void *, int, int);
probe depotRegion(void *, int, void *, int, int);
probe recircRegion(void *, int, void *, int, int);
probe allocRegion(void *, int, void *, int);
probe deallocRegion(void *, void *, int);
probe madvfreeRegion(void *, void *, void *, int);
probe pressureReliefBegin(void *, char *, int);
probe pressureReliefEnd(void *, char *, int, int);
probe mallocErrorBreak();
};
#pragma D attributes Evolving/Evolving/ISA provider magmalloc provider
#pragma D attributes Private/Private/Unknown provider magmalloc module
#pragma D attributes Private/Private/Unknown provider magmalloc function
#pragma D attributes Evolving/Evolving/ISA provider magmalloc name
#pragma D attributes Evolving/Evolving/ISA provider magmalloc args
================================================
FILE: InterView-obj-isa-class/libmalloc-166.220.1/src/malloc.c
================================================
/*
* Copyright (c) 1999, 2000, 2003, 2005, 2008, 2012 Apple Inc. All rights reserved.
*
* @APPLE_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apple Public Source License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. Please obtain a copy of the License at
* http://www.opensource.apple.com/apsl/ and read it before using this
* file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPLE_LICENSE_HEADER_END@
*/
#include "internal.h"
#if TARGET_OS_IPHONE
// malloc_report(ASL_LEVEL_INFO...) on iOS doesn't show up in the Xcode Console log of the device,
// but ASL_LEVEL_NOTICE does. So raising the log level is helpful.
#undef ASL_LEVEL_INFO
#define ASL_LEVEL_INFO ASL_LEVEL_NOTICE
#endif // TARGET_OS_IPHONE
#define USE_SLEEP_RATHER_THAN_ABORT 0
/*
MAX_LITE_MALLOCS
If msl lite is turned on due to a memory resource exception use this value as the maximum
number of allocations allowed before msl lite is turned off. This prevents msl lite from being
enabled indefinitely if the process never reaches 100% of its jetsam limit.
See rdar://problem/25950426 for a discussion of how this number was determined.
*/
#define MAX_LITE_MALLOCS 100000000
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);
extern malloc_logger_t *__syscall_logger; // use this to set up syscall logging (e.g., vm_allocate, vm_deallocate, mmap, munmap)
static _malloc_lock_s _malloc_lock = _MALLOC_LOCK_INIT;
#define MALLOC_LOCK() _malloc_lock_lock(&_malloc_lock)
#define MALLOC_TRY_LOCK() _malloc_lock_trylock(&_malloc_lock)
#define MALLOC_UNLOCK() _malloc_lock_unlock(&_malloc_lock)
#define MALLOC_REINIT_LOCK() _malloc_lock_init(&_malloc_lock)
/* The following variables are exported for the benefit of performance tools
*
* It should always be safe to first read malloc_num_zones, then read
* malloc_zones without taking the lock, if only iteration is required and
* provided that when malloc_destroy_zone is called all prior operations on that
* zone are complete and no further calls referencing that zone can be made.
*/
int32_t malloc_num_zones = 0;
int32_t malloc_num_zones_allocated = 0;
malloc_zone_t **malloc_zones = 0;
malloc_logger_t *malloc_logger = NULL;
static malloc_zone_t *initial_default_zone = NULL;
unsigned malloc_debug_flags = 0;
boolean_t malloc_tracing_enabled = false;
unsigned malloc_check_start = 0; // 0 means don't check
unsigned malloc_check_counter = 0;
unsigned malloc_check_each = 1000;
static int malloc_check_sleep = 100; // default 100 second sleep
static int malloc_check_abort = 0; // default is to sleep, not abort
static os_once_t _malloc_initialize_pred;
// Used by memory resource exceptions and enabling/disabling malloc stack logging via malloc_memory_event_handler
static boolean_t warn_mode_entered = false;
static boolean_t warn_mode_disable_retries = false;
static stack_logging_mode_type msl_type_enabled_at_runtime = stack_logging_mode_none;
/*
* Counters that coordinate zone destruction (in malloc_zone_unregister) with
* find_registered_zone (here abbreviated as FRZ).
*/
static int32_t volatile counterAlice = 0, counterBob = 0;
static int32_t volatile * volatile pFRZCounterLive = &counterAlice;
static int32_t volatile * volatile pFRZCounterDrain = &counterBob;
unsigned int _os_cpu_number_override = -1;
static inline malloc_zone_t *inline_malloc_default_zone(void) __attribute__((always_inline));
#define MALLOC_LOG_TYPE_ALLOCATE stack_logging_type_alloc
#define MALLOC_LOG_TYPE_DEALLOCATE stack_logging_type_dealloc
#define MALLOC_LOG_TYPE_HAS_ZONE stack_logging_flag_zone
#define MALLOC_LOG_TYPE_CLEARED stack_logging_flag_cleared
#define DEFAULT_MALLOC_ZONE_STRING "DefaultMallocZone"
#define DEFAULT_PUREGEABLE_ZONE_STRING "DefaultPurgeableMallocZone"
#define MALLOC_HELPER_ZONE_STRING "MallocHelperZone"
MALLOC_NOEXPORT
unsigned int phys_ncpus;
MALLOC_NOEXPORT
unsigned int logical_ncpus;
MALLOC_NOEXPORT
unsigned int hyper_shift;
// Boot argument for max magazine control
static const char max_magazines_boot_arg[] = "malloc_max_magazines";
/********* Utilities ************/
static bool _malloc_entropy_initialized;
void __malloc_init(const char *apple[]);
static int
__entropy_from_kernel(const char *str)
{
unsigned long long val;
char tmp[20], *p;
int idx = 0;
/* Skip over key to the first value */
str = strchr(str, '=');
if (str == NULL) {
return 0;
}
str++;
while (str && idx < sizeof(malloc_entropy) / sizeof(malloc_entropy[0])) {
strlcpy(tmp, str, 20);
p = strchr(tmp, ',');
if (p) {
*p = '\0';
}
val = strtoull_l(tmp, NULL, 0, NULL);
malloc_entropy[idx] = (uint64_t)val;
idx++;
if ((str = strchr(str, ',')) != NULL) {
str++;
}
}
return idx;
}
static void
__malloc_init_from_bootargs(const char *bootargs)
{
// The maximum number of magazines can be set either via a
// boot argument or from the environment. Get the boot argument value
// here and store it. We can't bounds check it until we have phys_ncpus,
// which happens later in _malloc_initialize(), along with handling
// of the environment value setting.
char value_buf[256];
const char *flag = malloc_common_value_for_key_copy(bootargs,
max_magazines_boot_arg, value_buf, sizeof(value_buf));
if (flag) {
const char *endp;
long value = malloc_common_convert_to_long(flag, &endp);
if (!*endp && value >= 0) {
max_magazines = (unsigned int)value;
} else {
malloc_report(ASL_LEVEL_ERR,
"malloc_max_magazines must be positive - ignored.\n");
}
}
}
/* TODO: Investigate adding _malloc_initialize() into this libSystem initializer */
void
__malloc_init(const char *apple[])
{
// We could try to be clever and cater for arbitrary length bootarg
// strings, but it's probably not worth it, especially as we would need
// to temporarily allocate at least a page of memory to read the bootargs
// into.
char bootargs[1024] = { '\0' };
size_t len = sizeof(bootargs) - 1;
if (!sysctlbyname("kern.bootargs", bootargs, &len, NULL, 0) && len > 0) {
bootargs[len + 1] = '\0';
}
#if CONFIG_NANOZONE
// TODO: envp should be passed down from Libsystem
const char **envp = (const char **)*_NSGetEnviron();
nano_common_init(envp, apple, bootargs);
#endif
const char **p;
for (p = apple; p && *p; p++) {
if (strstr(*p, "malloc_entropy") == *p) {
int count = __entropy_from_kernel(*p);
bzero((void *)*p, strlen(*p));
if (sizeof(malloc_entropy) / sizeof(malloc_entropy[0]) == count) {
_malloc_entropy_initialized = true;
}
break;
}
}
if (!_malloc_entropy_initialized) {
getentropy((void*)malloc_entropy, sizeof(malloc_entropy));
_malloc_entropy_initialized = true;
}
__malloc_init_from_bootargs(bootargs);
mvm_aslr_init();
}
static malloc_zone_t* lite_zone = NULL;
MALLOC_ALWAYS_INLINE
static inline malloc_zone_t *
runtime_default_zone() {
return (lite_zone) ? lite_zone : inline_malloc_default_zone();
}
static size_t
default_zone_size(malloc_zone_t *zone, const void *ptr)
{
zone = runtime_default_zone();
return zone->size(zone, ptr);
}
static void *
default_zone_malloc(malloc_zone_t *zone, size_t size)
{
zone = runtime_default_zone();
return zone->malloc(zone, size);
}
static void *
default_zone_calloc(malloc_zone_t *zone, size_t num_items, size_t size)
{
zone = runtime_default_zone();
return zone->calloc(zone, num_items, size);
}
static void *
default_zone_valloc(malloc_zone_t *zone, size_t size)
{
zone = runtime_default_zone();
return zone->valloc(zone, size);
}
static void
default_zone_free(malloc_zone_t *zone, void *ptr)
{
zone = runtime_default_zone();
return zone->free(zone, ptr);
}
static void *
default_zone_realloc(malloc_zone_t *zone, void *ptr, size_t new_size)
{
zone = runtime_default_zone();
return zone->realloc(zone, ptr, new_size);
}
static void
default_zone_destroy(malloc_zone_t *zone)
{
zone = runtime_default_zone();
return zone->destroy(zone);
}
static unsigned
default_zone_batch_malloc(malloc_zone_t *zone, size_t size, void **results, unsigned count)
{
zone = runtime_default_zone();
return zone->batch_malloc(zone, size, results, count);
}
static void
default_zone_batch_free(malloc_zone_t *zone, void **to_be_freed, unsigned count)
{
zone = runtime_default_zone();
return zone->batch_free(zone, to_be_freed, count);
}
static void *
default_zone_memalign(malloc_zone_t *zone, size_t alignment, size_t size)
{
zone = runtime_default_zone();
return zone->memalign(zone, alignment, size);
}
static void
default_zone_free_definite_size(malloc_zone_t *zone, void *ptr, size_t size)
{
zone = runtime_default_zone();
return zone->free_definite_size(zone, ptr, size);
}
static size_t
default_zone_pressure_relief(malloc_zone_t *zone, size_t goal)
{
zone = runtime_default_zone();
return zone->pressure_relief(zone, goal);
}
static boolean_t
default_zone_malloc_claimed_address(malloc_zone_t *zone, void *ptr)
{
zone = runtime_default_zone();
return malloc_zone_claimed_address(zone, ptr);
}
static kern_return_t
default_zone_ptr_in_use_enumerator(task_t task,
void *context,
unsigned type_mask,
vm_address_t zone_address,
memory_reader_t reader,
vm_range_recorder_t recorder)
{
malloc_zone_t *zone = runtime_default_zone();
return zone->introspect->enumerator(task, context, type_mask, (vm_address_t) zone, reader, recorder);
}
static size_t
default_zone_good_size(malloc_zone_t *zone, size_t size)
{
zone = runtime_default_zone();
return zone->introspect->good_size(zone, size);
}
static boolean_t
default_zone_check(malloc_zone_t *zone)
{
zone = runtime_default_zone();
return zone->introspect->check(zone);
}
static void
default_zone_print(malloc_zone_t *zone, boolean_t verbose)
{
zone = runtime_default_zone();
return (void)zone->introspect->print(zone, verbose);
}
static void
default_zone_log(malloc_zone_t *zone, void *log_address)
{
zone = runtime_default_zone();
return zone->introspect->log(zone, log_address);
}
static void
default_zone_force_lock(malloc_zone_t *zone)
{
zone = runtime_default_zone();
return zone->introspect->force_lock(zone);
}
static void
default_zone_force_unlock(malloc_zone_t *zone)
{
zone = runtime_default_zone();
return zone->introspect->force_unlock(zone);
}
static void
default_zone_statistics(malloc_zone_t *zone, malloc_statistics_t *stats)
{
zone = runtime_default_zone();
return zone->introspect->statistics(zone, stats);
}
static boolean_t
default_zone_locked(malloc_zone_t *zone)
{
zone = runtime_default_zone();
return zone->introspect->zone_locked(zone);
}
static void
default_zone_reinit_lock(malloc_zone_t *zone)
{
zone = runtime_default_zone();
return zone->introspect->reinit_lock(zone);
}
static struct malloc_introspection_t default_zone_introspect = {
default_zone_ptr_in_use_enumerator,
default_zone_good_size,
default_zone_check,
default_zone_print,
default_zone_log,
default_zone_force_lock,
default_zone_force_unlock,
default_zone_statistics,
default_zone_locked,
NULL,
NULL,
NULL,
NULL,
default_zone_reinit_lock
};
typedef struct {
malloc_zone_t malloc_zone;
uint8_t pad[PAGE_MAX_SIZE - sizeof(malloc_zone_t)];
} virtual_default_zone_t;
static virtual_default_zone_t virtual_default_zone
__attribute__((section("__DATA,__v_zone")))
__attribute__((aligned(PAGE_MAX_SIZE))) = {
NULL,
NULL,
default_zone_size,
default_zone_malloc,
default_zone_calloc,
default_zone_valloc,
default_zone_free,
default_zone_realloc,
default_zone_destroy,
DEFAULT_MALLOC_ZONE_STRING,
default_zone_batch_malloc,
default_zone_batch_free,
&default_zone_introspect,
10,
default_zone_memalign,
default_zone_free_definite_size,
default_zone_pressure_relief,
default_zone_malloc_claimed_address,
};
static malloc_zone_t *default_zone = &virtual_default_zone.malloc_zone;
static boolean_t
has_default_zone0(void)
{
if (!malloc_zones) {
return false;
}
return initial_default_zone == malloc_zones[0];
}
static inline malloc_zone_t *find_registered_zone(const void *, size_t *) __attribute__((always_inline));
static inline malloc_zone_t *
find_registered_zone(const void *ptr, size_t *returned_size)
{
// Returns a zone which contains ptr, else NULL
if (0 == malloc_num_zones) {
if (returned_size) {
*returned_size = 0;
}
return NULL;
}
// first look in the lite zone
if (lite_zone) {
malloc_zone_t *zone = lite_zone;
size_t size = zone->size(zone, ptr);
if (size) { // Claimed by this zone?
if (returned_size) {
*returned_size = size;
}
// Return the virtual default zone instead of the lite zone - see
return default_zone;
}
}
// The default zone is registered in malloc_zones[0]. There's no danger that it will ever be unregistered.
// So don't advance the FRZ counter yet.
malloc_zone_t *zone = malloc_zones[0];
size_t size = zone->size(zone, ptr);
if (size) { // Claimed by this zone?
if (returned_size) {
*returned_size = size;
}
// Asan and others replace the zone at position 0 with their own zone.
// In that case just return that zone as they need this information.
// Otherwise return the virtual default zone, not the actual zone in position 0.
if (!has_default_zone0()) {
return zone;
} else {
return default_zone;
}
}
int32_t volatile *pFRZCounter = pFRZCounterLive; // Capture pointer to the counter of the moment
OSAtomicIncrement32Barrier(pFRZCounter); // Advance this counter -- our thread is in FRZ
unsigned index;
int32_t limit = *(int32_t volatile *)&malloc_num_zones;
malloc_zone_t **zones = &malloc_zones[1];
// From this point on, FRZ is accessing the malloc_zones[] array without locking
// in order to avoid contention on common operations (such as non-default-zone free()).
// In order to ensure that this is actually safe to do, register/unregister take care
// to:
//
// 1. Register ensures that newly inserted pointers in malloc_zones[] are visible
// when malloc_num_zones is incremented. At the moment, we're relying on that store
// ordering to work without taking additional steps here to ensure load memory
// ordering.
//
// 2. Unregister waits for all readers in FRZ to complete their iteration before it
// returns from the unregister call (during which, even unregistered zone pointers
// are still valid). It also ensures that all the pointers in the zones array are
// valid until it returns, so that a stale value in limit is not dangerous.
for (index = 1; index < limit; ++index, ++zones) {
zone = *zones;
size = zone->size(zone, ptr);
if (size) { // Claimed by this zone?
goto out;
}
}
// Unclaimed by any zone.
zone = NULL;
size = 0;
out:
if (returned_size) {
*returned_size = size;
}
OSAtomicDecrement32Barrier(pFRZCounter); // our thread is leaving FRZ
return zone;
}
void
malloc_error_break(void)
{
// Provides a non-inlined place for various malloc error procedures to call
// that will be called after an error message appears. It does not make
// sense for developers to call this function, so it is marked
// hidden to prevent it from becoming API.
MAGMALLOC_MALLOCERRORBREAK(); // DTrace USDT probe
}
int
malloc_gdb_po_unsafe(void)
{
// In order to implement "po" other data formatters in gdb, the debugger
// calls functions that call malloc. The debugger will only run one thread
// of the program in this case, so if another thread is holding a zone lock,
// gdb may deadlock in this case.
//
// Iterate over the zones in malloc_zones, and call "trylock" on the zone
// lock. If trylock succeeds, unlock it, otherwise return "locked". Returns
// 0 == safe, 1 == locked/unsafe.
if (__stack_logging_locked()) {
return 1;
}
malloc_zone_t **zones = malloc_zones;
unsigned i, e = malloc_num_zones;
for (i = 0; i != e; ++i) {
malloc_zone_t *zone = zones[i];
// Version must be >= 5 to look at the new introspection field.
if (zone->version < 5) {
continue;
}
if (zone->introspect->zone_locked && zone->introspect->zone_locked(zone)) {
return 1;
}
}
return 0;
}
/********* Creation and destruction ************/
static void set_flags_from_environment(void);
static void
malloc_zone_register_while_locked(malloc_zone_t *zone)
{
size_t protect_size;
unsigned i;
/* scan the list of zones, to see if this zone is already registered. If
* so, print an error message and return. */
for (i = 0; i != malloc_num_zones; ++i) {
if (zone == malloc_zones[i]) {
malloc_report(ASL_LEVEL_ERR, "Attempted to register zone more than once: %p\n", zone);
return;
}
}
if (malloc_num_zones == malloc_num_zones_allocated) {
size_t malloc_zones_size = malloc_num_zones * sizeof(malloc_zone_t *);
mach_vm_size_t alloc_size = round_page(malloc_zones_size + vm_page_size);
mach_vm_address_t vm_addr;
int alloc_flags = VM_FLAGS_ANYWHERE | VM_MAKE_TAG(VM_MEMORY_MALLOC);
vm_addr = vm_page_size;
kern_return_t kr = mach_vm_allocate(mach_task_self(), &vm_addr, alloc_size, alloc_flags);
if (kr) {
malloc_report(ASL_LEVEL_ERR, "malloc_zone_register allocation failed: %d\n", kr);
return;
}
malloc_zone_t **new_zones = (malloc_zone_t **)vm_addr;
/* If there were previously allocated malloc zones, we need to copy them
* out of the previous array and into the new zones array */
if (malloc_zones) {
memcpy(new_zones, malloc_zones, malloc_zones_size);
vm_addr = (mach_vm_address_t)malloc_zones;
mach_vm_size_t dealloc_size = round_page(malloc_zones_size);
mach_vm_deallocate(mach_task_self(), vm_addr, dealloc_size);
}
/* Update the malloc_zones pointer, which we leak if it was previously
* allocated, and the number of zones allocated */
protect_size = (size_t)alloc_size;
malloc_zones = new_zones;
malloc_num_zones_allocated = (int32_t)(alloc_size / sizeof(malloc_zone_t *));
} else {
/* If we don't need to reallocate zones, we need to briefly change the
* page protection the malloc zones to allow writes */
protect_size = malloc_num_zones_allocated * sizeof(malloc_zone_t *);
mprotect(malloc_zones, protect_size, PROT_READ | PROT_WRITE);
}
/* This store-increment needs to be visible in the correct
* order to any threads in find_registered_zone, such that if the incremented value
* in malloc_num_zones is visible then the pointer write before it must also be visible.
*
* While we could be slightly more efficent here with atomic ops the cleanest way to
* ensure the proper store-release operation is performed is to use OSAtomic*Barrier
* to update malloc_num_zones.
*/
malloc_zones[malloc_num_zones] = zone;
OSAtomicIncrement32Barrier(&malloc_num_zones);
/* Finally, now that the zone is registered, disallow write access to the
* malloc_zones array */
mprotect(malloc_zones, protect_size, PROT_READ);
//malloc_report(ASL_LEVEL_INFO, "Registered malloc_zone %p in malloc_zones %p [%u zones, %u bytes]\n", zone, malloc_zones,
// malloc_num_zones, protect_size);
}
static void
create_and_insert_lite_zone_while_locked()
{
malloc_zone_t *zone0 = malloc_zones[0];
malloc_zone_t *stack_logging_lite_zone = create_stack_logging_lite_zone(0, zone0, malloc_debug_flags);
malloc_zone_register_while_locked(stack_logging_lite_zone);
malloc_set_zone_name(stack_logging_lite_zone, MALLOC_STOCK_LOGGING_LITE_ZONE_NAME);
lite_zone = stack_logging_lite_zone;
}
boolean_t
turn_on_stack_logging(stack_logging_mode_type mode)
{
boolean_t ret = false;
MALLOC_LOCK();
if (!stack_logging_enable_logging) {
if (__uniquing_table_memory_was_deleted()) {
// It would great to be able re-enable even if the uniquing table has been deleted
// malloc stack logging should be able to recreate the uniquing table if needed
} else {
switch (mode) {
case stack_logging_mode_all:
__prepare_to_log_stacks(false);
malloc_logger = __disk_stack_logging_log_stack;
__syscall_logger = __disk_stack_logging_log_stack;
stack_logging_mode = mode;
stack_logging_enable_logging = 1;
ret = true;
malloc_report(ASL_LEVEL_INFO, "recording malloc and VM allocation stacks to disk using standard recorder\n");
break;
case stack_logging_mode_malloc:
__prepare_to_log_stacks(false);
malloc_logger = __disk_stack_logging_log_stack;
stack_logging_mode = mode;
stack_logging_enable_logging = 1;
ret = true;
malloc_report(ASL_LEVEL_INFO, "recording malloc (but not VM allocation) stacks to disk using standard recorder\n");
break;
case stack_logging_mode_vm:
__prepare_to_log_stacks(false);
__syscall_logger = __disk_stack_logging_log_stack;
stack_logging_mode = mode;
stack_logging_enable_logging = 1;
ret = true;
malloc_report(ASL_LEVEL_INFO, "recording VM allocation (but not malloc) stacks to disk using standard recorder\n");
break;
case stack_logging_mode_lite:
if (!has_default_zone0()) {
malloc_report(ASL_LEVEL_ERR, "zone[0] is not the normal default zone so can't turn on lite mode.\n", mode);
ret = false;
} else {
malloc_report(ASL_LEVEL_INFO, "recording malloc (and VM allocation) stacks using lite mode\n");
if (lite_zone) {
enable_stack_logging_lite();
} else {
if (__prepare_to_log_stacks(true)) {
__syscall_logger = __disk_stack_logging_log_stack;
stack_logging_mode = stack_logging_mode_lite;
stack_logging_enable_logging = 1;
__prepare_to_log_stacks_stage2();
create_and_insert_lite_zone_while_locked();
enable_stack_logging_lite();
}
}
ret = true;
}
break;
case stack_logging_mode_vmlite:
if (__prepare_to_log_stacks(true)) {
__syscall_logger = __disk_stack_logging_log_stack;
stack_logging_mode = mode;
stack_logging_enable_logging = 1;
malloc_report(ASL_LEVEL_INFO, "recording VM allocation (but not malloc) stacks using lite mode\n");
}
break;
default:
malloc_report(ASL_LEVEL_ERR, "invalid mode %d passed to turn_on_stack_logging\n", mode);
break;
}
}
} else {
malloc_report(ASL_LEVEL_ERR, "malloc stack logging already enabled.\n");
}
MALLOC_UNLOCK();
return ret;
}
void
turn_off_stack_logging()
{
MALLOC_LOCK();
if (stack_logging_enable_logging) {
switch (stack_logging_mode) {
case stack_logging_mode_all:
malloc_logger = NULL;
__syscall_logger = NULL;
stack_logging_enable_logging = 0;
malloc_report(ASL_LEVEL_INFO, "turning off recording malloc and VM allocation stacks to disk using standard recorder\n");
break;
case stack_logging_mode_malloc:
malloc_logger = NULL;
stack_logging_enable_logging = 0;
malloc_report(ASL_LEVEL_INFO, "turnning off recording malloc (but not VM allocation) stacks to disk using standard recorder\n");
break;
case stack_logging_mode_vm:
__syscall_logger = NULL;
stack_logging_enable_logging = 0;
malloc_report(ASL_LEVEL_INFO, "turning off recording VM allocation (but not malloc) stacks to disk using standard recorder\n");
break;
case stack_logging_mode_lite:
malloc_report(ASL_LEVEL_INFO, "turning off recording malloc (but not VM allocation) stacks using lite mode\n");
disable_stack_logging_lite();
stack_logging_enable_logging = 0;
break;
case stack_logging_mode_vmlite:
__syscall_logger = NULL;
stack_logging_enable_logging = 0;
malloc_report(ASL_LEVEL_INFO, "turning off recording VM allocation stacks using lite mode\n");
break;
default:
malloc_report(ASL_LEVEL_ERR, "invalid stack_logging_mode %d in turn_off_stack_logging\n", stack_logging_mode);
break;
}
} else {
malloc_report(ASL_LEVEL_ERR, "malloc stack logging not enabled.\n");
}
MALLOC_UNLOCK();
}
// To be used in _malloc_initialize_once() only, call that function instead.
static void
_malloc_initialize(void *context __unused)
{
MALLOC_LOCK();
unsigned n;
malloc_zone_t *zone = NULL;
if (!_malloc_entropy_initialized) {
// Lazy initialization may occur before __malloc_init (rdar://27075409)
// TODO: make this a fatal error
malloc_report(ASL_LEVEL_ERR, "*** malloc was initialized without entropy\n");
}
phys_ncpus = *(uint8_t *)(uintptr_t)_COMM_PAGE_PHYSICAL_CPUS;
logical_ncpus = *(uint8_t *)(uintptr_t)_COMM_PAGE_LOGICAL_CPUS;
if (0 != (logical_ncpus % phys_ncpus)) {
MALLOC_REPORT_FATAL_ERROR(logical_ncpus % phys_ncpus,
"logical_ncpus %% phys_ncpus != 0\n");
}
switch (logical_ncpus / phys_ncpus) {
case 1:
hyper_shift = 0;
break;
case 2:
hyper_shift = 1;
break;
case 4:
hyper_shift = 2;
break;
default:
MALLOC_REPORT_FATAL_ERROR(logical_ncpus / phys_ncpus, "logical_ncpus / phys_ncpus not 1, 2, or 4");
}
// max_magazines may already be set from a boot argument. Make sure that it
// is bounded by the number of CPUs.
if (max_magazines) {
max_magazines = MIN(max_magazines, logical_ncpus);
} else {
max_magazines = logical_ncpus;
}
set_flags_from_environment(); // will only set flags up to two times
n = malloc_num_zones;
#if CONFIG_NANOZONE
nano_common_configure();
malloc_zone_t *helper_zone = create_scalable_zone(0, malloc_debug_flags);
if (_malloc_engaged_nano == NANO_V2) {
zone = nanov2_create_zone(helper_zone, malloc_debug_flags);
} else if (_malloc_engaged_nano == NANO_V1) {
zone = nano_create_zone(helper_zone, malloc_debug_flags);
}
if (zone) {
malloc_zone_register_while_locked(zone);
malloc_zone_register_while_locked(helper_zone);
// Must call malloc_set_zone_name() *after* helper and nano are hooked together.
malloc_set_zone_name(zone, DEFAULT_MALLOC_ZONE_STRING);
malloc_set_zone_name(helper_zone, MALLOC_HELPER_ZONE_STRING);
} else {
zone = helper_zone;
malloc_zone_register_while_locked(zone);
malloc_set_zone_name(zone, DEFAULT_MALLOC_ZONE_STRING);
}
#else
zone = create_scalable_zone(0, malloc_debug_flags);
malloc_zone_register_while_locked(zone);
malloc_set_zone_name(zone, DEFAULT_MALLOC_ZONE_STRING);
#endif
initial_default_zone = zone;
if (n != 0) { // make the default first, for efficiency
unsigned protect_size = malloc_num_zones_allocated * sizeof(malloc_zone_t *);
malloc_zone_t *hold = malloc_zones[0];
if (hold->zone_name && strcmp(hold->zone_name, DEFAULT_MALLOC_ZONE_STRING) == 0) {
malloc_set_zone_name(hold, NULL);
}
mprotect(malloc_zones, protect_size, PROT_READ | PROT_WRITE);
malloc_zones[0] = malloc_zones[n];
malloc_zones[n] = hold;
mprotect(malloc_zones, protect_size, PROT_READ);
}
// Only setup stack logging hooks once lazy initialization is complete, the
// malloc_zone calls above would otherwise initialize malloc stack logging,
// which calls into malloc re-entrantly from Libc upcalls and so deadlocks
// in the lazy initialization os_once(). rdar://13046853
if (stack_logging_enable_logging) {
switch (stack_logging_mode) {
case stack_logging_mode_malloc:
malloc_logger = __disk_stack_logging_log_stack;
break;
case stack_logging_mode_vm:
__syscall_logger = __disk_stack_logging_log_stack;
break;
case stack_logging_mode_all:
malloc_logger = __disk_stack_logging_log_stack;
__syscall_logger = __disk_stack_logging_log_stack;
break;
case stack_logging_mode_lite:
__syscall_logger = __disk_stack_logging_log_stack;
create_and_insert_lite_zone_while_locked();
enable_stack_logging_lite();
break;
case stack_logging_mode_vmlite:
__syscall_logger = __disk_stack_logging_log_stack;
break;
}
}
// malloc_report(ASL_LEVEL_INFO, "%d registered zones\n", malloc_num_zones);
// malloc_report(ASL_LEVEL_INFO, "malloc_zones is at %p; malloc_num_zones is at %p\n", (unsigned)&malloc_zones,
// (unsigned)&malloc_num_zones);
MALLOC_UNLOCK();
}
MALLOC_ALWAYS_INLINE
static inline void
_malloc_initialize_once(void)
{
os_once(&_malloc_initialize_pred, NULL, _malloc_initialize);
}
static inline malloc_zone_t *
inline_malloc_default_zone(void)
{
_malloc_initialize_once();
// malloc_report(ASL_LEVEL_INFO, "In inline_malloc_default_zone with %d %d\n", malloc_num_zones, malloc_has_debug_zone);
return malloc_zones[0];
}
malloc_zone_t *
malloc_default_zone(void)
{
return default_zone;
}
static inline malloc_zone_t *inline_malloc_default_scalable_zone(void) __attribute__((always_inline));
static inline malloc_zone_t *
inline_malloc_default_scalable_zone(void)
{
unsigned index;
_malloc_initialize_once();
// malloc_report(ASL_LEVEL_INFO, "In inline_malloc_default_scalable_zone with %d %d\n", malloc_num_zones,
// malloc_has_debug_zone);
MALLOC_LOCK();
#if CONFIG_NANOZONE
for (index = 0; index < malloc_num_zones; ++index) {
malloc_zone_t *z = malloc_zones[index];
if (z->zone_name && strcmp(z->zone_name, MALLOC_HELPER_ZONE_STRING) == 0) {
MALLOC_UNLOCK();
return z;
}
}
#endif
for (index = 0; index < malloc_num_zones; ++index) {
malloc_zone_t *z = malloc_zones[index];
if (z->zone_name && strcmp(z->zone_name, DEFAULT_MALLOC_ZONE_STRING) == 0) {
MALLOC_UNLOCK();
return z;
}
}
MALLOC_UNLOCK();
malloc_report(ASL_LEVEL_ERR, "*** malloc_default_scalable_zone() failed to find 'DefaultMallocZone'\n");
return NULL; // FIXME: abort() instead?
}
static void *
legacy_zeroing_large_malloc(malloc_zone_t *zone, size_t size)
{
if (size > LARGE_THRESHOLD) { // Leopard and earlier returned a ZFOD range, so ...
return default_zone_calloc(zone, 1, size); // Clear to zero always, ham-handedly touching in each page
} else {
return default_zone_malloc(zone, size);
}
}
static void *
legacy_zeroing_large_valloc(malloc_zone_t *zone, size_t size)
{
void *p = default_zone_valloc(zone, size);
// Leopard and earlier returned a ZFOD range, so ...
memset(p, 0, size); // Clear to zero always, ham-handedly touching in each page
return p;
}
void
zeroify_scalable_zone(malloc_zone_t *zone)
{
// this checkfix should replace the default zone's
// allocation routines with the zeroing versions. Instead of getting in hot
// water with the wrong zone, ensure that we're mutating the zone we expect.
//
// Additionally, the default_zone is no longer PROT_READ, so the two mprotect
// calls that were here are no longer needed.
if (zone == default_zone) {
zone->malloc = (void *)legacy_zeroing_large_malloc;
zone->valloc = (void *)legacy_zeroing_large_valloc;
}
}
/*
* Returns the version of the Nano allocator that's in use, or 0 if not.
*/
int
malloc_engaged_nano(void)
{
#if CONFIG_NANOZONE
return _malloc_engaged_nano;
#else
return 0;
#endif
}
malloc_zone_t *
malloc_default_purgeable_zone(void)
{
static malloc_zone_t *dpz;
if (!dpz) {
//
// PR_7288598: Must pass a *scalable* zone (szone) as the helper for create_purgeable_zone().
// Take care that the zone so obtained is not subject to interposing.
//
malloc_zone_t *tmp = create_purgeable_zone(0, inline_malloc_default_scalable_zone(), malloc_debug_flags);
malloc_zone_register(tmp);
malloc_set_zone_name(tmp, DEFAULT_PUREGEABLE_ZONE_STRING);
if (!OSAtomicCompareAndSwapPtrBarrier(NULL, tmp, (void**)&dpz)) {
malloc_destroy_zone(tmp);
}
}
return dpz;
}
static void
set_flags_from_environment(void)
{
const char *flag;
char **env = *_NSGetEnviron();
char **p;
char *c;
#if __LP64__
malloc_debug_flags = MALLOC_ABORT_ON_CORRUPTION; // Set always on 64-bit processes
#else
int libSystemVersion = NSVersionOfLinkTimeLibrary("System");
if ((-1 != libSystemVersion) && ((libSystemVersion >> 16) < 126) /* Lion or greater */) {
malloc_debug_flags = 0;
} else {
malloc_debug_flags = MALLOC_ABORT_ON_CORRUPTION;
}
#endif
stack_logging_enable_logging = 0;
stack_logging_dontcompact = 0;
malloc_logger = NULL;
malloc_check_start = 0;
malloc_check_each = 1000;
malloc_check_abort = 0;
malloc_check_sleep = 100;
/*
* Given that all environment variables start with "Malloc" we optimize by scanning quickly
* first the environment, therefore avoiding repeated calls to getenv().
* If we are setu/gid these flags are ignored to prevent a malicious invoker from changing
* our behaviour.
*/
for (p = env; (c = *p) != NULL; ++p) {
if (!strncmp(c, "Malloc", 6)) {
if (issetugid()) {
return;
}
break;
}
}
/*
* Deny certain flags for entitled processes rdar://problem/13521742
* MallocLogFile & MallocCorruptionAbort
* as these provide the ability to turn *off* aborting in error cases.
*/
bool restricted = dyld_process_is_restricted();
malloc_print_configure(restricted);
if (c == NULL) {
return;
}
if (getenv("MallocGuardEdges")) {
malloc_debug_flags |= MALLOC_ADD_GUARD_PAGES;
malloc_report(ASL_LEVEL_INFO, "protecting edges\n");
if (getenv("MallocDoNotProtectPrelude")) {
malloc_debug_flags |= MALLOC_DONT_PROTECT_PRELUDE;
malloc_report(ASL_LEVEL_INFO, "... but not protecting prelude guard page\n");
}
if (getenv("MallocDoNotProtectPostlude")) {
malloc_debug_flags |= MALLOC_DONT_PROTECT_POSTLUDE;
malloc_report(ASL_LEVEL_INFO, "... but not protecting postlude guard page\n");
}
}
flag = getenv("MallocStackLogging");
if (!flag) {
flag = getenv("MallocStackLoggingNoCompact");
stack_logging_dontcompact = 1;
}
if (flag) {
// Set up stack logging as early as possible to catch all ensuing VM allocations,
// including those from malloc_report and malloc zone setup. Make sure to set
// __syscall_logger after this, because prepare_to_log_stacks() itself makes VM
// allocations that we aren't prepared to log yet.
boolean_t lite_or_vmlite_mode = strcmp(flag, "lite") == 0 || strcmp(flag, "vmlite") == 0;
__prepare_to_log_stacks(lite_or_vmlite_mode);
if (strcmp(flag, "lite") == 0) {
stack_logging_mode = stack_logging_mode_lite;
malloc_report(ASL_LEVEL_INFO, "recording malloc and VM allocation stacks using lite mode\n");
} else if (strcmp(flag,"malloc") == 0) {
stack_logging_mode = stack_logging_mode_malloc;
malloc_report(ASL_LEVEL_INFO, "recording malloc (but not VM allocation) stacks to disk using standard recorder\n");
} else if (strcmp(flag, "vm") == 0) {
stack_logging_mode = stack_logging_mode_vm;
malloc_report(ASL_LEVEL_INFO, "recording VM allocation (but not malloc) stacks to disk using standard recorder\n");
} else if (strcmp(flag, "vmlite") == 0) {
stack_logging_mode = stack_logging_mode_vmlite;
malloc_report(ASL_LEVEL_NOTICE, "recording VM allocation (but not malloc) stacks using lite mode\n");
} else {
stack_logging_mode = stack_logging_mode_all;
malloc_report(ASL_LEVEL_INFO, "recording malloc and VM allocation stacks to disk using standard recorder\n");
}
stack_logging_enable_logging = 1;
if (stack_logging_dontcompact) {
if (stack_logging_mode == stack_logging_mode_all || stack_logging_mode == stack_logging_mode_malloc) {
malloc_report(
ASL_LEVEL_INFO, "stack logging compaction turned off; size of log files on disk can increase rapidly\n");
} else {
malloc_report(ASL_LEVEL_INFO, "stack logging compaction turned off; VM can increase rapidly\n");
}
}
}
if (getenv("MallocScribble")) {
malloc_debug_flags |= MALLOC_DO_SCRIBBLE;
malloc_report(ASL_LEVEL_INFO, "enabling scribbling to detect mods to free blocks\n");
}
if (getenv("MallocErrorAbort")) {
malloc_debug_flags |= MALLOC_ABORT_ON_ERROR;
malloc_report(ASL_LEVEL_INFO, "enabling abort() on bad malloc or free\n");
}
if (getenv("MallocTracing")) {
malloc_tracing_enabled = true;
}
#if __LP64__
/* initialization above forces MALLOC_ABORT_ON_CORRUPTION of 64-bit processes */
#else
flag = getenv("MallocCorruptionAbort");
if (!restricted && flag && (flag[0] == '0')) { // Set from an environment variable in 32-bit processes
malloc_debug_flags &= ~MALLOC_ABORT_ON_CORRUPTION;
} else if (flag) {
malloc_debug_flags |= MALLOC_ABORT_ON_CORRUPTION;
}
#endif
flag = getenv("MallocCheckHeapStart");
if (flag) {
malloc_check_start = (unsigned)strtoul(flag, NULL, 0);
if (malloc_check_start == 0) {
malloc_check_start = 1;
}
if (malloc_check_start == -1) {
malloc_check_start = 1;
}
flag = getenv("MallocCheckHeapEach");
if (flag) {
malloc_check_each = (unsigned)strtoul(flag, NULL, 0);
if (malloc_check_each == 0) {
malloc_check_each = 1;
}
if (malloc_check_each == -1) {
malloc_check_each = 1;
}
}
malloc_report(ASL_LEVEL_INFO, "checks heap after operation #%d and each %d operations\n", malloc_check_start, malloc_check_each);
flag = getenv("MallocCheckHeapAbort");
if (flag) {
malloc_check_abort = (unsigned)strtol(flag, NULL, 0);
}
if (malloc_check_abort) {
malloc_report(ASL_LEVEL_INFO, "will abort on heap corruption\n");
} else {
flag = getenv("MallocCheckHeapSleep");
if (flag) {
malloc_check_sleep = (unsigned)strtol(flag, NULL, 0);
}
if (malloc_check_sleep > 0) {
malloc_report(ASL_LEVEL_INFO, "will sleep for %d seconds on heap corruption\n", malloc_check_sleep);
} else if (malloc_check_sleep < 0) {
malloc_report(ASL_LEVEL_INFO, "will sleep once for %d seconds on heap corruption\n", -malloc_check_sleep);
} else {
malloc_report(ASL_LEVEL_INFO, "no sleep on heap corruption\n");
}
}
}
flag = getenv("MallocMaxMagazines");
if (flag) {
int value = (unsigned)strtol(flag, NULL, 0);
if (value == 0) {
malloc_report(ASL_LEVEL_INFO, "Maximum magazines defaulted to %d\n", max_magazines);
} else if (value < 0) {
malloc_report(ASL_LEVEL_ERR, "MallocMaxMagazines must be positive - ignored.\n");
} else if (value > logical_ncpus) {
max_magazines = logical_ncpus;
malloc_report(ASL_LEVEL_INFO, "Maximum magazines limited to number of logical CPUs (%d)\n", max_magazines);
} else {
max_magazines = value;
malloc_report(ASL_LEVEL_INFO, "Maximum magazines set to %d\n", max_magazines);
}
}
#if CONFIG_RECIRC_DEPOT
flag = getenv("MallocRecircRetainedRegions");
if (flag) {
int value = (int)strtol(flag, NULL, 0);
if (value > 0) {
recirc_retained_regions = value;
} else {
malloc_report(ASL_LEVEL_ERR, "MallocRecircRetainedRegions must be positive - ignored.\n");
}
}
#endif // CONFIG_RECIRC_DEPOT
if (getenv("MallocHelp")) {
malloc_report(ASL_LEVEL_INFO,
"environment variables that can be set for debug:\n"
"- MallocLogFile to create/append messages to file instead of stderr\n"
"- MallocGuardEdges to add 2 guard pages for each large block\n"
"- MallocDoNotProtectPrelude to disable protection (when previous flag set)\n"
"- MallocDoNotProtectPostlude to disable protection (when previous flag set)\n"
"- MallocStackLogging to record all stacks. Tools like leaks can then be applied\n"
"- MallocStackLoggingNoCompact to record all stacks. Needed for malloc_history\n"
"- MallocStackLoggingDirectory to set location of stack logs, which can grow large; default is /tmp\n"
"- MallocScribble to detect writing on free blocks and missing initializers:\n"
" 0x55 is written upon free and 0xaa is written on allocation\n"
"- MallocCheckHeapStart to start checking the heap after operations\n"
"- MallocCheckHeapEach to repeat the checking of the heap after operations\n"
"- MallocCheckHeapSleep to sleep seconds on heap corruption\n"
"- MallocCheckHeapAbort to abort on heap corruption if is non-zero\n"
"- MallocCorruptionAbort to abort on malloc errors, but not on out of memory for 32-bit processes\n"
" MallocCorruptionAbort is always set on 64-bit processes\n"
"- MallocErrorAbort to abort on any malloc error, including out of memory\n"\
"- MallocTracing to emit kdebug trace points on malloc entry points\n"\
"- MallocHelp - this help!\n");
}
}
malloc_zone_t *
malloc_create_zone(vm_size_t start_size, unsigned flags)
{
malloc_zone_t *zone;
/* start_size doesn't actually appear to be used, but we test anyway. */
if (start_size > MALLOC_ABSOLUTE_MAX_SIZE) {
return NULL;
}
_malloc_initialize_once();
zone = create_scalable_zone(start_size, flags | malloc_debug_flags);
malloc_zone_register(zone);
return zone;
}
/*
* For use by CheckFix: establish a new default zone whose behavior is, apart from
* the use of death-row and per-CPU magazines, that of Leopard.
*/
void
malloc_create_legacy_default_zone(void)
{
malloc_zone_t *zone;
int i;
_malloc_initialize_once();
zone = create_legacy_scalable_zone(0, malloc_debug_flags);
MALLOC_LOCK();
malloc_zone_register_while_locked(zone);
//
// Establish the legacy scalable zone just created as the default zone.
//
malloc_zone_t *hold = malloc_zones[0];
if (hold->zone_name && strcmp(hold->zone_name, DEFAULT_MALLOC_ZONE_STRING) == 0) {
malloc_set_zone_name(hold, NULL);
}
malloc_set_zone_name(zone, DEFAULT_MALLOC_ZONE_STRING);
unsigned protect_size = malloc_num_zones_allocated * sizeof(malloc_zone_t *);
mprotect(malloc_zones, protect_size, PROT_READ | PROT_WRITE);
// assert(zone == malloc_zones[malloc_num_zones - 1];
for (i = malloc_num_zones - 1; i > 0; --i) {
malloc_zones[i] = malloc_zones[i - 1];
}
malloc_zones[0] = zone;
mprotect(malloc_zones, protect_size, PROT_READ);
MALLOC_UNLOCK();
}
void
malloc_destroy_zone(malloc_zone_t *zone)
{
malloc_set_zone_name(zone, NULL); // Deallocate zone name wherever it may reside PR_7701095
malloc_zone_unregister(zone);
zone->destroy(zone);
}
static vm_address_t *frames = NULL;
static unsigned num_frames;
MALLOC_NOINLINE
void
malloc_zone_check_fail(const char *msg, const char *fmt, ...)
{
_SIMPLE_STRING b = _simple_salloc();
if (b) {
_simple_sprintf(b, "*** MallocCheckHeap: FAILED check at operation #%d\n", malloc_check_counter - 1);
} else {
malloc_report(MALLOC_REPORT_NOLOG, "*** MallocCheckHeap: FAILED check at operation #%d\n", malloc_check_counter - 1);
}
if (frames) {
unsigned index = 1;
if (b) {
_simple_sappend(b, "Stack for last operation where the malloc check succeeded: ");
while (index < num_frames)
_simple_sprintf(b, "%p ", (void*)frames[index++]);
malloc_report(MALLOC_REPORT_NOLOG, "%s\n(Use 'atos' for a symbolic stack)\n", _simple_string(b));
} else {
/*
* Should only get here if vm_allocate() can't get a single page of
* memory, implying _simple_asl_log() would also fail. So we just
* print to the file descriptor.
*/
malloc_report(MALLOC_REPORT_NOLOG, "Stack for last operation where the malloc check succeeded: ");
while (index < num_frames) {
malloc_report(MALLOC_REPORT_NOLOG, "%p ", (void *)frames[index++]);
}
malloc_report(MALLOC_REPORT_NOLOG, "\n(Use 'atos' for a symbolic stack)\n");
}
}
if (malloc_check_each > 1) {
unsigned recomm_each = (malloc_check_each > 10) ? malloc_check_each / 10 : 1;
unsigned recomm_start =
(malloc_check_counter > malloc_check_each + 1) ? malloc_check_counter - 1 - malloc_check_each : 1;
malloc_report(MALLOC_REPORT_NOLOG,
"*** Recommend using 'setenv MallocCheckHeapStart %d; setenv MallocCheckHeapEach %d' to narrow down failure\n",
recomm_start, recomm_each);
}
if (b) {
_simple_sfree(b);
}
// Use malloc_vreport() to:
// * report the error
// * call malloc_error_break() for a breakpoint
// * sleep or stop for debug
// * set the crash message and crash if malloc_check_abort is set.
unsigned sleep_time = 0;
uint32_t report_flags = ASL_LEVEL_ERR | MALLOC_REPORT_DEBUG | MALLOC_REPORT_NOLOG;
if (malloc_check_abort) {
report_flags |= MALLOC_REPORT_CRASH;
} else {
if (malloc_check_sleep > 0) {
malloc_report(ASL_LEVEL_NOTICE, "*** Will sleep for %d seconds to leave time to attach\n", malloc_check_sleep);
sleep_time = malloc_check_sleep;
} else if (malloc_check_sleep < 0) {
malloc_report(ASL_LEVEL_NOTICE, "*** Will sleep once for %d seconds to leave time to attach\n", -malloc_check_sleep);
sleep_time = -malloc_check_sleep;
malloc_check_sleep = 0;
}
}
va_list ap;
va_start(ap, fmt);
malloc_vreport(report_flags, sleep_time, msg, NULL, fmt, ap);
va_end(ap);
}
/********* Block creation and manipulation ************/
static void
internal_check(void)
{
if (malloc_zone_check(NULL)) {
if (!frames) {
vm_allocate(mach_task_self(), (void *)&frames, vm_page_size, 1);
}
thread_stack_pcs(frames, (unsigned)(vm_page_size / sizeof(vm_address_t) - 1), &num_frames);
}
malloc_check_start += malloc_check_each;
}
void *
malloc_zone_malloc(malloc_zone_t *zone, size_t size)
{
MALLOC_TRACE(TRACE_malloc | DBG_FUNC_START, (uintptr_t)zone, size, 0, 0);
void *ptr;
if (malloc_check_start && (malloc_check_counter++ >= malloc_check_start)) {
internal_check();
}
if (size > MALLOC_ABSOLUTE_MAX_SIZE) {
return NULL;
}
ptr = zone->malloc(zone, size); // if lite zone is passed in then we still call the lite methods
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);
}
MALLOC_TRACE(TRACE_malloc | DBG_FUNC_END, (uintptr_t)zone, size, (uintptr_t)ptr, 0);
return ptr;
}
void *
malloc_zone_calloc(malloc_zone_t *zone, size_t num_items, size_t size)
{
MALLOC_TRACE(TRACE_calloc | DBG_FUNC_START, (uintptr_t)zone, num_items, size, 0);
void *ptr;
if (malloc_check_start && (malloc_check_counter++ >= malloc_check_start)) {
internal_check();
}
ptr = zone->calloc(zone, num_items, size);
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);
}
MALLOC_TRACE(TRACE_calloc | DBG_FUNC_END, (uintptr_t)zone, num_items, size, (uintptr_t)ptr);
return ptr;
}
void *
malloc_zone_valloc(malloc_zone_t *zone, size_t size)
{
MALLOC_TRACE(TRACE_valloc | DBG_FUNC_START, (uintptr_t)zone, size, 0, 0);
void *ptr;
if (malloc_check_start && (malloc_check_counter++ >= malloc_check_start)) {
internal_check();
}
if (size > MALLOC_ABSOLUTE_MAX_SIZE) {
return NULL;
}
ptr = zone->valloc(zone, size);
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);
}
MALLOC_TRACE(TRACE_valloc | DBG_FUNC_END, (uintptr_t)zone, size, (uintptr_t)ptr, 0);
return ptr;
}
void *
malloc_zone_realloc(malloc_zone_t *zone, void *ptr, size_t size)
{
MALLOC_TRACE(TRACE_realloc | DBG_FUNC_START, (uintptr_t)zone, (uintptr_t)ptr, size, 0);
void *new_ptr;
if (malloc_check_start && (malloc_check_counter++ >= malloc_check_start)) {
internal_check();
}
if (size > MALLOC_ABSOLUTE_MAX_SIZE) {
return NULL;
}
new_ptr = zone->realloc(zone, ptr, size);
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);
}
MALLOC_TRACE(TRACE_realloc | DBG_FUNC_END, (uintptr_t)zone, (uintptr_t)ptr, size, (uintptr_t)new_ptr);
return new_ptr;
}
void
malloc_zone_free(malloc_zone_t *zone, void *ptr)
{
MALLOC_TRACE(TRACE_free, (uintptr_t)zone, (uintptr_t)ptr, (ptr) ? *(uintptr_t*)ptr : 0, 0);
if (malloc_logger) {
malloc_logger(MALLOC_LOG_TYPE_DEALLOCATE | MALLOC_LOG_TYPE_HAS_ZONE, (uintptr_t)zone, (uintptr_t)ptr, 0, 0, 0);
}
if (malloc_check_start && (malloc_check_counter++ >= malloc_check_start)) {
internal_check();
}
zone->free(zone, ptr);
}
static void
malloc_zone_free_definite_size(malloc_zone_t *zone, void *ptr, size_t size)
{
MALLOC_TRACE(TRACE_free, (uintptr_t)zone, (uintptr_t)ptr, size, (ptr && size) ? *(uintptr_t*)ptr : 0);
if (malloc_logger) {
malloc_logger(MALLOC_LOG_TYPE_DEALLOCATE | MALLOC_LOG_TYPE_HAS_ZONE, (uintptr_t)zone, (uintptr_t)ptr, 0, 0, 0);
}
if (malloc_check_start && (malloc_check_counter++ >= malloc_check_start)) {
internal_check();
}
zone->free_definite_size(zone, ptr, size);
}
malloc_zone_t *
malloc_zone_from_ptr(const void *ptr)
{
if (!ptr) {
return NULL;
} else {
return find_registered_zone(ptr, NULL);
}
}
void *
malloc_zone_memalign(malloc_zone_t *zone, size_t alignment, size_t size)
{
MALLOC_TRACE(TRACE_memalign | DBG_FUNC_START, (uintptr_t)zone, alignment, size, 0);
void *ptr;
if (zone->version < 5) { // Version must be >= 5 to look at the new memalign field.
return NULL;
}
if (malloc_check_start && (malloc_check_counter++ >= malloc_check_start)) {
internal_check();
}
if (size > MALLOC_ABSOLUTE_MAX_SIZE) {
return NULL;
}
if (alignment < sizeof(void *) || // excludes 0 == alignment
0 != (alignment & (alignment - 1))) { // relies on sizeof(void *) being a power of two.
return NULL;
}
if (!(zone->memalign)) {
return NULL;
}
ptr = zone->memalign(zone, alignment, size);
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);
}
MALLOC_TRACE(TRACE_memalign | DBG_FUNC_END, (uintptr_t)zone, alignment, size, (uintptr_t)ptr);
return ptr;
}
boolean_t
malloc_zone_claimed_address(malloc_zone_t *zone, void *ptr)
{
if (!ptr) {
// NULL is not a member of any zone.
return false;
}
if (malloc_check_start && (malloc_check_counter++ >= malloc_check_start)) {
internal_check();
}
if (zone->version < 10 || !zone->claimed_address) {
// For zones that have not implemented claimed_address, we always have
// to return true to avoid a false negative.
return true;
}
return zone->claimed_address(zone, ptr);
}
/********* Functions for zone implementors ************/
void
malloc_zone_register(malloc_zone_t *zone)
{
MALLOC_LOCK();
malloc_zone_register_while_locked(zone);
MALLOC_UNLOCK();
}
void
malloc_zone_unregister(malloc_zone_t *z)
{
unsigned index;
if (malloc_num_zones == 0) {
return;
}
MALLOC_LOCK();
for (index = 0; index < malloc_num_zones; ++index) {
if (z != malloc_zones[index]) {
continue;
}
// Modify the page to be allow write access, so that we can update the
// malloc_zones array.
size_t protect_size = malloc_num_zones_allocated * sizeof(malloc_zone_t *);
mprotect(malloc_zones, protect_size, PROT_READ | PROT_WRITE);
// If we found a match, replace it with the entry at the end of the list, shrink the list,
// and leave the end of the list intact to avoid racing with find_registered_zone().
malloc_zones[index] = malloc_zones[malloc_num_zones - 1];
--malloc_num_zones;
mprotect(malloc_zones, protect_size, PROT_READ);
// Exchange the roles of the FRZ counters. The counter that has captured the number of threads presently
// executing *inside* find_regiatered_zone is swapped with the counter drained to zero last time through.
// The former is then allowed to drain to zero while this thread yields.
int32_t volatile *p = pFRZCounterLive;
pFRZCounterLive = pFRZCounterDrain;
pFRZCounterDrain = p;
OSMemoryBarrier(); // Full memory barrier
while (0 != *pFRZCounterDrain) {
yield();
}
MALLOC_UNLOCK();
return;
}
MALLOC_UNLOCK();
malloc_report(ASL_LEVEL_ERR, "*** malloc_zone_unregister() failed for %p\n", z);
}
void
malloc_set_zone_name(malloc_zone_t *z, const char *name)
{
char *newName;
mprotect(z, sizeof(malloc_zone_t), PROT_READ | PROT_WRITE);
if (z->zone_name) {
free((char *)z->zone_name);
z->zone_name = NULL;
}
if (name) {
size_t buflen = strlen(name) + 1;
newName = malloc_zone_malloc(z, buflen);
if (newName) {
strlcpy(newName, name, buflen);
z->zone_name = (const char *)newName;
} else {
z->zone_name = NULL;
}
}
mprotect(z, sizeof(malloc_zone_t), PROT_READ);
}
const char *
malloc_get_zone_name(malloc_zone_t *zone)
{
return zone->zone_name;
}
/********* Generic ANSI callouts ************/
void *
malloc(size_t size)
{
void *retval;
retval = malloc_zone_malloc(default_zone, size);
if (retval == NULL) {
errno = ENOMEM;
}
return retval;
}
void *
calloc(size_t num_items, size_t size)
{
void *retval;
retval = malloc_zone_calloc(default_zone, num_items, size);
if (retval == NULL) {
errno = ENOMEM;
}
return retval;
}
void
free(void *ptr)
{
malloc_zone_t *zone;
size_t size;
if (!ptr) {
return;
}
zone = find_registered_zone(ptr, &size);
if (!zone) {
int flags = MALLOC_REPORT_DEBUG | MALLOC_REPORT_NOLOG;
if ((malloc_debug_flags & (MALLOC_ABORT_ON_CORRUPTION | MALLOC_ABORT_ON_ERROR))) {
flags = MALLOC_REPORT_CRASH | MALLOC_REPORT_NOLOG;
}
malloc_report(flags,
"*** error for object %p: pointer being freed was not allocated\n", ptr);
} else if (zone->version >= 6 && zone->free_definite_size) {
malloc_zone_free_definite_size(zone, ptr, size);
} else {
malloc_zone_free(zone, ptr);
}
}
void *
realloc(void *in_ptr, size_t new_size)
{
void *retval = NULL;
void *old_ptr;
malloc_zone_t *zone;
// SUSv3: "If size is 0 and ptr is not a null pointer, the object
// pointed to is freed. If the space cannot be allocated, the object
// shall remain unchanged." Also "If size is 0, either a null pointer
// or a unique pointer that can be successfully passed to free() shall
// be returned." We choose to allocate a minimum size object by calling
// malloc_zone_malloc with zero size, which matches "If ptr is a null
// pointer, realloc() shall be equivalent to malloc() for the specified
// size." So we only free the original memory if the allocation succeeds.
old_ptr = (new_size == 0) ? NULL : in_ptr;
if (!old_ptr) {
retval = malloc_zone_malloc(default_zone, new_size);
} else {
zone = find_registered_zone(old_ptr, NULL);
if (!zone) {
int flags = MALLOC_REPORT_DEBUG | MALLOC_REPORT_NOLOG;
if (malloc_debug_flags & (MALLOC_ABORT_ON_CORRUPTION | MALLOC_ABORT_ON_ERROR)) {
flags = MALLOC_REPORT_CRASH | MALLOC_REPORT_NOLOG;
}
malloc_report(flags, "*** error for object %p: pointer being realloc'd was not allocated\n", in_ptr);
} else {
retval = malloc_zone_realloc(zone, old_ptr, new_size);
}
}
if (retval == NULL) {
errno = ENOMEM;
} else if (new_size == 0) {
free(in_ptr);
}
return retval;
}
void *
valloc(size_t size)
{
void *retval;
malloc_zone_t *zone = default_zone;
retval = malloc_zone_valloc(zone, size);
if (retval == NULL) {
errno = ENOMEM;
}
return retval;
}
extern void
vfree(void *ptr)
{
free(ptr);
}
size_t
malloc_size(const void *ptr)
{
size_t size = 0;
if (!ptr) {
return size;
}
(void)find_registered_zone(ptr, &size);
return size;
}
size_t
malloc_good_size(size_t size)
{
malloc_zone_t *zone = default_zone;
return zone->introspect->good_size(zone, size);
}
/*
* The posix_memalign() function shall allocate size bytes aligned on a boundary specified by alignment,
* and shall return a pointer to the allocated memory in memptr.
* The value of alignment shall be a multiple of sizeof( void *), that is also a power of two.
* Upon successful completion, the value pointed to by memptr shall be a multiple of alignment.
*
* Upon successful completion, posix_memalign() shall return zero; otherwise,
* an error number shall be returned to indicate the error.
*
* The posix_memalign() function shall fail if:
* EINVAL
* The value of the alignment parameter is not a power of two multiple of sizeof( void *).
* ENOMEM
* There is insufficient memory available with the requested alignment.
*/
int
posix_memalign(void **memptr, size_t alignment, size_t size)
{
void *retval;
/* POSIX is silent on NULL == memptr !?! */
retval = malloc_zone_memalign(default_zone, alignment, size);
if (retval == NULL) {
// To avoid testing the alignment constraints redundantly, we'll rely on the
// test made in malloc_zone_memalign to vet each request. Only if that test fails
// and returns NULL, do we arrive here to detect the bogus alignment and give the
// required EINVAL return.
if (alignment < sizeof(void *) || // excludes 0 == alignment
0 != (alignment & (alignment - 1))) { // relies on sizeof(void *) being a power of two.
return EINVAL;
}
return ENOMEM;
} else {
*memptr = retval; // Set iff allocation succeeded
return 0;
}
}
boolean_t
malloc_claimed_address(void *ptr)
{
// We need to check with each registered zone whether it claims "ptr".
// Use logic similar to that in find_registered_zone().
if (malloc_num_zones == 0) {
return false;
}
// Start with the lite zone, if it's in use.
if (lite_zone && malloc_zone_claimed_address(lite_zone, ptr)) {
return true;
}
// Next, try the default zone, which is always present.
if (malloc_zone_claimed_address(malloc_zones[0], ptr)) {
return true;
}
// Try all the other zones. Increment the FRZ barrier so that we can
// walk the zones array without a lock (see find_registered_zone() for
// the details).
int32_t volatile *pFRZCounter = pFRZCounterLive;
OSAtomicIncrement32Barrier(pFRZCounter);
int32_t limit = *(int32_t volatile *)&malloc_num_zones;
malloc_zone_t **zones = &malloc_zones[1];
boolean_t result = false;
for (unsigned index = 1; index < limit; ++index, ++zones) {
malloc_zone_t *zone = *zones;
if (malloc_zone_claimed_address(zone, ptr)) {
result = true;
break;
}
}
OSAtomicDecrement32Barrier(pFRZCounter);
return result;
}
void *
reallocarray(void * in_ptr, size_t nmemb, size_t size){
size_t alloc_size;
if (os_mul_overflow(nmemb, size, &alloc_size)){
errno = ENOMEM;
return NULL;
}
return realloc(in_ptr, alloc_size);
}
void *
reallocarrayf(void * in_ptr, size_t nmemb, size_t size){
size_t alloc_size;
if (os_mul_overflow(nmemb, size, &alloc_size)){
errno = ENOMEM;
return NULL;
}
return reallocf(in_ptr, alloc_size);
}
static malloc_zone_t *
find_registered_purgeable_zone(void *ptr)
{
if (!ptr) {
return NULL;
}
/*
* Look for a zone which contains ptr. If that zone does not have the purgeable malloc flag
* set, or the allocation is too small, do nothing. Otherwise, set the allocation volatile.
* FIXME: for performance reasons, we should probably keep a separate list of purgeable zones
* and only search those.
*/
size_t size = 0;
malloc_zone_t *zone = find_registered_zone(ptr, &size);
/* FIXME: would really like a zone->introspect->flags->purgeable check, but haven't determined
* binary compatibility impact of changing the introspect struct yet. */
if (!zone) {
return NULL;
}
/* Check to make sure pointer is page aligned and size is multiple of page size */
if ((size < vm_page_size) || ((size % vm_page_size) != 0)) {
return NULL;
}
return zone;
}
void
malloc_make_purgeable(void *ptr)
{
malloc_zone_t *zone = find_registered_purgeable_zone(ptr);
if (!zone) {
return;
}
int state = VM_PURGABLE_VOLATILE;
vm_purgable_control(mach_task_self(), (vm_address_t)ptr, VM_PURGABLE_SET_STATE, &state);
return;
}
/* Returns true if ptr is valid. Ignore the return value from vm_purgeable_control and only report
* state. */
int
malloc_make_nonpurgeable(void *ptr)
{
malloc_zone_t *zone = find_registered_purgeable_zone(ptr);
if (!zone) {
return 0;
}
int state = VM_PURGABLE_NONVOLATILE;
vm_purgable_control(mach_task_self(), (vm_address_t)ptr, VM_PURGABLE_SET_STATE, &state);
if (state == VM_PURGABLE_EMPTY) {
return EFAULT;
}
return 0;
}
void
malloc_enter_process_memory_limit_warn_mode(void)
{
//
}
#if ENABLE_MEMORY_RESOURCE_EXCEPTION_HANDLING
// Is the system elible to turn on/off MSL lite in response to memory resource exceptions
//
// Return true if
// - The user has not explicitly opted out
// and
// - Either the user has explicitly opted in or this is an Apple Internal enabled build
static boolean_t
check_is_eligible_for_lite_mode_mre_handling(void)
{
struct stat stat_buf;
// User opted out
if (stat("/var/db/disableLiteModeMemoryResourceExceptionHandling", &stat_buf) == 0) {
return false;
}
// User opted in
if (stat("/var/db/enableLiteModeMemoryResourceExceptionHandling", &stat_buf) == 0) {
return true;
}
// Not enabled for everything else
return false;
}
// Not thread-safe, but it's called from malloc_memory_event_handler which already assumes
// single thread execution.
static boolean_t
is_eligible_for_lite_mode_mre_handling(void)
{
static boolean_t is_eligible = false;
static boolean_t needs_check = true;
if (needs_check) {
is_eligible = check_is_eligible_for_lite_mode_mre_handling();
needs_check = false;
}
return is_eligible;
}
#endif
static void
handle_msl_memory_event(unsigned long event)
{
// don't mix and match enabling mechanisms
if (warn_mode_entered) {
return;
}
event &= NOTE_MEMORYSTATUS_MSL_STATUS;
// sanity check
if (event == 0) {
return;
}
// first check if the disable bit is set
if (event & MEMORYSTATUS_DISABLE_MSL) {
turn_off_stack_logging();
return;
}
boolean_t msl_malloc = (event & MEMORYSTATUS_ENABLE_MSL_MALLOC);
boolean_t msl_vm = (event & MEMORYSTATUS_ENABLE_MSL_VM);
boolean_t msl_lite = (event & MEMORYSTATUS_ENABLE_MSL_LITE);
// The following ensures it's not possible to enable two different modes
// For instance this would not be allowed:
// Enable lite
// Disable
// Enable full
if (msl_lite) {
if (msl_vm && msl_malloc) {
if (msl_type_enabled_at_runtime == stack_logging_mode_none || msl_type_enabled_at_runtime == stack_logging_mode_lite) {
msl_type_enabled_at_runtime = stack_logging_mode_lite;
turn_on_stack_logging(stack_logging_mode_lite);
}
} else if (msl_vm) {
if (msl_type_enabled_at_runtime == stack_logging_mode_none || msl_type_enabled_at_runtime == stack_logging_mode_vmlite) {
msl_type_enabled_at_runtime = stack_logging_mode_vmlite;
turn_on_stack_logging(stack_logging_mode_vmlite);
}
}
return;
} else if (msl_malloc && msl_vm) {
if (msl_type_enabled_at_runtime == stack_logging_mode_none || msl_type_enabled_at_runtime == stack_logging_mode_all) {
msl_type_enabled_at_runtime = stack_logging_mode_all;
turn_on_stack_logging(stack_logging_mode_all);
}
return;
} else if (msl_malloc) {
if (msl_type_enabled_at_runtime == stack_logging_mode_none || msl_type_enabled_at_runtime == stack_logging_mode_malloc) {
msl_type_enabled_at_runtime = stack_logging_mode_malloc;
turn_on_stack_logging(stack_logging_mode_malloc);
}
return;
} else if (msl_vm) {
if (msl_type_enabled_at_runtime == stack_logging_mode_none || msl_type_enabled_at_runtime == stack_logging_mode_vm) {
msl_type_enabled_at_runtime = stack_logging_mode_vm;
turn_on_stack_logging(stack_logging_mode_vm);
}
return;
}
}
// Note that malloc_memory_event_handler is not thread-safe, and we are relying on the callers of this for synchronization
void
malloc_memory_event_handler(unsigned long event)
{
if (event & NOTE_MEMORYSTATUS_PRESSURE_WARN) {
malloc_zone_pressure_relief(0, 0);
}
// First check for enable/disable MSL - only recognize if all other bits are 0
// Don't attempt this if we've either entered or exited MRE mode
if ((event & NOTE_MEMORYSTATUS_MSL_STATUS) != 0 && (event & ~NOTE_MEMORYSTATUS_MSL_STATUS) == 0 && !warn_mode_entered && !warn_mode_disable_retries) {
handle_msl_memory_event(event);
return;
}
#if ENABLE_MEMORY_RESOURCE_EXCEPTION_HANDLING
// If we have reached EXC_RESOURCE, we no longer need stack log data.
// If we are under system-wide memory pressure, we should jettison stack log data.
if ((event & (NOTE_MEMORYSTATUS_PROC_LIMIT_CRITICAL | NOTE_MEMORYSTATUS_PRESSURE_CRITICAL)) &&
!warn_mode_disable_retries) {
// If we have crossed the EXC_RESOURCE limit once already, there is no point in
// collecting stack logs in the future, even if we missed a previous chance to
// collect data because nobody is going to ask us for it again.
warn_mode_disable_retries = true;
// Only try to clean up stack log data if it was enabled through a proc limit warning.
// User initiated stack logging should proceed unimpeded.
if (warn_mode_entered) {
malloc_report(ASL_LEVEL_INFO, "malloc_memory_event_handler: stopping stack-logging\n");
turn_off_stack_logging();
__malloc_lock_stack_logging();
__delete_uniquing_table_memory_while_locked();
__malloc_unlock_stack_logging();
warn_mode_entered = false;
}
}
// Enable stack logging if we are approaching the process limit, provided
// we aren't under system wide memory pressure and we're allowed to try again.
if ((event & NOTE_MEMORYSTATUS_PROC_LIMIT_WARN) &&
!(event & NOTE_MEMORYSTATUS_PRESSURE_CRITICAL) &&
!warn_mode_entered && !warn_mode_disable_retries &&
is_eligible_for_lite_mode_mre_handling()) {
malloc_report(ASL_LEVEL_INFO, "malloc_memory_event_handler: approaching memory limit. Starting stack-logging.\n");
if (turn_on_stack_logging(stack_logging_mode_lite)) {
warn_mode_entered = true;
// set the maximum allocation threshold
max_lite_mallocs = MAX_LITE_MALLOCS;
}
}
#endif
}
size_t
malloc_zone_pressure_relief(malloc_zone_t *zone, size_t goal)
{
if (!zone) {
unsigned index = 0;
size_t total = 0;
// Take lock to defend against malloc_destroy_zone()
MALLOC_LOCK();
while (index < malloc_num_zones) {
zone = malloc_zones[index++];
if (zone->version < 8) {
continue;
}
if (NULL == zone->pressure_relief) {
continue;
}
if (0 == goal) { /* Greedy */
total += zone->pressure_relief(zone, 0);
} else if (goal > total) {
total += zone->pressure_relief(zone, goal - total);
} else { /* total >= goal */
break;
}
}
MALLOC_UNLOCK();
return total;
} else {
// Assumes zone is not destroyed for the duration of this call
if (zone->version < 8) {
return 0;
}
if (NULL == zone->pressure_relief) {
return 0;
}
return zone->pressure_relief(zone, goal);
}
}
/********* Batch methods ************/
unsigned
malloc_zone_batch_malloc(malloc_zone_t *zone, size_t size, void **results, unsigned num_requested)
{
if (!zone->batch_malloc) {
return 0;
}
if (malloc_check_start && (malloc_check_counter++ >= malloc_check_start)) {
internal_check();
}
unsigned batched = zone->batch_malloc(zone, size, results, num_requested);
if (malloc_logger) {
unsigned index = 0;
while (index < batched) {
malloc_logger(MALLOC_LOG_TYPE_ALLOCATE | MALLOC_LOG_TYPE_HAS_ZONE, (uintptr_t)zone, (uintptr_t)size, 0,
(uintptr_t)results[index], 0);
index++;
}
}
return batched;
}
void
malloc_zone_batch_free(malloc_zone_t *zone, void **to_be_freed, unsigned num)
{
if (malloc_check_start && (malloc_check_counter++ >= malloc_check_start)) {
internal_check();
}
if (malloc_logger) {
unsigned index = 0;
while (index < num) {
malloc_logger(
MALLOC_LOG_TYPE_DEALLOCATE | MALLOC_LOG_TYPE_HAS_ZONE, (uintptr_t)zone, (uintptr_t)to_be_freed[index], 0, 0, 0);
index++;
}
}
if (zone->batch_free) {
zone->batch_free(zone, to_be_freed, num);
} else {
void (*free_fun)(malloc_zone_t *, void *) = zone->free;
while (num--) {
void *ptr = *to_be_freed++;
free_fun(zone, ptr);
}
}
}
/********* Functions for performance tools ************/
static kern_return_t
_malloc_default_reader(task_t task, vm_address_t address, vm_size_t size, void **ptr)
{
*ptr = (void *)address;
return 0;
}
kern_return_t
malloc_get_all_zones(task_t task, memory_reader_t reader, vm_address_t **addresses, unsigned *count)
{
// 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 )
vm_address_t remote_malloc_zones = (vm_address_t)&malloc_zones;
vm_address_t remote_malloc_num_zones = (vm_address_t)&malloc_num_zones;
kern_return_t err;
vm_address_t zones_address;
vm_address_t *zones_address_ref;
unsigned num_zones;
unsigned *num_zones_ref;
if (!reader) {
reader = _malloc_default_reader;
}
// printf("Read malloc_zones at address %p should be %p\n", &malloc_zones, malloc_zones);
err = reader(task, remote_malloc_zones, sizeof(void *), (void **)&zones_address_ref);
// printf("Read malloc_zones[%p]=%p\n", remote_malloc_zones, *zones_address_ref);
if (err) {
malloc_report(ASL_LEVEL_ERR, "*** malloc_get_all_zones: error reading zones_address at %p\n", (void *)remote_malloc_zones);
return err;
}
zones_address = *zones_address_ref;
// printf("Reading num_zones at address %p\n", remote_malloc_num_zones);
err = reader(task, remote_malloc_num_zones, sizeof(unsigned), (void **)&num_zones_ref);
if (err) {
malloc_report(ASL_LEVEL_ERR, "*** malloc_get_all_zones: error reading num_zones at %p\n", (void *)remote_malloc_num_zones);
return err;
}
num_zones = *num_zones_ref;
// printf("Read malloc_num_zones[%p]=%d\n", remote_malloc_num_zones, num_zones);
*count = num_zones;
// printf("malloc_get_all_zones succesfully found %d zones\n", num_zones);
err = reader(task, zones_address, sizeof(malloc_zone_t *) * num_zones, (void **)addresses);
if (err) {
malloc_report(ASL_LEVEL_ERR, "*** malloc_get_all_zones: error reading zones at %p\n", &zones_address);
return err;
}
// printf("malloc_get_all_zones succesfully read %d zones\n", num_zones);
return err;
}
/********* Debug helpers ************/
void
malloc_zone_print_ptr_info(void *ptr)
{
malloc_zone_t *zone;
if (!ptr) {
return;
}
zone = malloc_zone_from_ptr(ptr);
if (zone) {
printf("ptr %p in registered zone %p\n", ptr, zone);
} else {
printf("ptr %p not in heap\n", ptr);
}
}
boolean_t
malloc_zone_check(malloc_zone_t *zone)
{
boolean_t ok = 1;
if (!zone) {
unsigned index = 0;
while (index < malloc_num_zones) {
zone = malloc_zones[index++];
if (!zone->introspect->check(zone)) {
ok = 0;
}
}
} else {
ok = zone->introspect->check(zone);
}
return ok;
}
void
malloc_zone_print(malloc_zone_t *zone, boolean_t verbose)
{
if (!zone) {
unsigned index = 0;
while (index < malloc_num_zones) {
zone = malloc_zones[index++];
zone->introspect->print(zone, verbose);
}
} else {
zone->introspect->print(zone, verbose);
}
}
void
malloc_zone_statistics(malloc_zone_t *zone, malloc_statistics_t *stats)
{
if (!zone) {
memset(stats, 0, sizeof(*stats));
unsigned index = 0;
while (index < malloc_num_zones) {
zone = malloc_zones[index++];
malloc_statistics_t this_stats;
zone->introspect->statistics(zone, &this_stats);
stats->blocks_in_use += this_stats.blocks_in_use;
stats->size_in_use += this_stats.size_in_use;
stats->max_size_in_use += this_stats.max_size_in_use;
stats->size_allocated += this_stats.size_allocated;
}
} else {
zone->introspect->statistics(zone, stats);
}
}
void
malloc_zone_log(malloc_zone_t *zone, void *address)
{
if (!zone) {
unsigned index = 0;
while (index < malloc_num_zones) {
zone = malloc_zones[index++];
zone->introspect->log(zone, address);
}
} else {
zone->introspect->log(zone, address);
}
}
/********* Misc other entry points ************/
void
mag_set_thread_index(unsigned int index)
{
_os_cpu_number_override = index;
#if CONFIG_NANOZONE
nano_common_cpu_number_override_set();
#endif // CONFIG_NANOZONE
}
static void
DefaultMallocError(int x)
{
#if USE_SLEEP_RATHER_THAN_ABORT
malloc_report(ASL_LEVEL_ERR, "*** error %d\n", x);
sleep(3600);
#else
_SIMPLE_STRING b = _simple_salloc();
if (b) {
_simple_sprintf(b, "*** error %d", x);
malloc_report(MALLOC_REPORT_NOLOG, "%s\n", _simple_string(b));
_os_set_crash_log_message_dynamic(_simple_string(b));
} else {
malloc_report(MALLOC_REPORT_NOLOG, "*** error %d\n", x);
_os_set_crash_log_message("*** DefaultMallocError called");
}
abort();
#endif
}
void (*malloc_error(void (*func)(int)))(int)
{
return DefaultMallocError;
}
static void
_malloc_lock_all(void (*callout)(void))
{
unsigned index = 0;
MALLOC_LOCK();
while (index < malloc_num_zones) {
malloc_zone_t *zone = malloc_zones[index++];
zone->introspect->force_lock(zone);
}
callout();
}
static void
_malloc_unlock_all(void (*callout)(void))
{
unsigned index = 0;
callout();
while (index < malloc_num_zones) {
malloc_zone_t *zone = malloc_zones[index++];
zone->introspect->force_unlock(zone);
}
MALLOC_UNLOCK();
}
static void
_malloc_reinit_lock_all(void (*callout)(void))
{
unsigned index = 0;
callout();
while (index < malloc_num_zones) {
malloc_zone_t *zone = malloc_zones[index++];
if (zone->version < 9) { // Version must be >= 9 to look at reinit_lock
zone->introspect->force_unlock(zone);
} else {
zone->introspect->reinit_lock(zone);
}
}
MALLOC_REINIT_LOCK();
}
// Called prior to fork() to guarantee that malloc is not in any critical
// sections during the fork(); prevent any locks from being held by non-
// surviving threads after the fork.
void
_malloc_fork_prepare(void)
{
return _malloc_lock_all(&__stack_logging_fork_prepare);
}
// Called in the parent process after fork() to resume normal operation.
void
_malloc_fork_parent(void)
{
return _malloc_unlock_all(&__stack_logging_fork_parent);
}
// Called in the child process after fork() to resume normal operation.
void
_malloc_fork_child(void)
{
#if CONFIG_NANOZONE
if (_malloc_initialize_pred) {
if (_malloc_engaged_nano == NANO_V2) {
nanov2_forked_zone((nanozonev2_t *)inline_malloc_default_zone());
} else if (_malloc_engaged_nano == NANO_V1) {
nano_forked_zone((nanozone_t *)inline_malloc_default_zone());
}
}
#endif
return _malloc_reinit_lock_all(&__stack_logging_fork_child);
}
/*
* A Glibc-like mstats() interface.
*
* Note that this interface really isn't very good, as it doesn't understand
* that we may have multiple allocators running at once. We just massage
* the result from malloc_zone_statistics in any case.
*/
struct mstats
mstats(void)
{
malloc_statistics_t s;
struct mstats m;
malloc_zone_statistics(NULL, &s);
m.bytes_total = s.size_allocated;
m.chunks_used = s.blocks_in_use;
m.bytes_used = s.size_in_use;
m.chunks_free = 0;
m.bytes_free = m.bytes_total - m.bytes_used; /* isn't this somewhat obvious? */
return (m);
}
boolean_t
malloc_zone_enable_discharge_checking(malloc_zone_t *zone)
{
if (zone->version < 7) { // Version must be >= 7 to look at the new discharge checking fields.
return FALSE;
}
if (NULL == zone->introspect->enable_discharge_checking) {
return FALSE;
}
return zone->introspect->enable_discharge_checking(zone);
}
void
malloc_zone_disable_discharge_checking(malloc_zone_t *zone)
{
if (zone->version < 7) { // Version must be >= 7 to look at the new discharge checking fields.
return;
}
if (NULL == zone->introspect->disable_discharge_checking) {
return;
}
zone->introspect->disable_discharge_checking(zone);
}
void
malloc_zone_discharge(malloc_zone_t *zone, void *memory)
{
if (NULL == zone) {
zone = malloc_zone_from_ptr(memory);
}
if (NULL == zone) {
return;
}
if (zone->version < 7) { // Version must be >= 7 to look at the new discharge checking fields.
return;
}
if (NULL == zone->introspect->discharge) {
return;
}
zone->introspect->discharge(zone, memory);
}
void
malloc_zone_enumerate_discharged_pointers(malloc_zone_t *zone, void (^report_discharged)(void *memory, void *info))
{
if (!zone) {
unsigned index = 0;
while (index < malloc_num_zones) {
zone = malloc_zones[index++];
if (zone->version < 7) {
continue;
}
if (NULL == zone->introspect->enumerate_discharged_pointers) {
continue;
}
zone->introspect->enumerate_discharged_pointers(zone, report_discharged);
}
} else {
if (zone->version < 7) {
return;
}
if (NULL == zone->introspect->enumerate_discharged_pointers) {
return;
}
zone->introspect->enumerate_discharged_pointers(zone, report_discharged);
}
}
/***************** OBSOLETE ENTRY POINTS ********************/
#if PHASE_OUT_OLD_MALLOC
#error PHASE OUT THE FOLLOWING FUNCTIONS
#endif
void
set_malloc_singlethreaded(boolean_t single)
{
static boolean_t warned = 0;
if (!warned) {
#if PHASE_OUT_OLD_MALLOC
malloc_report(ASL_LEVEL_ERR, "*** OBSOLETE: set_malloc_singlethreaded(%d)\n", single);
#endif
warned = 1;
}
}
void
malloc_singlethreaded(void)
{
static boolean_t warned = 0;
if (!warned) {
malloc_report(ASL_LEVEL_ERR, "*** OBSOLETE: malloc_singlethreaded()\n");
warned = 1;
}
}
int
malloc_debug(int level)
{
malloc_report(ASL_LEVEL_ERR, "*** OBSOLETE: malloc_debug()\n");
return 0;
}
/* vim: set noet:ts=4:sw=4:cindent: */
================================================
FILE: InterView-obj-isa-class/libmalloc-166.220.1/src/malloc_common.c
================================================
/*
* Copyright (c) 2018 Apple Inc. All rights reserved.
*
* @APPLE_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apple Public Source License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. Please obtain a copy of the License at
* http://www.opensource.apple.com/apsl/ and read it before using this
* file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPLE_LICENSE_HEADER_END@
*/
#include "internal.h"
#pragma mark -
#pragma mark Utility Functions
// libplatform does not have strstr() and we don't want to add any new
// dependencies on libc, so we have to implement a version of strntr()
// here. Fortunately, as it's only used to look for boot arguments, it does not
// have to be efficient. We can also assume that the source string is
// nul-terminated. Eventually, we will move the function to a more central
// location and use it to replace other uses of strstr().
const char *
malloc_common_strstr(const char *src, const char *target, size_t target_len)
{
const char *next = src;
while (*next) {
if (!strncmp(next, target, target_len)) {
return next;
}
next++;
}
return NULL;
}
// Converts a string to a long. If a non-numeric value is found, the
// return value is whatever has been accumulated so far. end_ptr always points
// to the character that caused the conversion to stop. We can't use strtol()
// etc because that would add a new dependency on libc. Eventually, this
// function could be made generally available within the library and used to
// replace the existing calls to strtol(). Currenly only handles non-negative
// numbers and does not detect overflow.
long
malloc_common_convert_to_long(const char *ptr, const char **end_ptr)
{
long value = 0;
while (*ptr) {
char c = *ptr;
if (c < '0' || c > '9') {
break;
}
value = value * 10 + (c - '0');
ptr++;
}
*end_ptr = ptr;
return value;
}
// Looks for a sequence of the form "key=value" in the string 'src' and
// returns the location of the first character of 'value', or NULL if not
// found. No spaces are permitted around the "=".
const char *
malloc_common_value_for_key(const char *src, const char *key)
{
const char *ptr = src;
size_t keylen = strlen(key);
while ((ptr = malloc_common_strstr(ptr, key, keylen)) != NULL) {
ptr += keylen;
if (*ptr == '=') {
return ptr + 1;
}
}
return NULL;
}
// Looks for a sequence of the form "key=value" in the string 'src' and
// returns the location of the first character of 'value'. No spaces are
// permitted around the "=". The value is copied to 'bufp', up to the first
// whitespace or nul character and bounded by maxlen, and nul-terminated.
// Returns bufp if the key was found, NULL if not.
const char *
malloc_common_value_for_key_copy(const char *src, const char *key,
char *bufp, size_t maxlen)
{
const char *ptr = malloc_common_value_for_key(src, key);
if (ptr) {
char *to = bufp;
while (maxlen > 1) { // Always leave room for a '\0'
char c = *ptr++;
if (c == '\0' || c == ' ' || c == '\t' || c == '\n') {
break;
}
*to++ = c;
maxlen--;
}
*to = '\0'; // Always nul-terminate
return bufp;
}
return NULL;
}
================================================
FILE: InterView-obj-isa-class/libmalloc-166.220.1/src/malloc_common.h
================================================
/*
* Copyright (c) 2018 Apple Inc. All rights reserved.
*
* @APPLE_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apple Public Source License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. Please obtain a copy of the License at
* http://www.opensource.apple.com/apsl/ and read it before using this
* file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPLE_LICENSE_HEADER_END@
*/
#ifndef __MALLOC_COMMON_H
#define __MALLOC_COMMON_H
MALLOC_NOEXPORT
const char *
malloc_common_strstr(const char *src, const char *target, size_t target_len);
MALLOC_NOEXPORT
long
malloc_common_convert_to_long(const char *ptr, const char **end_ptr);
MALLOC_NOEXPORT
const char *
malloc_common_value_for_key(const char *src, const char *key);
MALLOC_NOEXPORT
const char *
malloc_common_value_for_key_copy(const char *src, const char *key,
char *bufp, size_t maxlen);
#endif // __MALLOC_COMMON_H
================================================
FILE: InterView-obj-isa-class/libmalloc-166.220.1/src/malloc_printf.c
================================================
/*
* Copyright (c) 2018 Apple Inc. All rights reserved.
*
* @APPLE_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apple Public Source License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. Please obtain a copy of the License at
* http://www.opensource.apple.com/apsl/ and read it before using this
* file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPLE_LICENSE_HEADER_END@
*/
#include "internal.h"
/* global flag to suppress ASL logging e.g. for syslogd */
int _malloc_no_asl_log = 0;
typedef enum {
DEBUG_WRITE_NONE,
DEBUG_WRITE_ON_CRASH,
DEBUG_WRITE_ALWAYS,
} write_debug_mode_t;
static const char Malloc_Facility[] = "com.apple.Libsystem.malloc";
static int malloc_debug_file = STDERR_FILENO;
static write_debug_mode_t debug_mode = DEBUG_WRITE_NONE;
static boolean_t malloc_error_stop; // Stop when reporting error.
static boolean_t malloc_error_sleep; // Sleep after reporting error.
static const int default_sleep_time = 3600;
// Gets the default time to sleep for when reporting an error. Returns 0
// (meaning do not sleep) if malloc_error_sleep is 0 (that is, if sleeping on
// error is not configured).
MALLOC_INLINE MALLOC_ALWAYS_INLINE
static unsigned _malloc_default_debug_sleep_time()
{
return malloc_error_sleep ? default_sleep_time : 0;
}
#define WRITE_TO_DEBUG_FILE(flags) \
((debug_mode == DEBUG_WRITE_ALWAYS) || \
(debug_mode == DEBUG_WRITE_ON_CRASH && (flags & MALLOC_REPORT_CRASH)))
#define MALLOC_REPORT_LEVEL_MASK 0x0f
#pragma mark -
#pragma mark Configuration
void
malloc_print_configure(bool restricted)
{
char *flag = getenv("MallocDebugReport");
if (flag) {
if (!strcmp(flag, "stderr")) {
debug_mode = DEBUG_WRITE_ALWAYS;
} else if (!strcmp(flag, "crash")) {
debug_mode = DEBUG_WRITE_ON_CRASH;
} else if (!strcmp(flag, "none")) {
debug_mode = DEBUG_WRITE_NONE;
} else {
debug_mode = DEBUG_WRITE_ALWAYS;
malloc_printf("Unrecognized value for MallocDebugReport (%s) - using 'stderr'\n", flag);
}
} else {
// Default is to write to stderr only if it's a tty.
if (isatty(STDERR_FILENO)) {
debug_mode = DEBUG_WRITE_ALWAYS;
}
}
if (getenv("MallocErrorStop")) {
malloc_error_stop = TRUE;
}
if (getenv("MallocErrorSleep")) {
malloc_error_sleep = TRUE;
}
}
#pragma mark -
#pragma mark Low level debug output
/*
* The functions that follow use _simple_*printf. They deal with a
* subset of printf format specifiers and do not call malloc internally.
*/
static void
_malloc_put(uint32_t flags, const char *msg)
{
_SIMPLE_STRING b;
if ((b = _simple_salloc()) == NULL) {
if (WRITE_TO_DEBUG_FILE(flags)) {
if (!(flags & MALLOC_REPORT_NOPREFIX)) {
void *self = _os_tsd_get_direct(__TSD_THREAD_SELF);
_simple_dprintf(malloc_debug_file, "%s(%d,%p) malloc: ", getprogname(), getpid(), self);
}
write(malloc_debug_file, msg, strlen(msg));
}
return;
}
if (!(flags & MALLOC_REPORT_NOPREFIX)) {
void *self = _os_tsd_get_direct(__TSD_THREAD_SELF);
_simple_sprintf(b, "%s(%d,%p) malloc: ", getprogname(), getpid(), self);
}
_simple_sprintf(b, "%s", msg);
if (WRITE_TO_DEBUG_FILE(flags)) {
_simple_put(b, malloc_debug_file);
}
if (_malloc_no_asl_log & !(flags & MALLOC_REPORT_NOLOG)) {
_simple_asl_log(flags & MALLOC_REPORT_LEVEL_MASK, Malloc_Facility, _simple_string(b));
}
_simple_sfree(b);
}
#pragma mark -
#pragma mark High-Level Reporting Functions
MALLOC_NOINLINE void
malloc_vreport(uint32_t flags, unsigned sleep_time, const char *prefix_msg,
const void *prefix_arg, const char *fmt, va_list ap)
{
const char *crash_msg = NULL;
_SIMPLE_STRING b = NULL;
if ((b = _simple_salloc()) == NULL) {
if (WRITE_TO_DEBUG_FILE(flags)) {
if (!(flags & MALLOC_REPORT_NOPREFIX)) {
void *self = _os_tsd_get_direct(__TSD_THREAD_SELF);
_simple_dprintf(malloc_debug_file, "%s(%d,%p) malloc: ", getprogname(), getpid(), self);
}
if (prefix_msg) {
_simple_dprintf(malloc_debug_file, prefix_msg, prefix_arg);
}
_simple_vdprintf(malloc_debug_file, fmt, ap);
}
if (flags & MALLOC_REPORT_CRASH) {
crash_msg = fmt;
}
} else {
if (!(flags & MALLOC_REPORT_NOPREFIX)) {
void *self = _os_tsd_get_direct(__TSD_THREAD_SELF);
_simple_sprintf(b, "%s(%d,%p) malloc: ", getprogname(), getpid(), self);
}
if (prefix_msg) {
_simple_sprintf(b, prefix_msg, prefix_arg);
}
_simple_vsprintf(b, fmt, ap);
if (WRITE_TO_DEBUG_FILE(flags)) {
_simple_put(b, malloc_debug_file);
}
if (!_malloc_no_asl_log && !(flags & MALLOC_REPORT_NOLOG)) {
_simple_asl_log(flags & MALLOC_REPORT_LEVEL_MASK, Malloc_Facility, _simple_string(b));
}
if (flags & MALLOC_REPORT_CRASH) {
crash_msg = _simple_string(b);
} else {
_simple_sfree(b);
}
}
if (flags & (MALLOC_REPORT_DEBUG | MALLOC_REPORT_CRASH)) {
_malloc_put(flags, "*** set a breakpoint in malloc_error_break to debug\n");
malloc_error_break();
if (malloc_error_stop) {
_malloc_put(ASL_LEVEL_NOTICE, "*** sending SIGSTOP to help debug\n");
kill(getpid(), SIGSTOP);
} else if (sleep_time) {
_malloc_put(ASL_LEVEL_NOTICE, "*** sleeping to help debug\n");
sleep(sleep_time);
}
}
if (flags & MALLOC_REPORT_CRASH) {
_os_set_crash_log_message_dynamic(crash_msg);
abort();
}
}
MALLOC_NOEXPORT void
malloc_report(uint32_t flags, const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
malloc_vreport(flags, _malloc_default_debug_sleep_time(), NULL, NULL, fmt, ap);
va_end(ap);
}
#pragma mark -
#pragma mark Zone Error Reporing
void
malloc_zone_error(uint32_t flags, bool is_corruption, const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
uint32_t report_flags = MALLOC_REPORT_DEBUG | MALLOC_REPORT_NOLOG;
if ((is_corruption && (flags & MALLOC_ABORT_ON_CORRUPTION)) ||
(flags & MALLOC_ABORT_ON_ERROR)) {
report_flags = MALLOC_REPORT_CRASH;
}
malloc_vreport(report_flags | ASL_LEVEL_ERR, _malloc_default_debug_sleep_time(),
NULL, NULL, fmt, ap);
va_end(ap);
}
#pragma mark -
#pragma mark Malloc Output API.
// malloc_printf() needs to be retained and exported because it's API (defined
// in malloc/malloc.h). It's equivalent to calling malloc_report() with
// a flags value of ASL_LEVEL_ERR, so does not result in a crash or any prompts
// for diagnostics or breakpoints.
// Do not use in malloc code.
void
malloc_printf(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
malloc_vreport(ASL_LEVEL_ERR, 0, NULL, NULL, fmt, ap);
va_end(ap);
}
================================================
FILE: InterView-obj-isa-class/libmalloc-166.220.1/src/nano_malloc.c
================================================
/*
* Copyright (c) 1999, 2000, 2003, 2005, 2008, 2012 Apple Inc. All rights reserved.
*
* @APPLE_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apple Public Source License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. Please obtain a copy of the License at
* http://www.opensource.apple.com/apsl/ and read it before using this
* file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPLE_LICENSE_HEADER_END@
*/
#include "internal.h"
/* nano_malloc for 64bit ABI */
#if CONFIG_NANOZONE
/********************* PROTOTYPES ***********************/
static void nano_statistics(nanozone_t *nanozone, malloc_statistics_t *stats);
/********************* VERY LOW LEVEL UTILITIES ************************/
// msg prints after fmt, ...
static MALLOC_ALWAYS_INLINE unsigned int
nano_mag_index(const nanozone_t *nanozone)
{
if (os_likely(_os_cpu_number_override == -1)) {
return (_os_cpu_number() >> hyper_shift) % nano_common_max_magazines;
}
return (_os_cpu_number_override >> hyper_shift) % nano_common_max_magazines;
}
#if NANO_PREALLOCATE_BAND_VM
static boolean_t
nano_preallocate_band_vm(void)
{
nano_blk_addr_t u;
uintptr_t s, e;
u.fields.nano_signature = NANOZONE_SIGNATURE;
u.fields.nano_mag_index = 0;
u.fields.nano_band = 0;
u.fields.nano_slot = 0;
u.fields.nano_offset = 0;
s = u.addr; // start of first possible band
u.fields.nano_mag_index = (1 << NANO_MAG_BITS) - 1;
u.fields.nano_band = (1 << NANO_BAND_BITS) - 1;
e = u.addr + BAND_SIZE; // end of last possible band
return nano_common_allocate_vm_space(s, e - s);
}
#endif
/*
* We maintain separate free lists for each (quantized) size. The literature
* calls this the "segregated policy".
*/
static boolean_t
segregated_band_grow(nanozone_t *nanozone, nano_meta_admin_t pMeta, size_t slot_bytes, unsigned int mag_index)
{
nano_blk_addr_t u; // the compiler holds this in a register
uintptr_t p, s;
size_t watermark, hiwater;
if (0 == pMeta->slot_current_base_addr) { // First encounter?
u.fields.nano_signature = NANOZONE_SIGNATURE;
u.fields.nano_mag_index = mag_index;
u.fields.nano_band = 0;
u.fields.nano_slot = (slot_bytes >> SHIFT_NANO_QUANTUM) - 1;
u.fields.nano_offset = 0;
p = u.addr;
pMeta->slot_bytes = (unsigned int)slot_bytes;
pMeta->slot_objects = SLOT_IN_BAND_SIZE / slot_bytes;
} else {
p = pMeta->slot_current_base_addr + BAND_SIZE; // Growing, so stride ahead by BAND_SIZE
u.addr = (uint64_t)p;
if (0 == u.fields.nano_band) { // Did the band index wrap?
return FALSE;
}
assert(slot_bytes == pMeta->slot_bytes);
}
pMeta->slot_current_base_addr = p;
mach_vm_address_t vm_addr = p & ~((uintptr_t)(BAND_SIZE - 1)); // Address of the (2MB) band covering this (128KB) slot
if (nanozone->band_max_mapped_baseaddr[mag_index] < vm_addr) {
#if !NANO_PREALLOCATE_BAND_VM
// Obtain the next band to cover this slot
kern_return_t kr = mach_vm_map(mach_task_self(), &vm_addr, BAND_SIZE, 0, VM_MAKE_TAG(VM_MEMORY_MALLOC_NANO),
MEMORY_OBJECT_NULL, 0, FALSE, VM_PROT_DEFAULT, VM_PROT_ALL, VM_INHERIT_DEFAULT);
void *q = (void *)vm_addr;
if (kr || q != (void *)(p & ~((uintptr_t)(BAND_SIZE - 1)))) { // Must get exactly what we asked for
if (!kr) {
mach_vm_deallocate(mach_task_self(), vm_addr, BAND_SIZE);
}
return FALSE;
}
#endif
nanozone->band_max_mapped_baseaddr[mag_index] = vm_addr;
}
// Randomize the starting allocation from this slot (introduces 11 to 14 bits of entropy)
if (0 == pMeta->slot_objects_mapped) { // First encounter?
pMeta->slot_objects_skipped = (malloc_entropy[1] % (SLOT_IN_BAND_SIZE / slot_bytes));
pMeta->slot_bump_addr = p + (pMeta->slot_objects_skipped * slot_bytes);
} else {
pMeta->slot_bump_addr = p;
}
pMeta->slot_limit_addr = p + (SLOT_IN_BAND_SIZE / slot_bytes) * slot_bytes;
pMeta->slot_objects_mapped += (SLOT_IN_BAND_SIZE / slot_bytes);
u.fields.nano_signature = NANOZONE_SIGNATURE;
u.fields.nano_mag_index = mag_index;
u.fields.nano_band = 0;
u.fields.nano_slot = 0;
u.fields.nano_offset = 0;
s = u.addr; // Base for this core.
// Set the high water mark for this CPU's entire magazine, if this resupply raised it.
watermark = nanozone->core_mapped_size[mag_index];
hiwater = MAX(watermark, p - s + SLOT_IN_BAND_SIZE);
nanozone->core_mapped_size[mag_index] = hiwater;
return TRUE;
}
static inline unsigned long
divrem(unsigned long a, unsigned int b, unsigned int *remainder)
{
// Encapsulating the modulo and division in an in-lined function convinces the compiler
// to issue just a single divide instruction to obtain quotient and remainder. Go figure.
*remainder = a % b;
return a / b;
}
static MALLOC_INLINE void *
segregated_next_block(nanozone_t *nanozone, nano_meta_admin_t pMeta, size_t slot_bytes, unsigned int mag_index)
{
while (1) {
uintptr_t theLimit = pMeta->slot_limit_addr; // Capture the slot limit that bounds slot_bump_addr right now
uintptr_t b = OSAtomicAdd64Barrier(slot_bytes, (volatile int64_t *)&(pMeta->slot_bump_addr));
b -= slot_bytes; // Atomic op returned addr of *next* free block. Subtract to get addr for *this* allocation.
if (b < theLimit) { // Did we stay within the bound of the present slot allocation?
return (void *)b; // Yep, so the slot_bump_addr this thread incremented is good to go
} else {
if (pMeta->slot_exhausted) { // exhausted all the bands availble for this slot?
pMeta->slot_bump_addr = theLimit;
return 0; // We're toast
} else {
// One thread will grow the heap, others will see its been grown and retry allocation
_malloc_lock_lock(&nanozone->band_resupply_lock[mag_index]);
// re-check state now that we've taken the lock
if (pMeta->slot_exhausted) {
_malloc_lock_unlock(&nanozone->band_resupply_lock[mag_index]);
return 0; // Toast
} else if (b < pMeta->slot_limit_addr) {
_malloc_lock_unlock(&nanozone->band_resupply_lock[mag_index]);
continue; // ... the slot was successfully grown by first-taker (not us). Now try again.
} else if (segregated_band_grow(nanozone, pMeta, slot_bytes, mag_index)) {
_malloc_lock_unlock(&nanozone->band_resupply_lock[mag_index]);
continue; // ... the slot has been successfully grown by us. Now try again.
} else {
pMeta->slot_exhausted = TRUE;
pMeta->slot_bump_addr = theLimit;
_malloc_lock_unlock(&nanozone->band_resupply_lock[mag_index]);
return 0;
}
}
}
}
}
static MALLOC_INLINE size_t
segregated_size_to_fit(nanozone_t *nanozone, size_t size, size_t *pKey)
{
size_t k, slot_bytes;
if (0 == size) {
size = NANO_REGIME_QUANTA_SIZE; // Historical behavior
}
k = (size + NANO_REGIME_QUANTA_SIZE - 1) >> SHIFT_NANO_QUANTUM; // round up and shift for number of quanta
slot_bytes = k << SHIFT_NANO_QUANTUM; // multiply by power of two quanta size
*pKey = k - 1; // Zero-based!
return slot_bytes;
}
static MALLOC_INLINE index_t
offset_to_index(nanozone_t *nanozone, nano_meta_admin_t pMeta, uintptr_t offset)
{
unsigned int slot_bytes = pMeta->slot_bytes;
unsigned int slot_objects = pMeta->slot_objects; // SLOT_IN_BAND_SIZE / slot_bytes;
unsigned int rem;
unsigned long quo = divrem(offset, BAND_SIZE, &rem);
assert(0 == rem % slot_bytes || pMeta->slot_exhausted);
return (index_t)((quo * slot_objects) + (rem / slot_bytes));
}
static MALLOC_INLINE uintptr_t
index_to_offset(nanozone_t *nanozone, nano_meta_admin_t pMeta, index_t i)
{
unsigned int slot_bytes = pMeta->slot_bytes;
unsigned int slot_objects = pMeta->slot_objects; // SLOT_IN_BAND_SIZE / slot_bytes;
unsigned int rem;
unsigned long quo = divrem(i, slot_objects, &rem);
return (quo * BAND_SIZE) + (rem * slot_bytes);
}
static kern_return_t
segregated_in_use_enumerator(task_t task,
void *context,
unsigned type_mask,
nanozone_t *nanozone,
memory_reader_t reader,
vm_range_recorder_t recorder)
{
unsigned int mag_index, slot_key;
vm_range_t ptr_range;
vm_range_t buffer[MAX_RECORDER_BUFFER];
kern_return_t err;
unsigned count = 0;
for (mag_index = 0; mag_index < nano_common_max_magazines; mag_index++) {
uintptr_t clone_magazine; // magazine base for ourselves
nano_blk_addr_t p; // slot base for remote
uintptr_t clone_slot_base; // slot base for ourselves (tracks with "p")
// Establish p as base address for slot 0 in remote
p.fields.nano_signature = NANOZONE_SIGNATURE;
p.fields.nano_mag_index = mag_index;
p.fields.nano_band = 0;
p.fields.nano_slot = 0;
p.fields.nano_offset = 0;
if (type_mask & MALLOC_PTR_IN_USE_RANGE_TYPE) {
mach_vm_address_t vm_addr;
mach_vm_size_t alloc_size = nanozone->core_mapped_size[mag_index];
int alloc_flags = VM_FLAGS_ANYWHERE | VM_MAKE_TAG(VM_MEMORY_MALLOC);
vm_addr = vm_page_size;
kern_return_t kr = mach_vm_allocate(mach_task_self(), &vm_addr, alloc_size, alloc_flags);
if (kr) {
return kr;
}
clone_magazine = (uintptr_t)vm_addr;
clone_slot_base = clone_magazine; // base for slot 0 in this local magazine
} else {
clone_slot_base = clone_magazine = 0; // and won't be used in this loop
}
for (slot_key = 0; slot_key < SLOT_KEY_LIMIT; p.addr += SLOT_IN_BAND_SIZE, // Advance to next slot base for remote
clone_slot_base += SLOT_IN_BAND_SIZE, // Advance to next slot base for ourselves
slot_key++) {
nano_meta_admin_t pMeta = &(nanozone->meta_data[mag_index][slot_key]);
size_t slot_objects_mapped = pMeta->slot_objects_mapped; // capture this volatile count
if (0 == slot_objects_mapped) { // Nothing allocated in this magazine for this slot?
continue;
}
if (type_mask & MALLOC_ADMIN_REGION_RANGE_TYPE) {
/* do NOTHING as there is no distinct admin region */
}
if (type_mask & (MALLOC_PTR_REGION_RANGE_TYPE | MALLOC_ADMIN_REGION_RANGE_TYPE)) {
nano_blk_addr_t q = p;
uintptr_t skip_adj = index_to_offset(nanozone, pMeta, (index_t)pMeta->slot_objects_skipped);
while (q.addr < pMeta->slot_limit_addr) {
ptr_range.address = q.addr + skip_adj;
ptr_range.size = SLOT_IN_BAND_SIZE - skip_adj;
skip_adj = 0;
recorder(task, context, MALLOC_PTR_REGION_RANGE_TYPE, &ptr_range, 1);
q.addr += BAND_SIZE;
}
}
if (type_mask & MALLOC_PTR_IN_USE_RANGE_TYPE) {
nano_blk_addr_t q = p;
uintptr_t slot_band, clone_slot_band_base = clone_slot_base;
uintptr_t skip_adj = index_to_offset(nanozone, pMeta, (index_t)pMeta->slot_objects_skipped);
// Copy the bitarray_t denoting madvise()'d pages (if any) into *this* task's address space
bitarray_t madv_page_bitarray;
int log_page_count;
if (pMeta->slot_madvised_pages) {
log_page_count = pMeta->slot_madvised_log_page_count;
err = reader(task, (vm_address_t)(pMeta->slot_madvised_pages), bitarray_size(log_page_count),
(void **)&madv_page_bitarray);
if (err) {
return err;
}
} else {
madv_page_bitarray = NULL;
log_page_count = 0;
}
while (q.addr < pMeta->slot_limit_addr) {
// read slot in each remote band. Lands in some random location. Do not read
// parts of the slot that are in madvised pages.
if (!madv_page_bitarray) {
// Nothing madvised yet - read everything in one go.
size_t len = MIN(pMeta->slot_bump_addr - q.addr, SLOT_IN_BAND_SIZE) - skip_adj;
err = reader(task, (vm_address_t)(q.addr + skip_adj), len, (void **)&slot_band);
if (err) {
return err;
}
// Place the data just read in the correct position relative to the local magazine.
memcpy((void *)(clone_slot_band_base + skip_adj), (void *)slot_band, len);
} else {
// We madvised at least one page. Read only the pages that
// have not been madvised. If bitarray_t had operations
// like "get next bit set after a given bit" and "find
// next unset bit after a given bit", we could do this more
// efficiently but given that it doesn't, we have to walk
// through each page individually. In practice this is not
// much of an issue because this code is only used by
// sampling tools and the additional time required is not
// really noticeable.
size_t len = MIN(pMeta->slot_bump_addr - q.addr, SLOT_IN_BAND_SIZE) - skip_adj;
vm_address_t start_addr = (vm_address_t)(q.addr + skip_adj);
vm_address_t end_addr = (vm_address_t)(start_addr + len);
void *target_addr = (void *)(clone_slot_band_base + skip_adj);
for (vm_address_t addr = start_addr; addr < end_addr;) {
vm_address_t next_page_addr = trunc_page_kernel(addr + vm_kernel_page_size);
size_t read_size = MIN(len, next_page_addr - addr);
boolean_t madvised = false;
nano_blk_addr_t r;
r.addr = addr;
index_t pgnum = ((((unsigned)r.fields.nano_band) << NANO_OFFSET_BITS) | ((unsigned)r.fields.nano_offset)) >>
vm_kernel_page_shift;
unsigned int log_page_count = pMeta->slot_madvised_log_page_count;
madvised = (pgnum < (1 << log_page_count)) &&
bitarray_get(madv_page_bitarray, log_page_count, pgnum);
if (!madvised) {
// This is not an madvised page - grab the data.
err = reader(task, addr, read_size, (void **)&slot_band);
if (err) {
return err;
}
// Place the data just read in the correct position relative to the local magazine.
memcpy(target_addr, (void *)slot_band, read_size);
} else {
// This is an madvised page - there should be nothing in here that's
// on the freelist, so just write garbage to the target memory.
memset(target_addr, (char)0xee, read_size);
}
addr = next_page_addr;
target_addr += read_size;
len -= read_size;
}
}
// Simultaneously advance pointers in remote and ourselves to the next band.
q.addr += BAND_SIZE;
clone_slot_band_base += BAND_SIZE;
skip_adj = 0;
}
// Walk the slot free list and populate a bitarray_t
int log_size = 64 - __builtin_clzl(slot_objects_mapped);
bitarray_t slot_bitarray = bitarray_create(log_size);
if (!slot_bitarray) {
return errno;
}
chained_block_t t;
unsigned stoploss = (unsigned)slot_objects_mapped;
while ((t = OSAtomicDequeue(
&(pMeta->slot_LIFO), offsetof(struct chained_block_s, next) + (clone_slot_base - p.addr)))) {
if (0 == stoploss) {
malloc_report(ASL_LEVEL_ERR, "Free list walk in segregated_in_use_enumerator exceeded object count.\n");
break;
}
stoploss--;
uintptr_t offset = ((uintptr_t)t - p.addr); // offset from beginning of slot, task-independent
index_t block_index = offset_to_index(nanozone, pMeta, offset);
if (block_index < slot_objects_mapped) {
bitarray_set(slot_bitarray, log_size, block_index);
}
}
// N.B. pMeta->slot_LIFO in *this* task is now drained (remote free list has *not* been disturbed)
// Enumerate all the block indices issued to date, and report those not on the free list
index_t i;
for (i = (index_t)pMeta->slot_objects_skipped; i < slot_objects_mapped; ++i) {
uintptr_t block_offset = index_to_offset(nanozone, pMeta, i);
if (p.addr + block_offset >= pMeta->slot_bump_addr) {
break;
}
// blocks falling on madvise()'d pages are free! So not enumerated.
if (madv_page_bitarray) {
nano_blk_addr_t q;
index_t pgnum, pgnum_end;
q.addr = p.addr + block_offset;
pgnum = ((((unsigned)q.fields.nano_band) << NANO_OFFSET_BITS) | ((unsigned)q.fields.nano_offset)) >>
vm_kernel_page_shift;
q.addr += pMeta->slot_bytes - 1;
pgnum_end = ((((unsigned)q.fields.nano_band) << NANO_OFFSET_BITS) | ((unsigned)q.fields.nano_offset)) >>
vm_kernel_page_shift;
if (pgnum < (1 << log_page_count)) { // bounds check for bitarray_get()'s that follow
if (bitarray_get(madv_page_bitarray, log_page_count, pgnum) ||
bitarray_get(madv_page_bitarray, log_page_count, pgnum_end)) {
continue;
}
}
}
if (!bitarray_get(slot_bitarray, log_size, i)) {
buffer[count].address = p.addr + block_offset;
buffer[count].size = (slot_key + 1) << SHIFT_NANO_QUANTUM;
count++;
if (count >= MAX_RECORDER_BUFFER) {
recorder(task, context, MALLOC_PTR_IN_USE_RANGE_TYPE, buffer, count);
count = 0;
}
}
}
if (count) {
recorder(task, context, MALLOC_PTR_IN_USE_RANGE_TYPE, buffer, count);
count = 0;
}
free(slot_bitarray);
}
}
if (clone_magazine) {
mach_vm_address_t vm_addr = clone_magazine;
mach_vm_size_t alloc_size = nanozone->core_mapped_size[mag_index];
mach_vm_deallocate(mach_task_self(), vm_addr, alloc_size);
}
}
return 0;
}
/****************** nanozone methods **********************/
/*
* These methods are called with "ptr" known to possess the nano signature (from
* which we can additionally infer "ptr" is not NULL), and with "size" bounded to
* the extent of the nano allocation regime -- (0, 256].
*/
static MALLOC_INLINE MALLOC_UNUSED boolean_t
_nano_block_inuse_p(nanozone_t *nanozone, const void *ptr)
{
nano_blk_addr_t p; // happily, the compiler holds this in a register
nano_meta_admin_t pMeta;
chained_block_t head = NULL, tail = NULL, t;
boolean_t inuse = TRUE;
p.addr = (uint64_t)ptr; // place ptr on the dissecting table
pMeta = &(nanozone->meta_data[p.fields.nano_mag_index][p.fields.nano_slot]);
// pop elements off the free list all the while looking for ptr.
unsigned stoploss = (unsigned)pMeta->slot_objects_mapped;
while ((t = OSAtomicDequeue(&(pMeta->slot_LIFO), offsetof(struct chained_block_s, next)))) {
if (0 == stoploss) {
malloc_zone_error(nanozone->debug_flags, true,
"Free list walk for slot %p in _nano_block_inuse_p exceeded object count.\n",
(void *)&(pMeta->slot_LIFO));
}
stoploss--;
if (NULL == head) {
head = t;
} else {
tail->next = t;
}
tail = t;
if (ptr == t) {
inuse = FALSE;
break;
}
}
if (tail) {
tail->next = NULL;
}
// push the free list extracted above back onto the LIFO, all at once
if (head) {
OSAtomicEnqueue(&(pMeta->slot_LIFO), head, (uintptr_t)tail - (uintptr_t)head + offsetof(struct chained_block_s, next));
}
return inuse;
}
static MALLOC_INLINE size_t
__nano_vet_and_size_inner(nanozone_t *nanozone, const void *ptr, boolean_t inner)
{
// Extracts the size of the block in bytes. Checks for a plausible ptr.
nano_blk_addr_t p; // the compiler holds this in a register
nano_meta_admin_t pMeta;
p.addr = (uint64_t)ptr; // Begin the dissection of ptr
if (NANOZONE_SIGNATURE != p.fields.nano_signature) {
return 0;
}
if (nano_common_max_magazines <= p.fields.nano_mag_index) {
return 0;
}
if (!inner && p.fields.nano_offset & NANO_QUANTA_MASK) { // stray low-order bits?
return 0;
}
pMeta = &(nanozone->meta_data[p.fields.nano_mag_index][p.fields.nano_slot]);
if ((void *)(pMeta->slot_bump_addr) <= ptr) {
return 0; // Beyond what's ever been allocated!
}
if (!inner && ((p.fields.nano_offset % pMeta->slot_bytes) != 0)) {
return 0; // Not an exact multiple of the block size for this slot
}
return pMeta->slot_bytes;
}
static MALLOC_INLINE size_t
__nano_vet_and_size(nanozone_t *nanozone, const void *ptr)
{
return __nano_vet_and_size_inner(nanozone, ptr, false);
}
static MALLOC_ALWAYS_INLINE boolean_t
_nano_block_has_canary_value(nanozone_t *nanozone, const void *ptr)
{
return (((chained_block_t)ptr)->double_free_guard ^ nanozone->cookie)
== (uintptr_t)ptr;
}
static MALLOC_ALWAYS_INLINE void
_nano_block_set_canary_value(nanozone_t *nanozone, const void *ptr)
{
((chained_block_t)ptr)->double_free_guard =
((uintptr_t)ptr) ^ nanozone->cookie;
}
static MALLOC_INLINE size_t
_nano_vet_and_size_of_live(nanozone_t *nanozone, const void *ptr)
{
size_t size = __nano_vet_and_size(nanozone, ptr);
if (0 == size) { // ptr fails sanity check?
return 0;
}
// We have the invariant: If ptr is on a free list, then ptr->double_free_guard is the canary.
// So if ptr->double_free_guard is NOT the canary, then ptr is not on a free list, hence is live.
if (!_nano_block_has_canary_value(nanozone, ptr)) {
return size; // Common case: not on a free list, hence live. Return its size.
} else {
// confirm that ptr is live despite ptr->double_free_guard having the canary value
if (_nano_block_inuse_p(nanozone, ptr)) {
return size; // live block that exhibits canary
} else {
return 0; // ptr wasn't live after all (likely a double free)
}
}
}
static MALLOC_INLINE size_t
_nano_vet_and_size_of_free(nanozone_t *nanozone, const void *ptr)
{
size_t size = __nano_vet_and_size(nanozone, ptr);
if (0 == size) { // ptr fails sanity check?
return 0;
}
// ptr was just dequed from a free list, so ptr->double_free_guard must have the canary value.
if (_nano_block_has_canary_value(nanozone, ptr)) {
return size; // return the size of this well formed free block.
} else {
return 0; // Broken invariant: If ptr is on a free list, then ptr->double_free_guard is the canary. (likely use after free)
}
}
static void *
_nano_malloc_check_clear(nanozone_t *nanozone, size_t size, boolean_t cleared_requested)
{
MALLOC_TRACE(TRACE_nano_malloc, (uintptr_t)nanozone, size, cleared_requested, 0);
void *ptr;
size_t slot_key;
size_t slot_bytes = segregated_size_to_fit(nanozone, size, &slot_key); // Note slot_key is set here
mag_index_t mag_index = nano_mag_index(nanozone);
nano_meta_admin_t pMeta = &(nanozone->meta_data[mag_index][slot_key]);
ptr = OSAtomicDequeue(&(pMeta->slot_LIFO), offsetof(struct chained_block_s, next));
if (ptr) {
unsigned debug_flags = nanozone->debug_flags;
#if NANO_FREE_DEQUEUE_DILIGENCE
size_t gotSize;
nano_blk_addr_t p; // the compiler holds this in a register
p.addr = (uint64_t)ptr; // Begin the dissection of ptr
if (NANOZONE_SIGNATURE != p.fields.nano_signature) {
malloc_zone_error(debug_flags, true,
"Invalid signature for pointer %p dequeued from free list\n",
ptr);
}
if (mag_index != p.fields.nano_mag_index) {
malloc_zone_error(debug_flags, true,
"Mismatched magazine for pointer %p dequeued from free list\n",
ptr);
}
gotSize = _nano_vet_and_size_of_free(nanozone, ptr);
if (0 == gotSize) {
malloc_zone_error(debug_flags, true,
"Invalid pointer %p dequeued from free list\n", ptr);
}
if (gotSize != slot_bytes) {
malloc_zone_error(debug_flags, true,
"Mismatched size for pointer %p dequeued from free list\n",
ptr);
}
if (!_nano_block_has_canary_value(nanozone, ptr)) {
malloc_zone_error(debug_flags, true,
"Heap corruption detected, free list canary is damaged for %p\n"
"*** Incorrect guard value: %lu\n", ptr,
((chained_block_t)ptr)->double_free_guard);
}
#if defined(DEBUG)
void *next = (void *)(((chained_block_t)ptr)->next);
if (next) {
p.addr = (uint64_t)next; // Begin the dissection of next
if (NANOZONE_SIGNATURE != p.fields.nano_signature) {
malloc_zone_error(debug_flags, true,
"Invalid next signature for pointer %p dequeued from free "
"list, next = %p\n", ptr, "next");
}
if (mag_index != p.fields.nano_mag_index) {
malloc_zone_error(debug_flags, true,
"Mismatched next magazine for pointer %p dequeued from "
"free list, next = %p\n", ptr, next);
}
gotSize = _nano_vet_and_size_of_free(nanozone, next);
if (0 == gotSize) {
malloc_zone_error(debug_flags, true,
"Invalid next for pointer %p dequeued from free list, "
"next = %p\n", ptr, next);
}
if (gotSize != slot_bytes) {
malloc_zone_error(debug_flags, true,
"Mismatched next size for pointer %p dequeued from free "
"list, next = %p\n", ptr, next);
}
}
#endif /* DEBUG */
#endif /* NANO_FREE_DEQUEUE_DILIGENCE */
((chained_block_t)ptr)->double_free_guard = 0;
((chained_block_t)ptr)->next = NULL; // clear out next pointer to protect free list
} else {
ptr = segregated_next_block(nanozone, pMeta, slot_bytes, mag_index);
}
if (cleared_requested && ptr) {
memset(ptr, 0, slot_bytes); // TODO: Needs a memory barrier after memset to ensure zeroes land first?
}
return ptr;
}
static void *
_nano_malloc_check_scribble(nanozone_t *nanozone, size_t size)
{
void *ptr = _nano_malloc_check_clear(nanozone, size, 0);
/*
* Scribble on allocated memory when requested.
*/
if ((nanozone->debug_flags & MALLOC_DO_SCRIBBLE) && ptr && size) {
memset(ptr, SCRIBBLE_BYTE, _nano_vet_and_size_of_live(nanozone, ptr));
}
return ptr;
}
static MALLOC_INLINE size_t
_nano_size(nanozone_t *nanozone, const void *ptr)
{
return _nano_vet_and_size_of_live(nanozone, ptr);
}
static MALLOC_INLINE size_t
_nano_good_size(nanozone_t *nanozone, size_t size)
{
return (size <= NANO_REGIME_QUANTA_SIZE) ? NANO_REGIME_QUANTA_SIZE
: (((size + NANO_REGIME_QUANTA_SIZE - 1) >> SHIFT_NANO_QUANTUM) << SHIFT_NANO_QUANTUM);
}
static MALLOC_INLINE void _nano_free_trusted_size_check_scribble(nanozone_t *nanozone,
void *ptr,
size_t trusted_size,
boolean_t do_scribble) MALLOC_ALWAYS_INLINE;
static MALLOC_INLINE void
_nano_free_trusted_size_check_scribble(nanozone_t *nanozone, void *ptr, size_t trusted_size, boolean_t do_scribble)
{
if (trusted_size) {
nano_blk_addr_t p; // happily, the compiler holds this in a register
nano_meta_admin_t pMeta;
if (do_scribble) {
(void)memset(ptr, SCRABBLE_BYTE, trusted_size);
}
_nano_block_set_canary_value(nanozone, ptr);
p.addr = (uint64_t)ptr; // place ptr on the dissecting table
pMeta = &(nanozone->meta_data[p.fields.nano_mag_index][p.fields.nano_slot]);
OSAtomicEnqueue(&(pMeta->slot_LIFO), ptr, offsetof(struct chained_block_s, next));
} else {
malloc_zone_error(nanozone->debug_flags, true,
"Freeing unallocated pointer %p\n", ptr);
}
}
static MALLOC_INLINE void _nano_free_check_scribble(nanozone_t *nanozone, void *ptr, boolean_t do_scribble) MALLOC_ALWAYS_INLINE;
static MALLOC_INLINE void
_nano_free_check_scribble(nanozone_t *nanozone, void *ptr, boolean_t do_scribble)
{
_nano_free_trusted_size_check_scribble(nanozone, ptr, _nano_vet_and_size_of_live(nanozone, ptr), do_scribble);
}
static MALLOC_INLINE void *
_nano_realloc(nanozone_t *nanozone, void *ptr, size_t new_size)
{
size_t old_size, new_good_size, valid_size;
void *new_ptr;
if (FALSE && NULL == ptr) { // ptr has our_signature so can't be NULL, but if it were Posix sez ...
// If ptr is a null pointer, realloc() shall be equivalent to malloc() for the specified size.
return _nano_malloc_check_scribble(nanozone, new_size);
} else if (0 == new_size) {
// If size is 0 and ptr is not a null pointer, the object pointed to is freed.
_nano_free_check_scribble(nanozone, ptr, (nanozone->debug_flags & MALLOC_DO_SCRIBBLE));
// If size is 0, either a null pointer or a unique pointer that can be successfully passed
// to free() shall be returned.
return _nano_malloc_check_scribble(nanozone, 1);
}
old_size = _nano_vet_and_size_of_live(nanozone, ptr);
if (!old_size) {
malloc_zone_error(nanozone->debug_flags, true,
"pointer %p being reallocated was not allocated\n", ptr);
return NULL;
}
new_good_size = _nano_good_size(nanozone, new_size);
if (new_good_size > old_size) {
/* Must grow. FALL THROUGH to alloc/copy/free. */
} else if (new_good_size <= (old_size >> 1)) {
/* Serious shrinkage (more than half). FALL THROUGH to alloc/copy/free. */
} else {
/* Let's hang on to what we got. */
if (nanozone->debug_flags & MALLOC_DO_SCRIBBLE) {
memset(ptr + new_size, SCRIBBLE_BYTE, old_size - new_size);
}
return ptr;
}
/*
* Allocate a new buffer and copy.
*/
new_ptr = _nano_malloc_check_scribble(nanozone, new_good_size);
if (new_ptr == NULL) {
return NULL;
}
valid_size = MIN(old_size, new_good_size);
memcpy(new_ptr, ptr, valid_size);
_nano_free_check_scribble(nanozone, ptr, (nanozone->debug_flags & MALLOC_DO_SCRIBBLE));
return new_ptr;
}
static MALLOC_INLINE void
_nano_destroy(nanozone_t *nanozone)
{
/* Now destroy the separate nanozone region */
nano_common_deallocate_pages((void *)nanozone, NANOZONE_PAGED_SIZE,
nanozone->debug_flags);
}
/****************** nanozone dispatch **********************/
static void *
nano_malloc(nanozone_t *nanozone, size_t size)
{
if (size <= NANO_MAX_SIZE) {
void *p = _nano_malloc_check_clear(nanozone, size, 0);
if (p) {
return p;
} else {
/* FALLTHROUGH to helper zone */
}
}
malloc_zone_t *zone = (malloc_zone_t *)(nanozone->helper_zone);
return zone->malloc(zone, size);
}
static void *
nano_forked_malloc(nanozone_t *nanozone, size_t size)
{
malloc_zone_t *zone = (malloc_zone_t *)(nanozone->helper_zone);
return zone->malloc(zone, size);
}
static void *
nano_malloc_scribble(nanozone_t *nanozone, size_t size)
{
if (size <= NANO_MAX_SIZE) {
void *ptr = _nano_malloc_check_clear(nanozone, size, 0);
if (ptr) {
/*
* Scribble on allocated memory.
*/
if (size) {
memset(ptr, SCRIBBLE_BYTE, _nano_vet_and_size_of_live(nanozone, ptr));
}
return ptr;
} else {
/* FALLTHROUGH to helper zone */
}
}
malloc_zone_t *zone = (malloc_zone_t *)(nanozone->helper_zone);
return zone->malloc(zone, size);
}
static void *
nano_calloc(nanozone_t *nanozone, size_t num_items, size_t size)
{
size_t total_bytes;
if (calloc_get_size(num_items, size, 0, &total_bytes)) {
return NULL;
}
if (total_bytes <= NANO_MAX_SIZE) {
void *p = _nano_malloc_check_clear(nanozone, total_bytes, 1);
if (p) {
return p;
} else {
/* FALLTHROUGH to helper zone */
}
}
malloc_zone_t *zone = (malloc_zone_t *)(nanozone->helper_zone);
return zone->calloc(zone, 1, total_bytes);
}
static void *
nano_forked_calloc(nanozone_t *nanozone, size_t num_items, size_t size)
{
malloc_zone_t *zone = (malloc_zone_t *)(nanozone->helper_zone);
return zone->calloc(zone, num_items, size);
}
static void *
nano_valloc(nanozone_t *nanozone, size_t size)
{
malloc_zone_t *zone = (malloc_zone_t *)(nanozone->helper_zone);
return zone->valloc(zone, size);
}
static MALLOC_INLINE void
__nano_free_definite_size(nanozone_t *nanozone, void *ptr, size_t size, boolean_t do_scribble) MALLOC_ALWAYS_INLINE;
static MALLOC_INLINE void
__nano_free_definite_size(nanozone_t *nanozone, void *ptr, size_t size, boolean_t do_scribble)
{
nano_blk_addr_t p; // happily, the compiler holds this in a register
p.addr = (uint64_t)ptr; // place ptr on the dissecting table
if (NANOZONE_SIGNATURE == p.fields.nano_signature) {
if (size == ((p.fields.nano_slot + 1) << SHIFT_NANO_QUANTUM)) { // "Trust but verify."
_nano_free_trusted_size_check_scribble(nanozone, ptr, size, do_scribble);
return;
} else {
malloc_zone_error(nanozone->debug_flags, true,
"Freeing pointer %p whose size was misdeclared\n", ptr);
}
} else {
malloc_zone_t *zone = (malloc_zone_t *)(nanozone->helper_zone);
zone->free_definite_size(zone, ptr, size);
return;
}
/* NOTREACHED */
}
static void
nano_free_definite_size(nanozone_t *nanozone, void *ptr, size_t size)
{
__nano_free_definite_size(nanozone, ptr, size, 0);
}
static void
nano_free_definite_size_scribble(nanozone_t *nanozone, void *ptr, size_t size)
{
__nano_free_definite_size(nanozone, ptr, size, 1);
}
static MALLOC_INLINE void __nano_free(nanozone_t *nanozone, void *ptr, boolean_t do_scribble) MALLOC_ALWAYS_INLINE;
static MALLOC_INLINE void
__nano_free(nanozone_t *nanozone, void *ptr, boolean_t do_scribble)
{
MALLOC_TRACE(TRACE_nano_free, (uintptr_t)nanozone, (uintptr_t)ptr, do_scribble, 0);
if (!ptr) {
return; // Protect against malloc_zone_free() passing NULL.
}
//